From 5dcb76bcc5ac3ec2fa040854d755960ee570f161 Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Tue, 17 Nov 2026 04:19:07 +0000 Subject: [PATCH 01/31] Bring online playtest improvements onto the latest contributor source --- CHANGELOG.md | 20 + VERSION | 2 +- architecture/online-identity-inputs.json | 12 +- docs/PUBLIC-1.0.16-playtest.1-NOTES.txt | 22 + docs/notes/2026-11-10-issue-45-wayland.md | 71 +++ .../notes/2026-11-14-network-host-handover.md | 53 ++ docs/notes/2026-11-14-playtest-notes.txt | 36 ++ ...26-11-14-steam-deck-online-frame-pacing.md | 111 +++++ docs/notes/2026-11-17-upstream-integration.md | 69 +++ .../1.0.16-playtest.1/RELEASE-NOTES.txt | 22 + docs/releases/1.0.16-playtest.1/UPDATER.txt | 5 + packaging/linux/dkr-port.appdata.xml | 1 + runtime-recomp/cmake/PeerRelay.cmake | 22 + runtime-recomp/src/game/custom_records.hpp | 1 + .../src/game/display_settings/ui.inl | 3 +- runtime-recomp/src/game/game_main.cpp | 37 +- .../src/game/mods/online_mod_sync.cpp | 5 + .../src/game/mods/online_mod_sync.hpp | 2 + .../src/game/netplay/direct_session.cpp | 95 +++- .../src/game/netplay/direct_session.hpp | 2 + .../netplay/experimental_presentation.cpp | 32 +- .../netplay/experimental_presentation.hpp | 3 +- .../src/game/netplay/experimental_runtime.cpp | 42 +- .../game/netplay/peer_relay/live_datagram.cpp | 6 +- .../game/netplay/peer_relay/owner_glue.cpp | 7 +- .../game/netplay/peer_relay/owner_glue.hpp | 3 +- .../src/game/netplay/peer_relay/transport.cpp | 22 +- .../src/game/netplay/quick_join_transport.cpp | 74 ++- .../netplay/session_links/handover_pump.inl | 298 ++++++++++++ .../session_links/handover_service.inl | 409 ++++++++++++++++ .../netplay/session_links/menu_control.hpp | 33 ++ .../game/netplay/session_links/mod_host.inl | 66 +++ .../netplay/session_links/mod_owner_ui.inl | 36 ++ .../netplay/session_links/owner_service.inl | 264 ++++++++++ .../src/game/netplay/session_links/policy.cpp | 270 +++++++++++ .../src/game/netplay/session_links/policy.hpp | 108 +++++ .../netplay/session_links/qualification.hpp | 106 ++++ .../netplay/session_links/quick_join_api.inl | 166 +++++++ .../session_links/quick_join_state.inl | 3 + .../game/netplay/session_links/registry.cpp | 99 ++++ .../game/netplay/session_links/registry.hpp | 15 + .../src/game/netplay/session_links/state.hpp | 183 +++++++ .../game/netplay/session_links/transfer.hpp | 35 ++ .../game/netplay/session_links/transport.cpp | 73 +++ .../game/netplay/session_links/transport.hpp | 28 ++ runtime-recomp/src/game/online_directory.cpp | 41 +- runtime-recomp/src/game/online_directory.hpp | 1 + .../correction_lifetime.hpp | 42 ++ .../host_settings_service.inl | 5 +- .../src/game/online_stability/live_delay.cpp | 25 +- .../src/game/online_stability/live_delay.hpp | 3 + .../src/game/online_stability/lobby_ui.inl | 151 ++++++ .../src/game/online_stability/replay_cost.hpp | 34 ++ runtime-recomp/src/game/owner_pump.inl | 27 +- runtime-recomp/src/game/party.cpp | 14 + runtime-recomp/src/game/party.hpp | 1 + runtime-recomp/src/game/party_link.cpp | 61 ++- runtime-recomp/src/game/party_link.hpp | 6 + runtime-recomp/src/game/party_runtime.cpp | 32 +- runtime-recomp/src/game/record_store.inl | 12 + .../src/game/runtime_online_mods_ui.inl | 3 + runtime-recomp/src/game/start_gate.hpp | 5 + runtime-recomp/tests/build_tooling_tests.py | 34 ++ .../tests/display_session_tests.cpp | 4 + runtime-recomp/tests/dkr_json_schema_tests.py | 2 +- .../tests/online_mod_sync_tests.cpp | 68 ++- runtime-recomp/tests/online_picture_tests.cpp | 87 ++++ .../tests/online_stability_tests.cpp | 73 +++ .../tests/peer_relay_glue_tests.cpp | 6 + .../tests/regression_harness_tests.py | 11 +- runtime-recomp/tests/release_tools_tests.py | 11 +- .../tests/replay_probe/probe_driver.cpp | 42 +- runtime-recomp/tests/run_private_fixture.py | 8 +- .../tests/session_links_native_tests.cpp | 455 ++++++++++++++++++ .../tests/session_links_policy_tests.cpp | 213 ++++++++ runtime-recomp/tests/tidy_changed_tests.py | 7 + scripts/package_ios.py | 5 + scripts/port_check.py | 4 +- scripts/release/package_release.py | 16 +- scripts/tests/test_package_ios.py | 9 + scripts/tidy_changed.py | 7 +- scripts/validate_release_metadata.py | 2 +- services/online-directory/api/library_api.mjs | 2 +- services/online-directory/build.py | 7 +- services/online-directory/directory.mjs | 63 +++ services/online-directory/tests/runtime.cjs | 52 ++ 86 files changed, 4487 insertions(+), 136 deletions(-) create mode 100644 docs/PUBLIC-1.0.16-playtest.1-NOTES.txt create mode 100644 docs/notes/2026-11-10-issue-45-wayland.md create mode 100644 docs/notes/2026-11-14-network-host-handover.md create mode 100644 docs/notes/2026-11-14-playtest-notes.txt create mode 100644 docs/notes/2026-11-14-steam-deck-online-frame-pacing.md create mode 100644 docs/notes/2026-11-17-upstream-integration.md create mode 100644 docs/releases/1.0.16-playtest.1/RELEASE-NOTES.txt create mode 100644 docs/releases/1.0.16-playtest.1/UPDATER.txt create mode 100644 runtime-recomp/src/game/netplay/session_links/handover_pump.inl create mode 100644 runtime-recomp/src/game/netplay/session_links/handover_service.inl create mode 100644 runtime-recomp/src/game/netplay/session_links/menu_control.hpp create mode 100644 runtime-recomp/src/game/netplay/session_links/mod_host.inl create mode 100644 runtime-recomp/src/game/netplay/session_links/mod_owner_ui.inl create mode 100644 runtime-recomp/src/game/netplay/session_links/owner_service.inl create mode 100644 runtime-recomp/src/game/netplay/session_links/policy.cpp create mode 100644 runtime-recomp/src/game/netplay/session_links/policy.hpp create mode 100644 runtime-recomp/src/game/netplay/session_links/qualification.hpp create mode 100644 runtime-recomp/src/game/netplay/session_links/quick_join_api.inl create mode 100644 runtime-recomp/src/game/netplay/session_links/quick_join_state.inl create mode 100644 runtime-recomp/src/game/netplay/session_links/registry.cpp create mode 100644 runtime-recomp/src/game/netplay/session_links/registry.hpp create mode 100644 runtime-recomp/src/game/netplay/session_links/state.hpp create mode 100644 runtime-recomp/src/game/netplay/session_links/transfer.hpp create mode 100644 runtime-recomp/src/game/netplay/session_links/transport.cpp create mode 100644 runtime-recomp/src/game/netplay/session_links/transport.hpp create mode 100644 runtime-recomp/src/game/online_presentation/correction_lifetime.hpp create mode 100644 runtime-recomp/src/game/online_stability/replay_cost.hpp create mode 100644 runtime-recomp/tests/session_links_native_tests.cpp create mode 100644 runtime-recomp/tests/session_links_policy_tests.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index d4ef89a4..19bcea03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # DKR-R changelog +## 1.0.16 playtest 1 — 2026-11-17 + +- Bring our online work onto the latest contributor code. Keep the upstream + source layout, cross-platform compatibility checks, relay support, shutdown + fixes, settings work and Track Lab improvements. +- Send racers' inputs directly to one another when that route is available. + Keep the host route for recovery. Spectators stay outside the racing input + path, including in a full lobby with four racers and eight spectators. +- Show a suggested host from measured connections. Let the host offer ownership + to another member without closing the lobby. The new host must accept, and + every member must finish the transfer before the next game starts. Controller + seats and the original online save owner stay the same. +- Keep usable pictures during ordinary rollback corrections and measure input + lateness against forward progress. Auto delay also takes replay cost into + account, to avoid repeatedly removing the delay that a slower machine needs. +- Mark window-matched resolution as recommended. Keep explicit rendering + preferences and the existing launcher layout. +- Keep the Linux Wayland fallback and package closure checks. Fix Windows test + portability for long cache paths, separate temporary drives and path separators. + ## 1.0.15 — 2026-11-08 - Replace the added Player Select footer with native colourful names for selected diff --git a/VERSION b/VERSION index a9707166..0f210008 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.0.15 +1.0.16-playtest.1 diff --git a/architecture/online-identity-inputs.json b/architecture/online-identity-inputs.json index 4d80cedb..fcec2e5a 100644 --- a/architecture/online-identity-inputs.json +++ b/architecture/online-identity-inputs.json @@ -85,8 +85,8 @@ "runtime-recomp/src/game/netplay/experimental_performance.hpp": "0f802347c393412e7a99003f60625f52de3ec62fd3f88c6e4601185c9c597bfa", "runtime-recomp/src/game/netplay/experimental_present_gate.cpp": "11fff06bd17bc8069274e090de7f6a005972bd5c909f09d75b121e8c109f98bf", "runtime-recomp/src/game/netplay/experimental_present_gate.hpp": "11ef80fb42f85f6d95601273352014bb123ba6cd6e122e3adbc6a9e6cf0edc46", - "runtime-recomp/src/game/netplay/experimental_presentation.cpp": "66c93e26eedbea8826cb15c063b72f5bc507cfe3686736ff4e0c7cec27f4438e", - "runtime-recomp/src/game/netplay/experimental_presentation.hpp": "dbd26ed84319448054da4be0f49c277391dee838b40e67f5654f54eb9066c955", + "runtime-recomp/src/game/netplay/experimental_presentation.cpp": "43db182ddc6589b23af5582778acf57463d85e647144705f7c89f2a6675401d1", + "runtime-recomp/src/game/netplay/experimental_presentation.hpp": "6752a3cbfd1b6a4635b06377deabb2ffca70500dbc5f567fd244a74c517af6d6", "runtime-recomp/src/game/netplay/experimental_process.cpp": "ebbfba4aa3f500c843dcedacb2f15bf605b8c8abe4e9f83224ab5aff6b549a31", "runtime-recomp/src/game/netplay/experimental_process.hpp": "5db5d2d4b04db0c08d3f102d41d0843866d6171ca3c76b7dcf95a841a9b44da9", "runtime-recomp/src/game/netplay/experimental_pump.cpp": "6bda29d224d5030344475a8127b9061d4801e125a5f2c1dde99d86748e716130", @@ -94,7 +94,7 @@ "runtime-recomp/src/game/netplay/experimental_race_frontend.cpp": "6223a033bcbbc51417d850e6d1acb359d2d987b172daf32de28b615e44228b61", "runtime-recomp/src/game/netplay/experimental_rollback.cpp": "b429eb1fc93a3e2b0454790cdec3c81f8ed29572f57cb4b56abf0e78c96ca738", "runtime-recomp/src/game/netplay/experimental_rollback.hpp": "23656d21cb5cde5cd336e69e9a7c9569799b06756f70bbde15c8078bef4809fe", - "runtime-recomp/src/game/netplay/experimental_runtime.cpp": "7784b8e94652c749fa3f0762a4e4c513ca0e773b8508802e65879caa713ccb00", + "runtime-recomp/src/game/netplay/experimental_runtime.cpp": "55920d9beaa803801c417bfe64bfe741b118a0a65dd7551e68972bea098a4fae", "runtime-recomp/src/game/netplay/experimental_runtime.hpp": "e2bd584098e45af7e67b6198f650d18a204d3b57be6bbe3214639e3abe73598c", "runtime-recomp/src/game/netplay/experimental_runtime_admission.hpp": "6e2e1b60086bebaccdb50089ea5dce8c40b572fab6912b2562acc7e81211f527", "runtime-recomp/src/game/netplay/experimental_runtime_presence.hpp": "0c14e186cd618998e0902f28a1e88be53d4601bd2ffee1cbc5ba19cc5bb851ba", @@ -106,7 +106,7 @@ "runtime-recomp/src/game/netplay/runtime_state.hpp": "9d54de461b5220b246763d5f0b044cfc7ed845da4c8ad1ba521eb6f3cb905b07", "runtime-recomp/src/game/netplay/setup_policy.hpp": "c2630dbc6a3950e947d0ce380d1be42c71568a864bb7dbef42703df5f1cf31fc", "runtime-recomp/src/game/party_release.hpp": "0f364dfe23f991223547679858ca894056974d891040527a2c6e0ea6065e3676", - "runtime-recomp/src/game/party_runtime.cpp": "0eb45b3483dabebd0e0ae6b98e6fed67ae8593dd5bfdaa40ed899db38893a8fc", + "runtime-recomp/src/game/party_runtime.cpp": "20e2818b9ebf10e3f828f702caaf54849688208dcdbcc933dfe565bad85bc15d", "runtime-recomp/src/game/party_runtime.hpp": "f71d5b873f71fd24000c43833171967fa40860468f2ee6f50367ac1c1c60b404", "runtime-recomp/src/game/runtime_save_routing.cpp": "837917b9ede8d0f9cadd86edaa325da50c7e88a6c34242758f18228112737890", "runtime-recomp/src/game/runtime_save_routing.hpp": "cb3ae802050f29e38def0d42c60c01345be2cc46a515a95e9c50d49a06cf6879", @@ -148,7 +148,7 @@ "runtime-recomp/tests/replay_probe/probe_bridge.h": "893652acb1858fd5a93e17f1a8dd720e6634b532212096b123b87ddd34f91c03", "runtime-recomp/tests/replay_probe/probe_component.c": "022cc844ac8a5879168e82dd79035c98ebe2203eadabf4268cff0559c58979c3", "runtime-recomp/tests/replay_probe/probe_component.h": "bd1919c9701e6aeba909af45e17d89e7e4275d846f66a9df806857b7e2460009", - "runtime-recomp/tests/replay_probe/probe_driver.cpp": "bc027b5aa7fbe082d863be3ace06fc7e89fac76639919abe6d2b546565fabeaa", + "runtime-recomp/tests/replay_probe/probe_driver.cpp": "a4940cce66a8fee0169797085c2fc0d391211c8035d4cfa11f68b3c5832b5288", "runtime-recomp/tests/replay_probe/probe_driver.hpp": "630fb96603ea6f9d3abc2a6554c63d1acbaa43b5dc741e767df06a2d154660f6", "runtime-recomp/tests/replay_probe/probe_eeprom.cpp": "b3596a6727f899508d111e5a73acf755822d42e6901b7d89a95c546ae708d89b", "runtime-recomp/tests/replay_probe/probe_input.c": "40eef7c9fdd82da5e1247711b9cca1ef38852176681b5e3addb819eca1d7ced7", @@ -207,6 +207,6 @@ }, "last_update": { "identity_changed": false, - "reason": "PR #93 port: auto-boot presentation admission sizes host vectors only; levelLinks hook is funcs-only (owned hook set identical), a no-op online and on retail maps; boss and hub .dkrmap levels are offline only" + "reason": "Retain v1.0.15 simulation and wire identities. Optional authenticated session-links v2 extensions add duplicate immutable racer delivery and consented waiting-lobby handover among capable peers; default menu ownership remains port zero and older peers retain host delivery. Correction eligibility and Auto delay accounting affect presentation and scheduling only. Upstream architecture-free launch hashes, state cross-checks, GuestCallContext and reliable checkpoint semantics are retained." } } diff --git a/docs/PUBLIC-1.0.16-playtest.1-NOTES.txt b/docs/PUBLIC-1.0.16-playtest.1-NOTES.txt new file mode 100644 index 00000000..e51857c0 --- /dev/null +++ b/docs/PUBLIC-1.0.16-playtest.1-NOTES.txt @@ -0,0 +1,22 @@ +DKR-R v1.0.16 playtest 1 + +This is a testing build. It brings our latest online work together with the +changes that have landed from other contributors since v1.0.15. + +Racers can send inputs directly to each other, while the host still handles +recovery. Spectators stay outside that input path. You can also offer the host +role to someone else in the lobby without making everyone leave and rejoin. +They have to accept, and the transfer has to finish before starting the game. +Your controller seat and the owner of the online save stay the same. + +There are further changes to online picture handling and Auto input delay to +help with the frame dips we saw on Steam Deck. Please test both a normal session +and a full lobby, and keep the runtime logs if anything goes wrong. + +The launcher layout is unchanged. The contributor work on cross-platform play, +relay connections, shutdown, Track Lab and the rest of the folded source tree +is included. This does not add a new hosted relay service. + +Use matching builds for testing. No release or service update has been published +as part of preparing these files. See docs/notes/2026-11-17-upstream-integration.md +for the exact source and verification record. diff --git a/docs/notes/2026-11-10-issue-45-wayland.md b/docs/notes/2026-11-10-issue-45-wayland.md new file mode 100644 index 00000000..fb0a2e73 --- /dev/null +++ b/docs/notes/2026-11-10-issue-45-wayland.md @@ -0,0 +1,71 @@ +# Issue #45: missing Wayland client in Linux AppImages + +The original report concerns v1.0.4 on Batocera 43.1. Its follow-up confirms +v1.0.5-beta.12 also fails and that adding Ubuntu Noble's Wayland client resolves +startup. Inspection of the retained published v1.0.15 payload shows the same +omission: cursor/EGL libraries are present, but `libwayland-client.so.0` is not. + +The existing dependency audit classifies the client as a host library, following +the upstream AppImage exclusion list. That makes the missing library an admitted +host requirement rather than a failed packaging check. Upstream excludes it +because an older bundled client can conflict with newer Mesa drivers. Simply +putting an old client into the global library directory would trade one failure +for another. + +The fix installs a private fallback in `usr/lib/dkr-r/wayland-fallback`, refreshes +cursor/EGL from the matching target sysroot and includes the Wayland copyright +notice. The AppRun shell entry probes the cursor dependency with the normal +search path. A resolvable host client stays in use; otherwise the private client +is added. No graphics driver is bundled or replaced. The isolated file-dialog +helper keeps its existing host desktop stack and environment policy. +Only the fallback directory is added to the inherited runtime search path when +needed. Its own RUNPATH resolves bundled dependencies, so this does not expose +every AppImage library globally to host graphics drivers. + +Both the generic shell packager and retained release package pipeline invoke +the shared first-party installer. Static inspection requires the private client, +correct ELF architecture/SONAME, matching AppRun and copyright notice, and rejects +a global client override. Cross packaging requires a target sysroot; it cannot +silently copy the build host's x64 client into an ARM64 package. + +Contributor regressions cover the old omission, architecture/SONAME failures, +sysroot selection, notices, global overrides and escaping source links. Runtime +qualification uses an isolated filesystem containing the actual packaged game +and only explicitly selected host libraries. Its missing-client and host-present +cases distinguish a working fallback from a test accidentally using the build +machine's library. This is not physical Batocera or ARM graphics acceptance. + +The v1.0.15 tag, published downloads and signed updater files remain unchanged. +Local test AppImages reuse the released runtime; only packaging changes. The +fix needs a future release version when distributed publicly. No GitHub issue +comment or closure is part of this local investigation. + +Verification on 10 November 2026: + +- Both final x64 and ARM64 AppImages passed archive readback and the complete + ELF dependency audit. Their game executables and online identities match the + released v1.0.15 payload byte for byte. Dependency floors remain glibc 2.38 + and GLIBCXX 3.4.32. +- In an isolated Linux filesystem without a host Wayland client, the old package + fails with the reported loader error. The corrected AppRun passes the runtime's + Controller Pak round-trip/backup test using the private fallback. Restoring + the host client makes it take priority. Loader traces confirm both choices. +- The final x64 AppImage also extracted and launched itself in that filesystem, + with a real mounted proc filesystem, and passed the same test. ARM64's actual + image payload passed through QEMU with eager symbol binding and the private + fallback. These are loader/CPU checks, not physical GPU acceptance. +- The final x64 image passed US v1.0 manual-launch and US v1.1 skip-launcher + startup checks under Xvfb/software Vulkan, including the manual fade handover. +- Windows host checks passed 173/173. Linux passed 172/173; the regression + harness hit its existing subprocess timeout on the mounted Windows checkout. + Its unchanged 25 cases passed on native Linux storage. The final 12 Wayland + tooling cases passed separately on both Windows and Linux. +- Guard, tooling, metadata, source-asset scans and the applicable pre-commit + checks passed. No protected/generated sources or dependency submodules changed. + +The reporter's Batocera hardware still needs to confirm startup and rendering +with the fixed image before calling that platform accepted. + +Sources: [issue and confirmed workaround](https://github.com/ThatGuyMcd/DKR-R/issues/45#issuecomment-5984441330), +[upstream exclusion and Mesa rationale](https://github.com/AppImageCommunity/pkg2appimage/blob/master/excludelist), +[upstream fallback precedent](https://github.com/musescore/MuseScore/pull/24128). diff --git a/docs/notes/2026-11-14-network-host-handover.md b/docs/notes/2026-11-14-network-host-handover.md new file mode 100644 index 00000000..060de2a2 --- /dev/null +++ b/docs/notes/2026-11-14-network-host-handover.md @@ -0,0 +1,53 @@ +# Networking and host handover work + +This work is on `codex/network-host-handover`, above the issue 45 packaging repair. It has not been published or deployed. + +The implementation adds authenticated direct input paths between racing members. The current host still relays and repairs inputs, and remains the authority for membership, scene transitions and confirmation. Eight spectators remain outside the four-racer input mesh. Introduced peer keys grant input delivery privileges only; the receiver still checks the current controller lease and input owner. + +Planned host handover runs in the waiting lobby, including after returning from a race. It does not provide crash failover or move authority during a live simulation. The candidate must accept. All connected members must prepare the same session snapshot and prove their successor routes before commit. Controller ports remain unchanged. Lost commit acknowledgements hold race start; they never restore the former host after commit. The former host coordinates release and retransmission until everyone has installed the new authority. + +The original persistent save owner stays separate from the networking host. A successor receives the shared online EEPROM, controller Paks and custom records in memory and retains a match-scoped online session bank. It must not replace its personal Adventure or unrelated online save. Pair-key inventory is sent privately to the successor; other members receive only its digest. + +The candidate checks its own local consent, even when acceptance is relayed by the former host. Departed-member pair keys are wiped before constructing another transfer inventory, and clients release their retired introduced routes. Pair encryption counters survive role changes. Private direct-connect invitations are not copied into the directory-code field. + +Connection probes use the realtime input lane. After installing the new role, the successor clears old heartbeat measurements and proves fresh round trips to every racer before acknowledging activation. The old coordinator publishes completion only after that proof. This retains the existing race-start connection check and avoids announcing readiness before an immediate Start request can pass it. + +Optional racer-route recovery is separate from the authority connection. An introduced racer cannot replace the host bootstrap or invitation code, and a failing optional route cannot trigger the client's host reconnect. Host changes also need the manual clock reference and shared menu input policy to follow the successor's existing controller port. Ordinary racing input keeps the original controller assignments. A spectator host leaves the game's shared menu controller on the first racing port. + +Public lobby handover also requires an atomic ownership operation on the existing directory. Its account and instance checks must agree with the already admitted native successor. The existing room ID and membership survive the transfer. The directory feature is capability gated, so an older deployed service cannot silently produce a partially transferred public lobby. No new player software or third-party service is required. The matching existing backend update still needs deployment review after preparation and testing. + +## Validation + +- Local exported API, service binding and SQLite Durable Object: 205 checks passed, including four racing slots and eight spectator slots, matching candidate consent, another instance of the same account, altered state digests, repeated commit acknowledgement, sequential handovers, a spectator accepting hosting and the former host leaving. +- The ROM-free host build completed. The full Linux CTest run passed 173 of 174 tests; its regression harness timed out. The same regression harness passed on Windows with native CMake and Git (25 tests, one skipped). Four targeted networking CTests passed after restoring the frozen interfaces. +- Native Windows and Linux tests passed sequential transfers to a racer and then a spectator, with four racing slots and eight spectators, unchanged controller leases and unchanged save ownership. The delayed variant passed with 375 ms delivery delay in each direction, jitter, 200 ms spikes, periodic realtime packet loss and a 128 KiB Pak preserved at every member. These tests use actual DirectSession sockets and encryption with synthetic save data. They do not run a guest ROM. The successor must pass the existing start connection check immediately when completion is reported. The tests then run the actual synchronized countdown after injecting a stale pre-roster start receipt. +- The pattern guard and checksum-pinned-file checks passed. The full Windows guard/tooling suite passed after selecting native CMake and Git. The installed pre-commit checks passed. +- Windows and Linux game builds passed. The disposable-profile qualification hook waits for all twelve members, transfers to the racer on controller port one and starts the normal game afterward. Early actual Quick Join runs exposed missing route aliases, stale start receipts and an immediate Start request racing the new host's heartbeat proof. Each now has a regression test. Normal UI sessions still require the candidate's consent. + +These are local test results, not physical Steam Deck or intercontinental gameplay measurements. Actual nonempty-mod handover followed by another mod download still needs a guest-game check; native transfer tests cover verified cache promotion separately. + +### Actual game qualification + +- R17, paced Quick Join admission: twelve real game processes, four racers and eight spectators, transferred hosting to the second racing port and entered a normal race. All twelve exited successfully. All four racers recorded zero race input-wait time. +- R17, paced admission with 375 ms common receive delay in each direction, 25 ms jitter, 200 ms spikes and periodic realtime/replica loss: all twelve completed. A slow spectator also received 1,000 ms delay and 1,000 ms spikes. Racer input waits were limited to the first roughly 75 race frames; their total measured waits were 35.739, 96.532, 0 and 497.598 ms. These are application-delivery impairments on every route, not measured WAN RTT or a wire shaper. +- R20, simultaneous admission after separating authority recovery: all twelve real Quick Join game processes completed host transfer and racing. All four racers recorded zero race input waits. Its old spectator counter included menu simulation, so it is not used as proof of sustained race playback. +- R21/R23 failed before commit and preserved the original host. Tracing found that an authorized Quick Join reservation could exist without a peer object; renaming that route for the successor then failed. R24 repairs the reservation alias and its release bookkeeping. Native coverage checks alias collisions and repeated reservation release. +- R24 then exposed a descriptor accepted before the new roster arrived. Repeating the descriptor did not refresh the client's cached roster receipt. R26 revalidates the receipt when roster or shared-save identity changes; its native test completes the real countdown after injecting that order of events. +- R27 removes unsent obsolete observer checkpoint chunks and confirmed-frame batches when replacing a spectator transfer. It preserves current-transfer data, other recipients, other games, exact input repair and live controls. Spectators also retain an already approved checkpoint decode when receiving the matching release, instead of requesting the same baseline again. +- R27 Windows burst-admission stress: all twelve processes exited zero after handover and a normal race. Each racer had 375 ms common receive delay, 25 ms jitter, 200 ms spike windows and periodic realtime/replica loss. One spectator had 1,000 ms delay and 1,000 ms spikes. Racing input-wait totals were 0 / 101.286 / 0 / 0 ms; the only nonzero sample was the first race interval, around frame 84. Every later reported interval was zero for all four racers. This is not an absolute zero-wait claim. +- The R27 spectator acceptance check requires at least 300 additional simulated frames between two samples from the actual race epoch. All eight passed the Windows stress run; their observed race deltas ranged from 623 to 800 frames. Earlier runs checked a cumulative menu-plus-race counter and are excluded from this stronger result. +- R27 mixed-platform functional run: a Linux AppImage succeeded the original Windows host, all twelve completed handover, all four entered a race, and all eight spectators advanced by 1,303-1,627 additional race frames. The first report parser rejected an interleaved log token; the saved logs were recovered with numeric-field parsing. All workers recorded clean retirement. The repeat passed with all twelve exit codes zero, no reported rollback failures, and spectator race deltas of 1,298-1,629 frames. Exit codes are saved before parsing the runtime logs. +- The latest full ROM-free Linux host run again passed 173/174 checks, with two child commands timing out in the regression harness under WSL/NTFS. The unchanged regression harness passed its 25 cases (one skipped) on native Windows. Windows guard/tooling and installed pre-commit checks passed. The host-port menu routing policy tests passed for all four possible host ports, shared menus, ordinary racing, unassigned ports and nested construction contexts. + +The mixed-platform run is functional evidence only. WSL's monotonic clock ran about nine percent away from its raw clock and native Windows time. This Codex process had no Administrator token, so the previously authorized VM time-service lease could not be used. No time service was changed or paused. Linux rendering in this fixture uses Xvfb/lavapipe, not Steam Deck hardware. Its timing and frame-rate totals are excluded. + +Both R27 packages passed the full source/binary release packaging audit. Their rollback build IDs agree on Windows and Linux for both supported ROM revisions. They are private test artifacts, not published releases: + +- Windows ZIP SHA-256: `04efe5372c3e09a4dc1b3f3a7a188e32098a038b5a21b4f712de546e2100c7aa`. +- Linux AppImage SHA-256: `2f006943fd61bc3316671ed19fbf1ba2ea35366e4f5525ef7cc6796131e91632`. + +The directory bundle and its 205 checks are prepared locally. It has not been deployed. Public-lobby ownership transfer remains safely unavailable on the old directory until the matching backend is deployed. Private Quick Join handover is covered by the actual-game tests above. No repository changes have been pushed. + +## Steam Deck follow-up + +The source review, captured Deck logs and follow-up repair are recorded in `2026-11-14-steam-deck-online-frame-pacing.md`. The logs show expensive correction and frequent queue rejection with zero recorded input waits. The approved repair is being qualified as v1.0.16 Playtest 1. GPU duration and device power/temperature were not captured, so physical Deck acceptance is still required. diff --git a/docs/notes/2026-11-14-playtest-notes.txt b/docs/notes/2026-11-14-playtest-notes.txt new file mode 100644 index 00000000..895f395d --- /dev/null +++ b/docs/notes/2026-11-14-playtest-notes.txt @@ -0,0 +1,36 @@ +DKR-R v1.0.16 Playtest 1 + +This is a test build for the next online update. Please use the same playtest +on every PC and Steam Deck in the lobby. + +ONLINE FRAME PACING +- Fixed Auto measuring late input against a rewound frame during rollback. +- Auto now considers the cost of correction bursts as well as sustained CPU + load, with separate thresholds for increasing and reducing protective delay. +- Ordinary corrections can keep queued pictures from before the changed frame. + Changed pictures still get rejected, and scene/resource changes keep their + full retirement and GPU completion checks. +- Automatic - match window is marked as the recommended resolution choice. + Existing settings and explicitly selected higher resolutions are preserved. + +HOST HANDOVER AND FULL LOBBIES +- Adds authenticated direct input connections between racers. The host's + existing relay and input repair remain available. +- Hosts can offer ownership to another member while waiting in the lobby, + including after returning from a race. The new host must accept. +- Controller slots and the original online save owner survive the transfer. +- Spectators stay outside the racing input mesh and use buffered playback. +- Fixes route reservations, starting-grid acknowledgements and redundant + spectator checkpoint requests found during full-lobby testing. + +TESTING +This is a playtest, not the final v1.0.16 release. Physical Steam Deck frame +pacing still needs checking with the same mods and settings as the affected +session. Internet latency still affects response time; this build cannot +guarantee zero waits or 60 FPS under every connection and graphics setting. + +Private Quick Join host transfer is included. Public-lobby host transfer also +needs the matching update on the existing lobby directory. That backend update +has not been deployed as part of this local playtest build. + +Nothing in this package includes a game ROM. Existing personal saves are kept. diff --git a/docs/notes/2026-11-14-steam-deck-online-frame-pacing.md b/docs/notes/2026-11-14-steam-deck-online-frame-pacing.md new file mode 100644 index 00000000..a1e40a15 --- /dev/null +++ b/docs/notes/2026-11-14-steam-deck-online-frame-pacing.md @@ -0,0 +1,111 @@ +# Steam Deck online frame-rate investigation + +The report concerns public v1.0.15: a Steam Deck host showed severe frame-rate dips, but audio continued and there were no reported waits for inputs. The owner subsequently confirmed two racers and no spectators. Spectator streaming and twelve-member lobby load therefore cannot explain that particular session. The supplied logs establish the view, resolution and active mods below; power settings remain unconfirmed. This is separate from the earlier standalone launcher software-renderer repair. + +## What the current code does + +The party simulation runs at 30 Hz. The renderer can produce interpolated pictures at a higher rate. Those are different clocks and budgets; a 30 Hz simulation result does not prove 60 FPS presentation. + +Late input can trigger correction without exhausting prediction history. In that case the input-wait counter can stay at zero. The driver restores a retained state, replays the affected ticks, and captures and hashes a checkpoint after each executed tick. The current ordinary vanilla state is about 17 MB. The direct snapshot pool already avoids a second full-state copy and paged-store assembly when the state fits its bounded memory budget. + +`PartyRuntime` publishes a replacement picture only when correction has finished and no scene boundary is pending. This prevents exposing a half-corrected timeline. A correction taking several expensive ticks can therefore hold the last completed image while confirmed audio keeps playing. The renderer's immutable snapshot leases already let ordinary correction proceed without waiting for a GPU drain; that earlier repair must not be removed. Water asset residency also already distinguishes real asset-scene changes from rollback identity, so a correction is not by itself proof that water assets are being rebuilt. + +Replay is serviced in bounded slices, at most four pulses or four milliseconds between ticks. A single guest tick is not preemptible, so a four-millisecond slice limit does not guarantee a four-millisecond maximum correction cost. Automatic input delay already receives executed-step and replay-cost reports. It raises protective input lead under sustained replay pressure and keeps each published input immutable. Increasing lead trades some response latency for less speculative work; increasing prediction history alone does not remove replay cost. + +## Local evidence + +The R27 full-lobby Windows stress run completed with four racers and eight spectators after host transfer. It recorded only one nonzero race input-wait interval, totaling 101.286 ms on one racer; all later reported intervals were zero for every racer. This establishes that the network-wait problem and visible frame pacing must be assessed separately. It does not establish a 60 FPS lock. + +A separate four-process Windows run used the audited R27 runtime, fresh disposable profiles, the actual game, four racers, no spectators, the Modern Vulkan renderer, a requested 60 Hz presentation rate, Automatic input delay and a fourteen-frame prediction window. All four processes exited zero and entered the race. All four reported zero racing network-input wait. The host's last race performance sample recorded 143 corrections and 259 replayed ticks over roughly 1,849 simulation frames, with a largest correction of four frames. The other racers recorded 8-11 corrections. + +One settled host interval recorded approximately 2.36 ms for state capture, 1.79 ms for hashing and 6.83 ms for the guest/audio tick, before the separate picture-publication and renderer work. The party pacing sample recorded an 11.38 ms mean executed-step cost and a 20.39 ms maximum. These are wall-time stage observations with four applications sharing one Windows PC, not Steam Deck measurements or independent additive GPU timings. + +The existing timing reporter can run on both rendering and simulation threads, with separate report windows over shared counters. Their windows overlap. Summing their interval counts would double-count work, so the investigation uses individual intervals rather than claiming aggregate FPS or a CPU percentage from their sum. Presentation intervals are CPU observations and are not a GPU timestamp or physical scanout measurement. + +An additional four-player impaired-delivery profiling attempt did not enter gameplay. Its disposable CLI automation requested Start before all two-way connection proofs were ready, then kept its local `started` flag set after the asynchronous start request was rejected. It never retried. The normal launcher permits another Start attempt. This attempt exited with code 5 and is excluded from frame-rate evidence; it does not demonstrate a gameplay slowdown or override the successful full-lobby handover runs. The automation needs retry-aware state handling before using that entry point for further startup impairment comparisons. + +The mixed Windows/AppImage test is functional evidence only. Its Linux VM clock is skewed and its renderer explicitly uses lavapipe. Neither its FPS nor its software rasterizer says anything about the physical Deck's active driver. + +## Two-racer follow-up + +After the owner confirmed two racers and no spectators, two additional ordinary-startup runs used the same audited R27 Windows binary, one host and one client, no spectators, no mods, Modern Vulkan, My racer fullscreen, a requested 60 Hz refresh rate and a fourteen-frame prediction window. Both members entered a normal race and exited zero in each run, with no reported rollback failure. This is two applications on one Windows GPU, not a physical Deck test or a fresh measurement of the public v1.0.15 binary. + +With normal delivery, both racers recorded zero network-input waiting. The host's final performance report recorded 161 corrections, 480 replayed ticks and a largest correction of four frames over roughly 2,417 race frames. The client recorded zero corrections and zero replayed ticks. Nevertheless, that client's last rendering report had long intervals: approximately 29.89 ms mean display-list processing wall time and 21.59 ms mean presented-frame interval, with a 100 ms histogram upper bound at the 99th percentile. Processing wall time can include waiting and backpressure; it is not a GPU-duration measurement. This is reason to inspect rendering and presentation independently of rollback, not proof of the Deck's bottleneck. + +The impaired run applied 375 ms receive delay, 25 ms jitter, 200 ms spike windows and periodic realtime/replica loss to each member. Logged receive instrumentation verified that the delay was active. These are application-delivery impairments, not measured internet RTT. Host/client whole-race input-wait totals were 753.841 / 607.391 ms, so this run does not meet an absolute zero-wait criterion. The final reported pacing samples had zero input wait. The final host/client correction counts were 155 / 146, with 765 / 405 replayed ticks and largest corrections of 14 / 5 frames. Automatic local input lead ended at 7 / 9 frames. That is a material response-latency trade-off and does not justify increasing delay blindly. + +The impaired run's last presentation intervals averaged about 17.9 / 17.7 ms, with 99th-percentile histogram upper bounds of 66 / 50 ms. These are not locked-60 results. The normal and impaired runs did not follow identical camera positions and trajectories, and share one PC's GPU, so their renderer means must not be presented as an improvement caused by adding latency. + +An earlier two-player warm-up experiment temporarily paused one thread of its own disposable host process while connecting the client. It did not reach a race and recorded a heartbeat disconnect, so it is excluded. Its thread was resumed and both processes retired. The accepted runs above use ordinary process startup without thread suspension. Logs and per-process exit codes for all attempts are retained outside the repository. + +## Captured Deck session, received 14 November + +The owner supplied `dkrr steamdeck logs.zip`. The latest `runtime.log` contains launcher activity only. The last online session is in `runtime-previous.log`, with a ZIP modification time of 14 November at 00:35:58. It contains one two-racer host runtime and multiple scene epochs/races. Earlier history files include older sessions and are not substituted for this one. The archive and extracted raw logs are retained outside the repository. + +The ELF build ID is `5c2394d9a4e89c26d560172e700b2682c6f50217`. It matches the retained public v1.0.15 Linux executable exactly by GNU build ID. Gamescope reports an old `1.0.14` AppImage filename, but the version banner and binary identity identify v1.0.15; the filename alone is not evidence of an old runtime. + +The session used the actual AMD Custom GPU 0405 / RADV VANGOGH Vulkan driver. The standalone launcher also reported accelerated OpenGL with the AMD rasterizer. This was not the earlier launcher software-renderer problem. Gamescope and RT64 requested a 60 Hz presentation rate. + +The internal render size was 1920x1200 and the output window 1600x1000, with scale 5 and downsample 1. Most racing pictures used My racer fullscreen; menus and shared scenes used the shared view. Mods were active, including three code packages. The serialized world was 18,119,892 bytes, and the log confirms the direct full-image checkpoint store was already active: `direct=1`, retaining 398,638,296 bytes within a 398,703,160-byte budget. Reimplementing that earlier optimization would not repair this session. + +There are 393 pacing samples and 388 presentation timing samples. Every pacing sample records zero network-input waiting, zero presentation-drain waiting and zero measured long scheduling gap. That supports the owner's report of no input-wait pauses. It does not prove that the GPU was idle or that the device was never throttled; no GPU-duration, clock, power or temperature trace was supplied. + +Host route RTT samples after owned startup have a median of 142 ms, a 95th percentile of 148 ms and a maximum of 477 ms. The nearby route sample during the worst rendering interval was 141 ms with empty realtime, authority, control and checkpoint queues. That interval does not look like an exhausted input window or a bulk download saturating the link. + +One particularly bad five-second interval in epoch 107 contains: + +| Measurement | Recorded value | +| --- | --- | +| Network-input waiting | 0 microseconds | +| Executed ticks, including replay | 253 | +| Replayed ticks | 104 | +| Time executing replayed ticks | 1,753.443 ms | +| Mean executed-step cost | 13.529 ms | +| Reported presentation rate | 29.77 FPS over 5.005 seconds | +| 95th/99th presentation interval bucket | Above 100 ms | +| Newly tagged pictures | 158 | +| Accepted queued pictures | 76 | +| Rejected queued pictures | 82 | + +The last three numbers are differences between consecutive reports at raw log lines 16604 and 16671. In the renderer report, the field named `retired` is `present_gate::Statistics::rejected`. It counts queue-admission rejection, not ordinary successful resource reclamation. Rejections can include generation retirement, expired leases or slot-identity mismatch; the log does not distinguish all causes. The code's conservative generation invalidation during correction is a concrete candidate for avoidable rejection. It must not be bypassed wholesale. + +The very large percentile number `18446744073709551615` is the histogram's overflow bucket. It means an interval exceeded 100 ms, not an actual multi-century pause. Across the session, 128 presentation reports have a 99th-percentile overflow bucket; nine also have a 95th-percentile overflow bucket. These are repeated visible hitches, not just a low overall average. Other samples, including the final shared scene, return to approximately 60 reported FPS. + +The pacing samples record about 206.6 seconds of replay execution and 10,553 replayed ticks over the session. Five-second samples straddle scene boundaries, so those interval sums should not be equated exactly with each epoch's last cumulative counter. Detailed per-stage rollback profiling was not enabled. The evidence identifies expensive correction and interrupted presentation, but does not split the Deck's replay cost into guest execution, capture and hashing or establish the GPU's share of every slow frame. + +## Reproduced Auto measurement problem + +The source review found a specific timing error. `LiveDelay::pulse` retains a monotonic `clock_frontier_` but also updates `frame_` to the current execution cursor. That cursor moves backwards during correction. `LiveDelay::arrival` measures lateness against `frame_`, so fresh input arriving during replay can be classified as on time even though it is behind the furthest simulated frame. + +A small external diagnostic linked the actual `DKROnlineStabilityCore` and reproduced the calculation without a ROM or networking: + +1. Execute to frame 100 in one epoch. +2. Rewind execution to frame 90. +3. Receive twelve fresh latest-input samples for frame 95. +4. Read the ordinary delay report. + +The report gives twelve samples, zero lateness and zero owner lateness at the 90th percentile. Against the retained live frontier, these samples are five frames late. This is a reproduced undercount in the current calculation. The device log does not expose the individual replay cursor and arrival pair, so it does not prove how many of its samples were affected. + +The current policy also primarily responds to sustained work ratios and reduces protective lead after a short stable interval. The device trace repeatedly shows low/zero configured lead and frequent corrections without input waits. Correcting the lateness reference is a more precise first step than increasing everyone's delay or just increasing prediction history. + +## Repair and validation plan + +1. Measure fresh input lateness against the monotonic simulation frontier in the same epoch. Keep exact historical repairs excluded from fresh jitter measurements. Add regression coverage for input arriving during a rewind, future input, returning to frame zero in a new scene, duplicate/repair batches and per-owner isolation. Do not change packet layout, final input values or the shared simulation clock. +2. Review correction retirement separately from real scene/resource retirement. An immutable queued picture strictly before the first corrected frame can still describe an unaffected past frame. Explore retaining that eligibility while rejecting the corrected frame and all later affected pictures. Preserve full invalidation for resource/scene changes, exact queue-slot identities, GPU completion fences and bounded snapshot storage. Add delayed-consumer and repeated-rewind tests before changing eligibility. +3. Measure correction burst duration as well as sustained replay load before tuning Auto. Aim to prevent repeated catch-up bursts with the smallest necessary per-owner lead. Avoid learning false stability while the driver is rewound, and avoid oscillating between zero lead and repeated corrections. Do not merely redraw a frozen image more often to inflate FPS counters. +4. Verify the Gamescope/window resolution choice and the automatic render-size policy. The observed internal size has 44 percent more pixels than the output window. Offer a clear device/window-native automatic choice while preserving explicitly selected supersampling resolutions. Resolution is an additional load factor here, not a proven sole cause. +5. Requalify unchanged simulation/save results, correction boundaries, two-racer play, four racers plus eight spectators, late packets/loss and the renderer's actual presentation intervals. Build audited Windows and AppImage test packages. The physical Deck must then verify the improvement with the same mods and graphics settings; local desktop/WSL results cannot certify a 60 FPS lock on it. + +The initial investigation reproduced the timing error without changing production behavior. R27 remains the earlier network/host-handover baseline. The approved repair is prepared separately as v1.0.16 Playtest 1. + +## Approved repair + +Fresh arrivals and delay reports now use the monotonic frontier, including while execution is rewound. Exact historical repairs and local input remain excluded from delivery jitter. The existing 96-byte delay protocol is unchanged. Regression checks cover rewind, future input, a new epoch, per-owner samples and repair exclusion. + +Auto estimates forward tick cost from existing reports after subtracting measured replay work. Repeated expensive corrections can raise an owner's protective lead even below the old sustained-work threshold. Separate growth and reduction thresholds retain that protection while correction remains costly. Quiet or inexpensive replay does not by itself request extra delay. This estimates correction pressure; it does not measure GPU duration or promise a fixed rendering rate. + +Ordinary independent CPU correction retains an immutable picture only if it precedes every subsequent affected frame. Invalidated pictures cannot become eligible again after another rewind. Scene/resource retirement still invalidates every picture. Exact queue identities, previously admitted GPU work, epoch retirement and the four-image memory limit remain enforced. The new lifetime records hold weak references, never more image RAM, and do not acquire a last strong reference under the domain lock. + +The presentation implementation is integrated through the existing checked Patch Pipeline and authored `online_presentation` module. The checksum-pinned presentation base files and retained capsule remain unchanged. A staged production-library test passed 48 queue-picture checks, including a consumer delayed at actual admission, repeated corrections, slot-identity rejection and full retirement. Final packaged-game results are separate from this test. + +Window-matched automatic resolution is labelled as recommended. Existing settings and explicit higher resolutions are preserved. Display policy checks cover the captured 1600x1000 output, its old 1920x1200 integer render size, and a native 1280x800 window. diff --git a/docs/notes/2026-11-17-upstream-integration.md b/docs/notes/2026-11-17-upstream-integration.md new file mode 100644 index 00000000..995db5f2 --- /dev/null +++ b/docs/notes/2026-11-17-upstream-integration.md @@ -0,0 +1,69 @@ +# Contributor sync and v1.0.16 playtest + +The integration starts from upstream `adfd02e377d3eba6736a40682d5e3e95422b3560`, +including the 131 commits after the public v1.0.15 tag. The earlier local work +was based on `f1c0c3581e517c720499b15444a0139dc6ea1b70` and an uncommitted tree. +Both are retained in the recovery bundle, along with an exact authored-file +archive. Restoring that backup reproduced all 3,071 recorded file hashes. + +## How the work was combined + +Upstream is the base. None of its commits were reverted or replaced with an +older release layer. Our additional changes live in the maintained first-party +modules, with the old networking changes ported by behavior rather than by +copying an old DirectSession over the new one. + +- Keep upstream's cross-architecture manifest matching, state checks, named + guest hooks, symbol tables and GuestCallContext conversions. +- Keep its relay owner/glue, reliable checkpoint path, deferred session logs, + close/wakeup fixes, TLS changes, settings codecs and Track Lab work. +- Add authenticated direct racer inputs, consented waiting-lobby host handover, + cached-mod promotion and transfer of verified session state. Preserve the + local architecture, original save owner and existing controller leases. +- Version the optional session-links capability. Older local playtests retain + ordinary host delivery and cannot begin the newer handover. +- Keep usable immutable pictures during ordinary correction, without relaxing + scene/resource retirement or the four-image memory limit. Keep replay-cost + protection in Auto delay and use forward progress for late-input samples. +- Keep the existing launcher layout. The rejected resolution-dependent redesign + has not been restored. +- Keep the maintained Wayland wrapper and architecture/closure checks. The old + helper and old first-party build layers have not been restored. + +The shipped v1.0.15 rollback identities remain unchanged. The compatibility +reason is recorded by `scripts/identity_guard.py` in the ordinary input record. +New optional control extensions do not change the simulation input format; +default menu ownership is unchanged. A transferred menu owner is agreed by all +capable members before a new owned world is constructed. + +## Verification and build notes + +The initial combined Windows host run passed all 214 tests. A separate native +four-racer/eight-spectator test passed sequential handovers to a racer and a +spectator, including mixed-architecture metadata, preserved seats/save owner, +and a synchronized start. Its impaired run added 375 ms one-way delay, 25 ms +jitter, 200 ms spikes and loss of every 97th disposable packet, and also passed. + +Local directory tests passed 95 ordinary-lobby and 101 running-spectator checks. +The native/profile integration passed 107 checks with synthetic identities. +These tests used no deployed service or real player credentials. + +Windows portability fixes retain the checks: use extended paths for deep cache +fixtures, keep relative executable tests on the interpreter's drive, normalize +schema paths, compare review text with universal newlines, encode the iOS bundle +entry point's executable mode explicitly, and use native paths for the local +esbuild and CMake command construction. + +The clean Linux baseline and the first combined Linux run both exposed the +same regression-harness timeout. Git status on the NTFS source checkout took +23.14 seconds; the test's outer timeout is 20 seconds. Linux verification moves +to a normal Linux checkout instead of increasing or disabling that deadline. + +Windows and Linux game builds, prepared-input verification, actual-game tests +and final package scans are still being completed. This note will be updated +with their results before the testing packages are handed over. + +Nothing has been pushed, published, signed for the updater or deployed. Public +directory ownership transfer remains capability-gated until its matching +service update is deliberately deployed. Physical Steam Deck acceptance is +separate from local Windows/WSL functional testing. diff --git a/docs/releases/1.0.16-playtest.1/RELEASE-NOTES.txt b/docs/releases/1.0.16-playtest.1/RELEASE-NOTES.txt new file mode 100644 index 00000000..e51857c0 --- /dev/null +++ b/docs/releases/1.0.16-playtest.1/RELEASE-NOTES.txt @@ -0,0 +1,22 @@ +DKR-R v1.0.16 playtest 1 + +This is a testing build. It brings our latest online work together with the +changes that have landed from other contributors since v1.0.15. + +Racers can send inputs directly to each other, while the host still handles +recovery. Spectators stay outside that input path. You can also offer the host +role to someone else in the lobby without making everyone leave and rejoin. +They have to accept, and the transfer has to finish before starting the game. +Your controller seat and the owner of the online save stay the same. + +There are further changes to online picture handling and Auto input delay to +help with the frame dips we saw on Steam Deck. Please test both a normal session +and a full lobby, and keep the runtime logs if anything goes wrong. + +The launcher layout is unchanged. The contributor work on cross-platform play, +relay connections, shutdown, Track Lab and the rest of the folded source tree +is included. This does not add a new hosted relay service. + +Use matching builds for testing. No release or service update has been published +as part of preparing these files. See docs/notes/2026-11-17-upstream-integration.md +for the exact source and verification record. diff --git a/docs/releases/1.0.16-playtest.1/UPDATER.txt b/docs/releases/1.0.16-playtest.1/UPDATER.txt new file mode 100644 index 00000000..a4e07721 --- /dev/null +++ b/docs/releases/1.0.16-playtest.1/UPDATER.txt @@ -0,0 +1,5 @@ +DKR-R v1.0.16 playtest 1 + +Testing build with the latest contributor changes, direct racer input links, +host handover and further online frame pacing work. Keep your runtime logs if +you run into a problem. This build has not been published to the updater. diff --git a/packaging/linux/dkr-port.appdata.xml b/packaging/linux/dkr-port.appdata.xml index 79d0310b..e9263c4a 100644 --- a/packaging/linux/dkr-port.appdata.xml +++ b/packaging/linux/dkr-port.appdata.xml @@ -16,6 +16,7 @@ +

Combined upstream integration playtest with direct racer inputs, consented host handover, retained save ownership and lower-cost online picture correction.

Improved online input recovery, lower-cost checkpoints, buffered spectators and live host settings. Added storage cleanup, a pinned Play button, native custom-character names, isolated file dialogs and better crash diagnostics.

Online responsiveness and sync presentation, a unified launcher and overlay, analogue driving, controller feedback, automatic seasons, languages, display options and opt-in crash reporting.

Analogue acceleration and braking, standalone online Look behind and full CRT controls in Graphics.

diff --git a/runtime-recomp/cmake/PeerRelay.cmake b/runtime-recomp/cmake/PeerRelay.cmake index a0d94e9b..3c84a3eb 100644 --- a/runtime-recomp/cmake/PeerRelay.cmake +++ b/runtime-recomp/cmake/PeerRelay.cmake @@ -29,6 +29,9 @@ function(dkr_add_peer_relay) "${_dkr_relay_root}/src/game/netplay/peer_relay/live_datagram.cpp" "${_dkr_relay_root}/src/game/netplay/peer_relay/owner_glue.cpp" "${_dkr_relay_root}/src/game/netplay/peer_relay/transport.cpp" + "${_dkr_relay_root}/src/game/netplay/session_links/policy.cpp" + "${_dkr_relay_root}/src/game/netplay/session_links/registry.cpp" + "${_dkr_relay_root}/src/game/netplay/session_links/transport.cpp" ) target_compile_features(DKRPeerRelay PUBLIC cxx_std_20) target_include_directories(DKRPeerRelay PUBLIC "${_dkr_relay_root}/src/game") @@ -46,6 +49,25 @@ function(dkr_add_peer_relay) target_include_directories(DKRPeerRelay PRIVATE "${DKR_DEPENDENCIES_DIR}/libdatachannel/deps/json/include") endif() endif() + if(NOT TARGET DKRSessionLinksPolicyTests) + add_executable(DKRSessionLinksPolicyTests "${_dkr_relay_root}/tests/session_links_policy_tests.cpp") + target_link_libraries(DKRSessionLinksPolicyTests PRIVATE DKRPeerRelay DKRNetplayCore) + add_executable(DKRSessionLinksNativeTests "${_dkr_relay_root}/tests/session_links_native_tests.cpp") + target_link_libraries(DKRSessionLinksNativeTests PRIVATE DKRNetplayCore) + foreach(_test DKRSessionLinksPolicyTests DKRSessionLinksNativeTests) + if(MSVC) + target_compile_options(${_test} PRIVATE /UNDEBUG) + else() + target_compile_options(${_test} PRIVATE -UNDEBUG) + endif() + endforeach() + if(BUILD_TESTING) + add_test(NAME DKRSessionLinksPolicy COMMAND DKRSessionLinksPolicyTests) + add_test(NAME DKRSessionLinksNative COMMAND DKRSessionLinksNativeTests) + set_tests_properties(DKRSessionLinksPolicy DKRSessionLinksNative PROPERTIES LABELS "host;runtime") + set_tests_properties(DKRSessionLinksNative PROPERTIES TIMEOUT 180) + endif() + endif() if(NOT TARGET DKRLiveDatagramTests) add_executable(DKRLiveDatagramTests "${_dkr_relay_root}/tests/live_datagram_tests.cpp") target_link_libraries(DKRLiveDatagramTests PRIVATE DKRPeerRelay DKRNetplayCore) diff --git a/runtime-recomp/src/game/custom_records.hpp b/runtime-recomp/src/game/custom_records.hpp index 882a43b4..c7afcd47 100644 --- a/runtime-recomp/src/game/custom_records.hpp +++ b/runtime-recomp/src/game/custom_records.hpp @@ -84,6 +84,7 @@ inline bool valid(std::span bytes) { // Normal guest hooks enqueue copies only. No disk access during replay. bool begin(const std::filesystem::path& path, bool restore, std::string& error); Bytes seed(); +bool begin_memory(std::span bytes, std::string& error); void submit(Bytes bytes); bool finish(std::string& error); bool persist(const std::filesystem::path& path, std::span bytes, std::string& error); diff --git a/runtime-recomp/src/game/display_settings/ui.inl b/runtime-recomp/src/game/display_settings/ui.inl index bdb8ac21..4c906c63 100644 --- a/runtime-recomp/src/game/display_settings/ui.inl +++ b/runtime-recomp/src/game/display_settings/ui.inl @@ -20,7 +20,8 @@ bool DrawDisplayChoices(float width, bool aspect_field) { bool changed = false; const auto list = choices(preference, w, h); std::vector resolutions{ - {std::string(dkr::localisation::source("Automatic - match window"))}, + {std::string(dkr::localisation::source("Automatic - match window")) + " (" + + std::string(dkr::localisation::source("Recommended")) + ")"}, {std::string(dkr::localisation::source("Automatic - sharp integer scaling"))}}; int selected = preference.height == 0 ? 0 : preference.height == -1 ? 1 : -1; for (const auto& item : list) { diff --git a/runtime-recomp/src/game/game_main.cpp b/runtime-recomp/src/game/game_main.cpp index 290196b4..9efb82c6 100644 --- a/runtime-recomp/src/game/game_main.cpp +++ b/runtime-recomp/src/game/game_main.cpp @@ -54,6 +54,7 @@ #include #endif #if DKR_LEGACY_QUALIFICATION +#include "netplay/session_links/qualification.hpp" #include "legacy_runtime_qualification.hpp" #endif #if DKR_RUNTIME_HAS_RT64 @@ -981,6 +982,8 @@ int DkrMain(int argc, char** argv) { dkr::runtime::platform::shutdown(); return 5; } + dkr::runtime::netplay::links::HandoverQualification handover_check(owned_check); + auto start_retry_at = std::chrono::steady_clock::time_point{}; bool joined = launch.owned_check_host, invitation_written = false, ready = false, started = false, accepted = false; bool connection_test_requested = false, connection_tested = false; @@ -1014,11 +1017,18 @@ int DkrMain(int argc, char** argv) { const auto chat_started = std::chrono::steady_clock::now(); std::optional chat_release; auto report_at = std::chrono::steady_clock::now(); - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60); + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(handover_check.enabled() ? 180 : 60); while (std::chrono::steady_clock::now() < deadline && !accepted) { dkr::runtime::vehicles::lighting::pump_owned_check(); dkr::runtime::platform::pump_window_events(nullptr); const auto state = online.view(); + std::string handover_error; + const bool handover_ready = handover_check.pulse(&online, handover_error); + if (!handover_error.empty()) { + rom_error = handover_error; + break; + } if (std::chrono::steady_clock::now() >= report_at) { std::fprintf(stderr, "[rollback][check] lobby state=%d local=%u status=%s\n", int(state.state), unsigned(state.local_slot), state.status.c_str()); @@ -1080,7 +1090,7 @@ int DkrMain(int argc, char** argv) { std::chrono::steady_clock::now() - chat_started >= std::chrono::seconds(25)) chat_release = std::chrono::steady_clock::now(); } - if (launch.owned_check_host) + if (state.host) for (const auto& pending : state.pending_joins) if (!online.approve_join(pending.request_id, rom_error)) break; @@ -1090,7 +1100,10 @@ int DkrMain(int argc, char** argv) { state.state == dkr::runtime::netplay::ConnectionState::Lobby)) { ready = online.set_ready(true, rom_error); } - if (launch.owned_check_host && ready && !started) { + if (state.host && ready && handover_ready && + state.state == dkr::runtime::netplay::ConnectionState::Hosting && !state.launch_countdown_active && + state.launch_stage == dkr::runtime::netplay::LaunchStage::Idle && + (!started || std::chrono::steady_clock::now() >= start_retry_at)) { unsigned occupants = 0; bool all_ready = true; for (const auto& racer : state.room.players) @@ -1131,8 +1144,10 @@ int DkrMain(int argc, char** argv) { const bool chat_ready = !check_chat || (chat_release && std::chrono::steady_clock::now() >= *chat_release); if (chat_ready && - (connection_tested || !(connection_test && std::string_view(connection_test) == "1"))) + (connection_tested || !(connection_test && std::string_view(connection_test) == "1"))) { started = online.request_start(rom_error); + start_retry_at = std::chrono::steady_clock::now() + std::chrono::seconds(1); + } } } accepted = online.consume_launch_request(); @@ -1410,10 +1425,13 @@ int DkrMain(int argc, char** argv) { selecting_save_owner = true; if (dkr::runtime::spectators::party_enabled(&dkr::runtime::netplay::session())) { auto party = dkr::runtime::spectators::party_link(&dkr::runtime::netplay::session()); - std::vector seed; + std::vector seed, shared_records; + bool owns_save = false; { std::scoped_lock lock(party->mutex); seed = party->seed; + shared_records = party->links.save_records; + owns_save = party->links.save_owner == party->local; } if (seed.size() != 512) throw dkr::mods::Error("Party bootstrap is missing its verified save seed."); @@ -1423,7 +1441,7 @@ int DkrMain(int argc, char** argv) { dkr::runtime::spectators::party_bootstrap_write}); dkr::runtime::pak::begin_session_directory({}); std::filesystem::path records; - if (online_save.host) { + if (owns_save && shared_records.empty()) { std::vector active; std::filesystem::path owner; if (!dkr::runtime::saves::read_online_adventure(true, online_save.launch_descriptor->match_id, @@ -1431,8 +1449,13 @@ int DkrMain(int argc, char** argv) { active != seed) throw dkr::mods::Error("The host online seed changed during party boot: " + rom_error); records = owner.parent_path() / "custom-records-v1.bin"; + if (!dkr::runtime::saves::records::begin(records, false, rom_error)) + throw dkr::mods::Error(rom_error); + shared_records = dkr::runtime::saves::records::seed(); + std::scoped_lock lock(party->mutex); + party->links.save_records = shared_records; } - if (!dkr::runtime::saves::records::begin(records, false, rom_error)) + if (!dkr::runtime::saves::records::begin_memory(shared_records, rom_error)) throw dkr::mods::Error(rom_error); } else { dkr::runtime::spectators::party_bootstrap_seed({}); diff --git a/runtime-recomp/src/game/mods/online_mod_sync.cpp b/runtime-recomp/src/game/mods/online_mod_sync.cpp index 9c257c2c..d6039c9c 100644 --- a/runtime-recomp/src/game/mods/online_mod_sync.cpp +++ b/runtime-recomp/src/game/mods/online_mod_sync.cpp @@ -262,6 +262,10 @@ void ModSync::host_loop(std::shared_ptr bundle, std::stop_token st hosted = true; else if (hosted) break; + if (!network.host) { + pause(stop, std::chrono::milliseconds(20)); + continue; + } if (network.game_active) { peers.clear(); { @@ -800,3 +804,4 @@ void ModSync::client_loop(const SyncSettings& settings, const RuntimePreparation } } } // namespace dkr::mods::online +#include "netplay/session_links/mod_host.inl" diff --git a/runtime-recomp/src/game/mods/online_mod_sync.hpp b/runtime-recomp/src/game/mods/online_mod_sync.hpp index 0bd9c304..7c7913ec 100644 --- a/runtime-recomp/src/game/mods/online_mod_sync.hpp +++ b/runtime-recomp/src/game/mods/online_mod_sync.hpp @@ -79,6 +79,8 @@ class ModSync { bool prepare_host(SyncSettings settings, std::filesystem::path legacy, std::vector labs, std::string revision, bool custom_ai, RuntimePreparation prepare); bool watch_client(SyncSettings settings, RuntimePreparation prepare); + bool promote_cached_host(SyncSettings settings, std::string& error); + bool cached_host_active() const; void consent(bool accept, bool keep_offline = true, std::string approved_code_offer = {}); void cancel(); SyncView snapshot() const; diff --git a/runtime-recomp/src/game/netplay/direct_session.cpp b/runtime-recomp/src/game/netplay/direct_session.cpp index 1b01c6ea..b1756593 100644 --- a/runtime-recomp/src/game/netplay/direct_session.cpp +++ b/runtime-recomp/src/game/netplay/direct_session.cpp @@ -4,6 +4,8 @@ #include "netplay/session_chat/settings.hpp" #include "netplay/peer_relay/owner_glue.hpp" #include "netplay/peer_relay/transport.hpp" +#include "netplay/session_links/registry.hpp" +#include "netplay/session_links/transport.hpp" #include "start_cancel_message.hpp" #include "online_stability/qualification_delivery.hpp" #include "../policy.hpp" @@ -299,6 +301,7 @@ void DirectSession::configure_session_save(std::vector canonical_s } void DirectSession::retire_transport_locked() { + links::forget(this); pending_invitation_.reset(); if (!transport_->quick_join()) { transport_->close(); @@ -5804,6 +5807,13 @@ void DirectSession::flush_outbound_locked() { } std::uint64_t& DirectSession::outbound_sequence(const PeerAddress& address, const secure::Key& key) { + // Pair-key counters survive a role change and optional direct-input routes. + { + auto party = dkr::runtime::spectators::party_link(this); + std::scoped_lock party_lock(party->mutex); + if (auto* p = party->peer(address); p && p->key == key) + return p->sequence; + } if (!is_host_) return next_sequence_; for (PeerRecord& peer : peers_) { @@ -5862,6 +5872,8 @@ void DirectSession::broadcast(protocol::MessageType type, std::spanaddress}); + } } proxy::configure(this, proxy::build_context(roster, now), std::move(addresses)); proxy::RouteTable table; @@ -5946,10 +5968,14 @@ void DirectSession::service_peer_relay_locked(dkr::runtime::spectators::PartyLin table.reachable.push_back(peer.sender_id); } } + if (!is_host_ && party.enabled && !party.local_watching()) + for (const auto& member : party.party.snapshot().members) + if (member.role == watch::Role::Racer && party.links.introduced.contains(member.id)) + table.introduced.push_back(member.id); for (auto& command : proxy::route(proxy::controls(this), table)) { auto payload = watch::link_encode(watch::LinkKind::Extension, command.bytes); const auto type = protocol::MessageType(watch::PartyMessageType); - if (!is_host_) { + if (!is_host_ && command.target == host_sender_id_) { send_with_key(host_address_, key_, type, payload); } else if (party.enabled) { if (const auto* peer = party.peer(command.target)) @@ -6093,6 +6119,8 @@ void DirectSession::pump_locked() { PeerAddress departed{}; while (transport_->take_peer_departure(departed)) { + if (!is_host_ && !(departed == host_address_) && links::retire_route(this, match_id_, departed)) + continue; { auto party = dkr::runtime::spectators::party_link(this); std::scoped_lock party_lock(party->mutex); @@ -6198,6 +6226,7 @@ void DirectSession::pump_locked() { if (!secure::inspect_packet(encrypted, packet_sender, packet_match) || packet_match != match_id_) continue; const secure::Key* receive_key = &key_; + std::optional introduced_key; bool provisional_mod_peer = false; if (is_host_) { PeerRecord* peer = peer_by_sender(packet_sender); @@ -6217,7 +6246,10 @@ void DirectSession::pump_locked() { } } } else if (packet_sender != host_sender_id_) { - continue; + introduced_key = links::receive_key(this, match_id_, packet_sender, source); + if (!introduced_key) + continue; + receive_key = &*introduced_key; } std::uint64_t opened_sender = 0U; std::uint64_t packet_sequence = 0U; @@ -6234,6 +6266,8 @@ void DirectSession::pump_locked() { if (provisional_mod_peer && packet.header.type != protocol::MessageType::ModControl && packet.header.type != protocol::MessageType::ModData) continue; + if (introduced_key && unsigned(packet.header.type) != dkr::runtime::spectators::PartyMessageType) + continue; // A fragmented authority snapshot must not age a delayed rollback // input out of the replay window. Keep authenticated sequence windows // per traffic lane while retaining one globally unique encryption @@ -6308,6 +6342,18 @@ void DirectSession::pump_locked() { if (!watch::link_decode(packet.payload, message)) continue; if (message.kind == watch::LinkKind::Extension) { + if (message.body.size() >= 6 && message.body[5] == 7) { + const bool admitted = party->enabled && party->party.find(packet_sender) && + (packet_sender == host_sender_id_ || party->peer(packet_sender)); + if (admitted) { + if (auto* peer = party->peer(packet_sender)) + peer->heard = std::chrono::steady_clock::now(); + if (packet_sender == host_sender_id_) + last_admission_response_ = std::chrono::steady_clock::now(); + party->links.receive(packet_sender, message.body); + } + continue; + } // Authentication/replay checks already ran. A provisional download // route is not an admitted lobby member and cannot publish metadata. const bool admitted = is_host_ ? (party->enabled ? party->peer(packet_sender) != nullptr @@ -6315,12 +6361,26 @@ void DirectSession::pump_locked() { : (packet_sender == host_sender_id_ && source == host_address_); if (admitted && message.body.size() >= 6 && message.body[5] == 4) dkr::chat::channel(this)->receive(packet_sender, message.body); - else if (admitted && message.body.size() >= 6 && (message.body[5] == 3 || message.body[5] == 6)) + else if ((admitted || (party->enabled && party->peer(packet_sender) && + party->links.introduced.contains(packet_sender))) && + message.body.size() >= 6 && message.body[5] == 6) + dkr::relay::control(this, packet_sender, message.body); + else if (admitted && message.body.size() >= 6 && message.body[5] == 3) dkr::relay::control(this, packet_sender, message.body); else dkr::online_stability::control(this)->receive(packet_sender, admitted, message.body); continue; } + if (!is_host_ && packet_sender != host_sender_id_) { + // Introductions authorize only immutable racer inputs. Room, + // stop, start and checkpoint authority remains with the host. + if (message.kind == watch::LinkKind::Runtime && party->links.introduced.contains(packet_sender)) { + if (auto* peer = party->peer(packet_sender); + peer && peer->address == source && party->admit_incoming(packet_sender, message.body)) + peer->heard = std::chrono::steady_clock::now(); + } + continue; + } if (is_host_) { auto* member = party->peer(packet_sender); if (!party->enabled || !member || member->address != source) @@ -6385,8 +6445,8 @@ void DirectSession::pump_locked() { break; } case watch::LinkKind::Ready: - if (!party->launch && !party->stopping && message.body.size() == 1 && message.body[0] <= 1 && - party->participant(packet_sender)) + if (!party->launch && !party->stopping && !links::busy(party->links) && message.body.size() == 1 && + message.body[0] <= 1 && party->participant(packet_sender)) party->ready[packet_sender] = message.body[0] != 0; break; case watch::LinkKind::Stop: @@ -6545,8 +6605,9 @@ void DirectSession::pump_locked() { if (!party->launch) { // The roster is part of the receipt. Re-arm when it moves on, or a // start validated against the previous roster is never acknowledged. - if (!gate->launch || gate->hash != start.descriptor_hash || - gate->roster != roster.generation) { + if (dkr::runtime::party_start::needs_prepare( + *gate, start.descriptor_hash, roster.generation, session_save_generation_, + manifest_.session_save_hash)) { gate->launch = launch; gate->hash = start.descriptor_hash; gate->roster = roster.generation; @@ -6679,6 +6740,7 @@ void DirectSession::pump_locked() { return; #include "../remove_member.inl" const auto now = std::chrono::steady_clock::now(); + service_session_links_locked(*party, now); auto queue = [&](watch::MemberId target, watch::LinkKind kind, std::vector body) { const auto traffic = kind == watch::LinkKind::Heartbeat ? TransportTrafficClass::Realtime : TransportTrafficClass::Control; @@ -6750,7 +6812,8 @@ void DirectSession::pump_locked() { party->ready.clear(); party->advertised = {}; } - if (party->ready_requested && !party->launch && party->participant(sender_id_)) + if (party->ready_requested && !party->launch && !links::busy(party->links) && + party->participant(sender_id_)) party->ready[sender_id_] = party->ready_value; party->ready_requested = false; // Within the DirectSession and PartyLink owner locks. @@ -6785,8 +6848,8 @@ void DirectSession::pump_locked() { }; if (party->start_requested) { party->start_requested = false; - if (!party->launch && !party->stopping && gate->phase != StartPhase::Countdown && - gate->phase != StartPhase::Committing) { + if (!party->launch && !party->stopping && !links::busy(party->links) && + gate->phase != StartPhase::Countdown && gate->phase != StartPhase::Committing) { std::string reason; bool all = true; for (const auto& m : party->party.snapshot().members) @@ -7063,6 +7126,10 @@ void DirectSession::pump_locked() { auto item = std::move(pending.front()); pending.pop_front(); party->outgoing_bytes -= item.bytes.size(); + if (!is_host_ && item.target && item.target != host_sender_id_ && + item.kind == watch::LinkKind::Runtime && item.traffic == TransportTrafficClass::Realtime && + item.bytes.size() > 4 && item.bytes[4] == 19 && !party->links.live_routes.contains(item.target)) + continue; auto payload = watch::link_encode(item.kind, item.bytes); bool blocked = false; auto send = [&](const PeerAddress& destination, const secure::Key& key) { @@ -7111,6 +7178,9 @@ void DirectSession::pump_locked() { send(peer->address, peer->key); } else if (!item.target || item.target == host_sender_id_) send(host_address_, key_); + else if (auto* peer = party->peer(item.target); + peer && party->links.introduced.contains(item.target)) + send(peer->address, peer->key); if (blocked) party->enqueue(std::move(item)); } @@ -7499,6 +7569,8 @@ void DirectSession::handle_join_request(const PeerAddress& source, std::spanenabled && links::busy(party->links)) + return; if (party_join && !party->enabled && !watch_join) party_join = false; if (party_join && watch_join && !party->allow_spectators && !party->peer(packet_sender)) { @@ -7617,11 +7689,14 @@ void DirectSession::handle_join_request(const PeerAddress& source, std::spanlinks.architectures, + [&](const auto& item) { return item.first != sender_id_ && !present.contains(item.first); }); } if (hello.manifest.architecture == manifest_.architecture) other_architecture_senders_.erase(packet_sender); else other_architecture_senders_.insert(packet_sender); + party->links.architectures.insert_or_assign(packet_sender, hello.manifest.architecture); PendingRecord* pending = pending_by_sender(packet_sender); if (pending && pending->mods_approved && (!(pending->address == source) || pending->key != peer_key || pending->client_public != client_public)) diff --git a/runtime-recomp/src/game/netplay/direct_session.hpp b/runtime-recomp/src/game/netplay/direct_session.hpp index 73e66e4d..9318c7fc 100644 --- a/runtime-recomp/src/game/netplay/direct_session.hpp +++ b/runtime-recomp/src/game/netplay/direct_session.hpp @@ -639,6 +639,8 @@ class DirectSession final { void pump_locked(); // Session chat's share of the pump. Requires mutex_ and party.mutex. void service_chat_locked(dkr::runtime::spectators::PartyLink& party); + void service_session_links_locked(dkr::runtime::spectators::PartyLink& party, + std::chrono::steady_clock::time_point now); // The peer relay's share of the pump (lobby roster for the relay, its control packets). // Requires mutex_ and party.mutex; `now` is the pump's clock reading. void service_peer_relay_locked(dkr::runtime::spectators::PartyLink& party, diff --git a/runtime-recomp/src/game/netplay/experimental_presentation.cpp b/runtime-recomp/src/game/netplay/experimental_presentation.cpp index 35488861..389f5fbb 100644 --- a/runtime-recomp/src/game/netplay/experimental_presentation.cpp +++ b/runtime-recomp/src/game/netplay/experimental_presentation.cpp @@ -1,6 +1,7 @@ #include "experimental_presentation.hpp" #include "experimental_checkpoint_hash.hpp" #include "experimental_performance.hpp" +#include "online_presentation/correction_lifetime.hpp" #include #include #include @@ -11,6 +12,7 @@ struct SubmissionDomain { std::uint64_t epoch = 0, generation = 0; std::size_t in_flight = 0, consumers = 0; bool alive = true; + CorrectionLifetime corrections; // Two queued immutable images + latest pending + publication candidate, // one decoder, INCLUDING cached capacity: 80 MiB vanilla / 120 MiB // with portable code storage. Slot count never grows into a FIFO. @@ -125,7 +127,7 @@ std::unique_ptr SubmissionPermit::acquire(std::shared_ptrdomain_; std::scoped_lock lock(domain.mutex); - if (!domain.alive || domain.epoch != snapshot->epoch() || domain.generation != snapshot->generation()) { + if (!domain.alive || domain.epoch != snapshot->epoch() || !domain.corrections.eligible(snapshot.get())) { // An unclaimed candidate must not run the counted-release destructor. permit->snapshot_.reset(); return {}; @@ -183,6 +185,7 @@ bool PresentationMailbox::begin_epoch(std::uint64_t epoch) { std::scoped_lock domain_lock(domain_->mutex); domain_->epoch = epoch_; domain_->generation = generation_; + domain_->corrections.reset(); } return true; } @@ -213,6 +216,11 @@ bool PresentationMailbox::publish(std::uint64_t epoch, RenderDescriptor descript // the race while its immutable image was being copied. if (epoch != epoch_ || generation != generation_ || (last_frame_ && descriptor.frame <= *last_frame_)) return false; + { + std::scoped_lock domain_lock(domain_->mutex); + if (!domain_->corrections.publish(candidate)) + return false; + } pending_ = std::move(candidate); last_frame_ = descriptor.frame; return true; @@ -259,15 +267,23 @@ bool PresentationMailbox::retire_for_restore(std::uint64_t epoch, std::uint32_t retire_locked(first); return true; } -void PresentationMailbox::retire_locked(std::uint32_t first) { - // Even a previously valid older lease is conservatively retired. A real - // renderer must recheck this generation before presentation and retain - // its last completed image while a replacement is being produced. +bool PresentationMailbox::retire_for_correction(std::uint64_t epoch, std::uint32_t first) { + std::scoped_lock lock(mutex_); + if (!epoch_ || epoch != epoch_ || generation_ == UINT64_MAX || first == UINT32_MAX) + return false; + retire_locked(first, true); + return true; +} +void PresentationMailbox::retire_locked(std::uint32_t first, bool correction) { + // An immutable picture survives only when it precedes every correction + // affecting its lease. Scene/resource retirement remains unconditional. ++generation_; - pending_.reset(); + if (!correction || (pending_ && pending_->descriptor().frame >= first)) + pending_.reset(); { std::scoped_lock domain_lock(domain_->mutex); domain_->generation = generation_; + domain_->corrections.retire(first, correction); } if (last_frame_ && first <= *last_frame_) last_frame_ = first ? std::optional(first - 1) : std::nullopt; @@ -275,7 +291,9 @@ void PresentationMailbox::retire_locked(std::uint32_t first) { bool PresentationMailbox::is_current(const std::shared_ptr& snapshot) const { std::scoped_lock lock(mutex_); const auto active = active_.lock(); - return snapshot && active == snapshot && snapshot->epoch() == epoch_ && snapshot->generation() == generation_; + std::scoped_lock domain_lock(domain_->mutex); + return snapshot && active == snapshot && snapshot->epoch() == epoch_ && + domain_->corrections.eligible(snapshot.get()); } bool PresentationMailbox::quiescent() const { std::scoped_lock lock(mutex_); diff --git a/runtime-recomp/src/game/netplay/experimental_presentation.hpp b/runtime-recomp/src/game/netplay/experimental_presentation.hpp index c1bf5c88..33dc694a 100644 --- a/runtime-recomp/src/game/netplay/experimental_presentation.hpp +++ b/runtime-recomp/src/game/netplay/experimental_presentation.hpp @@ -147,6 +147,7 @@ class PresentationMailbox final { // image or after a slow renderer's last publication. Retires any in-flight // candidate/lease without claiming that the GPU has finished consuming it. bool retire_for_restore(std::uint64_t epoch, std::uint32_t first_changed_frame); + bool retire_for_correction(std::uint64_t epoch, std::uint32_t first_changed_frame); bool is_current(const std::shared_ptr& snapshot) const; // Nonblocking status for an asynchronous restore/preparation owner. An // adapter requiring fully retired presentation MUST await this, keeping @@ -156,7 +157,7 @@ class PresentationMailbox final { BufferStatistics buffer_statistics() const; private: - void retire_locked(std::uint32_t first_changed_frame); + void retire_locked(std::uint32_t first_changed_frame, bool correction = false); // Serialize producers without holding the small consumer-state lock while // copying/hashing RAM. A correction may retire a candidate during that work. std::mutex producer_mutex_; diff --git a/runtime-recomp/src/game/netplay/experimental_runtime.cpp b/runtime-recomp/src/game/netplay/experimental_runtime.cpp index cda1bb10..7c2ad21d 100644 --- a/runtime-recomp/src/game/netplay/experimental_runtime.cpp +++ b/runtime-recomp/src/game/netplay/experimental_runtime.cpp @@ -1,3 +1,4 @@ +#include "netplay/session_links/menu_control.hpp" #include "online_input_broker.hpp" #include "online_stability/startup_transport.hpp" #include "online_stability/flow_trace.hpp" @@ -427,10 +428,23 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi namespace party = dkr::runtime::spectators; auto hub = party::party_link(&lobby); const auto initial = party::party_link_view(&lobby); - std::vector seed; + std::vector seed, transferred_paks; + bool save_owner = false; + unsigned menu_owner_port = 0; { std::scoped_lock lock(hub->mutex); seed = hub->seed; + save_owner = hub->links.save_owner == initial.local; + if (initial.host) + transferred_paks = hub->links.save_paks; + if (const auto* owner = hub->party.find(hub->party.snapshot().host); owner && owner->port) + menu_owner_port = *owner->port; + else + for (const auto& member : hub->party.snapshot().members) + if (member.port) { + menu_owner_port = *member.port; + break; + } } if (!initial.enabled || !initial.admitted || seed.size() != 512 || bootstrap.empty()) { error = "The party launch is missing its verified local bootstrap/save."; @@ -452,10 +466,10 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi shared.confirmed_save = seed; std::atomic local_port{4}; std::atomic watching{true}; - ConfirmedSaveWriter save_writer([&, host = initial.host](const ConfirmedSaveSnapshot& s, std::string& e) { - // Only the authority stores the communal online bank. Observers never - // install host state into a personal save, records bank or controller Pak. - if (host && !launch.development) { + ConfirmedSaveWriter save_writer([&, owner = save_owner](const ConfirmedSaveSnapshot& s, std::string& e) { + // The original save owner retains the durable bank after host handover. + // The current host retains only the verified in-memory transfer state. + if (owner && !launch.development) { if (!saves::commit_online_adventure(true, launch.match_id, s.eeprom, e) || !saves::commit_experimental_online_paks(true, launch.match_id, s.paks, e)) return false; @@ -467,6 +481,11 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi return false; } } + if (initial.host) { + std::scoped_lock lock(hub->mutex); + hub->links.save_paks = s.paks; + hub->links.save_records = s.records; + } std::scoped_lock lock(shared.mutex); shared.confirmed_save = s.eeprom; e.clear(); @@ -557,6 +576,7 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi throw std::runtime_error("Party presentation epoch refused."); const auto revision = lobby.view().room.manifest.revision == Revision::UsV80 ? rom::Revision::UsV80 : rom::Revision::UsV77; + dkr::runtime::netplay::links::menu_control::CreationPort menu_controls(menu_owner_port); world = make_owned_game_for_revision( revision, bootstrap, bytes, epoch, shared.mailbox, [&](ConfirmedAudio a, std::string& e) { return shared.audio.push(a.rate, a.pcm, e); }, message, false, @@ -569,8 +589,9 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi throw std::runtime_error(message); std::fprintf(stderr, "[party][boot] owned world ready; bytes=%zu\n", world->contract().state_bytes); if (initial.host) { - std::vector paks; - if (!saves::read_experimental_online_paks(true, launch.match_id, paks, message) || + auto paks = transferred_paks; + if ((paks.empty() && + !saves::read_experimental_online_paks(save_owner, launch.match_id, paks, message)) || !world->install_initial_paks(epoch, paks, message)) throw std::runtime_error(message); } @@ -708,8 +729,9 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi report({true, wait, cursor.epoch, cursor.frame, runtime.confirmed(), stats.rollbacks, stats.replayed_frames, runtime.status(), cursor.epoch == 0}); if (now >= next_save) { - if (initial.host && !save_writer.submit(world->confirmed_save(), world->confirmed_paks(), message, - world->confirmed_records())) + if ((initial.host || save_owner) && + !save_writer.submit(world->confirmed_save(), world->confirmed_paks(), message, + world->confirmed_records())) throw std::runtime_error(message); next_save = now + std::chrono::seconds(5); } @@ -735,7 +757,7 @@ bool run_party_runtime(ultramodern::renderer::WindowHandle window, const std::fi else party::party_stop(&lobby, "Party simulation stopped."); } - if (world && initial.host) { + if (world && (initial.host || save_owner)) { std::string message; if (!save_writer.submit(world->confirmed_save(), world->confirmed_paks(), message, world->confirmed_records())) diff --git a/runtime-recomp/src/game/netplay/peer_relay/live_datagram.cpp b/runtime-recomp/src/game/netplay/peer_relay/live_datagram.cpp index 8c73664f..016addfd 100644 --- a/runtime-recomp/src/game/netplay/peer_relay/live_datagram.cpp +++ b/runtime-recomp/src/game/netplay/peer_relay/live_datagram.cpp @@ -196,8 +196,12 @@ void LiveDatagram::configure(const Context& context, const std::vector wanted; + const auto local = std::find_if(context.members.begin(), context.members.end(), + [&](const auto& member) { return member.id == context.local; }); for (const auto& member : context.members) - if (member.id && member.id != context.local && (context.local == context.host || member.id == context.host)) + if (member.id && member.id != context.local && + (context.local == context.host || member.id == context.host || + (local != context.members.end() && local->racer && member.racer))) wanted.insert(member.id); std::erase_if(s.peers, [&](const auto& p) { return !wanted.contains(p.first); }); for (const auto id : wanted) diff --git a/runtime-recomp/src/game/netplay/peer_relay/owner_glue.cpp b/runtime-recomp/src/game/netplay/peer_relay/owner_glue.cpp index 607ec8c2..992f670d 100644 --- a/runtime-recomp/src/game/netplay/peer_relay/owner_glue.cpp +++ b/runtime-recomp/src/game/netplay/peer_relay/owner_glue.cpp @@ -53,9 +53,14 @@ Context build_context(const RelayRoster& roster, Clock::time_point now) { std::vector route(std::vector controls, const RouteTable& table) { std::vector sends; for (auto& control : controls) { + const bool ice = + control.bytes.size() >= 6 && std::equal(control.bytes.begin(), control.bytes.begin() + 6, + std::array{'D', 'K', 'R', 'X', 1, 6}.begin()); + const bool introduced = ice && std::find(table.introduced.begin(), table.introduced.end(), control.target) != + table.introduced.end(); const bool deliverable = table.is_host ? std::find(table.reachable.begin(), table.reachable.end(), control.target) != table.reachable.end() - : control.target == table.host; + : control.target == table.host || introduced; if (deliverable) sends.push_back(std::move(control)); } diff --git a/runtime-recomp/src/game/netplay/peer_relay/owner_glue.hpp b/runtime-recomp/src/game/netplay/peer_relay/owner_glue.hpp index 3d280061..89356f00 100644 --- a/runtime-recomp/src/game/netplay/peer_relay/owner_glue.hpp +++ b/runtime-recomp/src/game/netplay/peer_relay/owner_glue.hpp @@ -69,7 +69,8 @@ Context build_context(const RelayRoster&, Clock::time_point now); struct RouteTable { bool is_host = false; Id host = 0; - std::vector reachable; // a host's reachable member ids + std::vector reachable; // a host's reachable member ids + std::vector introduced; // authenticated racer ICE peers, not additional relay authorities }; // The control packets that will be sent, in order: a host's to reachable members, // a client's to the host, nothing else. diff --git a/runtime-recomp/src/game/netplay/peer_relay/transport.cpp b/runtime-recomp/src/game/netplay/peer_relay/transport.cpp index 353e9808..3ab1d052 100644 --- a/runtime-recomp/src/game/netplay/peer_relay/transport.cpp +++ b/runtime-recomp/src/game/netplay/peer_relay/transport.cpp @@ -1,5 +1,6 @@ #include "../../session_log.hpp" #include "transport.hpp" +#include "netplay/session_links/transport.hpp" #include "live_datagram.hpp" #include "online_stability/traffic_meter.hpp" #include "online_stability/live_send_capacity.hpp" @@ -77,7 +78,7 @@ bool endpoint(std::string value, net::PeerAddress& address) { return false; } } -class Transport final : public net::SessionTransport { +class Transport final : public net::SessionTransport, public net::links::IntroducedTransport { public: Transport(const void* key, std::unique_ptr base, NetworkOptions options) : key_(key), base_(std::move(base)), options_(std::move(options)), events_(std::make_shared()), @@ -190,6 +191,25 @@ class Transport final : public net::SessionTransport { std::uint16_t local_port() const override { return base_->local_port(); } + std::string local_peer_name() const override { + return net::links::local_peer_name(*base_); + } + std::string peer_name(const net::PeerAddress& address) const override { + return net::links::peer_name(*base_, address); + } + bool introduce_peer(std::string_view endpoint, bool initiate, net::PeerAddress& address, + std::string& error) override { + return net::links::introduce_peer(*base_, endpoint, initiate, address, error); + } + bool prepare_host(std::string bootstrap, std::string& error) override { + return net::links::prepare_host(*base_, std::move(bootstrap), error); + } + bool alias_peer(const net::PeerAddress& address, std::string_view name, std::string& error) override { + return net::links::alias_peer(*base_, address, name, error); + } + bool apply_host_role(bool host, std::string_view remote, std::string& error) override { + return net::links::apply_host_role(*base_, host, remote, error); + } net::DatagramSendStatus send_status(const net::PeerAddress& to, std::span bytes, net::TransportTrafficClass traffic, std::string& error) override { // Checkpoint chunks have no repair: the sender advances after each accepted diff --git a/runtime-recomp/src/game/netplay/quick_join_transport.cpp b/runtime-recomp/src/game/netplay/quick_join_transport.cpp index c6d616d2..6678a1e7 100644 --- a/runtime-recomp/src/game/netplay/quick_join_transport.cpp +++ b/runtime-recomp/src/game/netplay/quick_join_transport.cpp @@ -4,6 +4,8 @@ #include "online_presentation/test_receive_delay.hpp" #include "online_stability/live_send_capacity.hpp" #include "session_transport.hpp" +#include "netplay/session_links/transport.hpp" +#include #include "callback_lifetime.hpp" #include "transport_send_policy.hpp" #include "social_executor.hpp" @@ -127,7 +129,7 @@ std::string signaling_ca_bundle() { return std::string(kPeerJsFallbackRoot); } -class QuickJoinTransport final : public SessionTransport { +class QuickJoinTransport final : public SessionTransport, public links::IntroducedTransport { public: QuickJoinTransport(bool host, std::string code) : host_(host), code_(std::move(code)) {} ~QuickJoinTransport() override { @@ -187,6 +189,9 @@ class QuickJoinTransport final : public SessionTransport { peers.swap(peers_); remote_to_identifier_.clear(); pinned_routes_.clear(); + authorized_remote_.clear(); + peer_aliases_.clear(); + preparing_host_.store(false); departed_peers_.clear(); retired.swap(retired_peers_); control_inbound_.clear(); @@ -236,7 +241,8 @@ class QuickJoinTransport final : public SessionTransport { void retain_peer_route(const PeerAddress& address) override { std::scoped_lock lock(mutex_); for (const auto& [id, peer] : peers_) { - if (peer->address == address && (pinned_routes_.contains(peer->remote_id) || pinned_routes_.size() < 16U)) { + if (peer->address == address && + (pinned_routes_.contains(peer->remote_id) || pinned_route_count_locked() < 16U)) { pinned_routes_[peer->remote_id] = {id, address}; return; } @@ -244,6 +250,19 @@ class QuickJoinTransport final : public SessionTransport { } void release_peer_route(const PeerAddress& address) override { std::scoped_lock lock(mutex_); + for (const auto& [id, peer] : peers_) + if (peer->address == address) { + authorized_remote_.erase(peer->remote_id); + if (const auto alias = peer_aliases_.find(id); alias != peer_aliases_.end()) { + authorized_remote_.erase(alias->second); + peer_aliases_.erase(alias); + } + } + for (const auto& [name, route] : pinned_routes_) + if (route.second == address) { + authorized_remote_.erase(name); + peer_aliases_.erase(route.first); + } std::erase_if(pinned_routes_, [&](const auto& entry) { return entry.second.second == address; }); } bool take_peer_departure(PeerAddress& address) override { @@ -302,8 +321,10 @@ class QuickJoinTransport final : public SessionTransport { return code_; } +#include "netplay/session_links/quick_join_api.inl" + bool rekey_quick_join(std::string bootstrap, std::string& error) override { - if (!host_ || !is_open() || rekey_status() == QuickJoinRekeyStatus::Pending) { + if ((!host_ && !preparing_host_.load()) || !is_open() || rekey_status() == QuickJoinRekeyStatus::Pending) { error = "Only an active host without a pending code replacement can rekey."; return false; } @@ -316,6 +337,7 @@ class QuickJoinTransport final : public SessionTransport { pending->bootstrap = std::move(bootstrap); pending->generation = next_signaling_generation_.fetch_add(1U) + 1U; pending_rekey_ = pending; + pending->quiet = preparing_host_.load(); } rekey_state_.store(QuickJoinRekeyStatus::Pending); pending->socket = make_signaling_socket(pending->generation, pending); @@ -644,6 +666,7 @@ class QuickJoinTransport final : public SessionTransport { friend struct QuickJoinTestAccess; CallbackLifetime callbacks_; struct PendingRekey { + bool quiet = false; std::string code; std::string bootstrap; std::uint64_t generation = 0U; @@ -690,16 +713,17 @@ class QuickJoinTransport final : public SessionTransport { pending->socket->close(); return; } - for (const auto& channel : channels) { - rtc::binary framed{static_cast(3U)}; - for (unsigned char c : pending->code) - framed.push_back(static_cast(c)); - try { - if (channel->isOpen()) - channel->send(std::move(framed)); - } catch (...) { + if (!pending->quiet) + for (const auto& channel : channels) { + rtc::binary framed{static_cast(3U)}; + for (unsigned char c : pending->code) + framed.push_back(static_cast(c)); + try { + if (channel->isOpen()) + channel->send(std::move(framed)); + } catch (...) { + } } - } if (previous) previous->close(); } @@ -710,6 +734,7 @@ class QuickJoinTransport final : public SessionTransport { PeerAddress address{}; std::atomic current{true}; std::atomic route_ready{false}; + std::atomic authority_route{false}; bool departure_reported = false; // mutex_ protected bool signals_released = false; // mutex_ protected std::vector held_signals; // mutex_ protected @@ -806,9 +831,10 @@ class QuickJoinTransport final : public SessionTransport { bool has_established_route() const { std::scoped_lock lock(mutex_); - return std::any_of(peers_.begin(), peers_.end(), [](const auto& entry) { + return std::any_of(peers_.begin(), peers_.end(), [this](const auto& entry) { const auto& peer = entry.second; return peer && peer->current.load(std::memory_order_acquire) && + (host_ || peer->authority_route.load(std::memory_order_acquire)) && peer->route_ready.load(std::memory_order_acquire) && peer->control_channel && peer->control_channel->isOpen(); }); @@ -879,7 +905,7 @@ class QuickJoinTransport final : public SessionTransport { failed_.load(std::memory_order_acquire)) return; peer->route_ready.store(false, std::memory_order_release); - if (!host_) { + if (!host_ && peer->authority_route.load(std::memory_order_acquire)) { std::uint64_t unscheduled = 0U; next_route_retry_ms_.compare_exchange_strong(unscheduled, steady_milliseconds() + 750U, std::memory_order_acq_rel); @@ -918,6 +944,7 @@ class QuickJoinTransport final : public SessionTransport { std::shared_ptr replaced; { std::scoped_lock lock(mutex_); + peer->authority_route.store(!host_ && peer->remote_id == remote_host_id_); if (peer->remote_id.size() > 128U || peer->connection_id.size() > 128U || retired_peers_.size() + pending_retirements_.load() >= 16U || (peers_.size() >= 16U && std::none_of(peers_.begin(), peers_.end(), [&](const auto& entry) { @@ -965,7 +992,7 @@ class QuickJoinTransport final : public SessionTransport { payload["serialization"] = "none"; } send_peer_signal(locked, Json{{"type", type == "offer" ? "OFFER" : "ANSWER"}, - {"dst", locked->remote_id}, + {"dst", signal_name(locked->identifier, locked->remote_id)}, {"payload", std::move(payload)}}); })); peer->connection->onLocalCandidate(callbacks_.wrap([this, weak_peer](rtc::Candidate candidate) { @@ -975,7 +1002,7 @@ class QuickJoinTransport final : public SessionTransport { send_peer_signal( locked, Json{{"type", "CANDIDATE"}, - {"dst", locked->remote_id}, + {"dst", signal_name(locked->identifier, locked->remote_id)}, {"payload", {{"connectionId", locked->connection_id}, {"type", "data"}, @@ -993,7 +1020,7 @@ class QuickJoinTransport final : public SessionTransport { return; if (state == rtc::PeerConnection::State::Connected) { locked->route_ready.store(true, std::memory_order_release); - if (!host_) { + if (!host_ && locked->authority_route.load(std::memory_order_acquire)) { next_route_retry_ms_.store(0U, std::memory_order_release); route_retry_requested_.store(false, std::memory_order_release); } @@ -1214,10 +1241,10 @@ class QuickJoinTransport final : public SessionTransport { std::scoped_lock lock(mutex_); if (!locked->current.load(std::memory_order_acquire) || closing_.load()) return; - if (kind == 2U && !host_) { + if (kind == 2U && !host_ && locked->authority_route.load(std::memory_order_acquire)) { bootstrap_.assign(bytes.begin(), bytes.end()); bootstrap_peer_ = locked->address; - } else if (kind == 3U && !host_) { + } else if (kind == 3U && !host_ && locked->authority_route.load(std::memory_order_acquire)) { const std::string replacement(bytes.begin(), bytes.end()); if (valid_quick_join_code(replacement)) { const std::string new_remote = "dkrr-31-" + normalize_code(replacement); @@ -1352,7 +1379,12 @@ class QuickJoinTransport final : public SessionTransport { if (connection_id.empty()) return; std::shared_ptr peer = find_peer(remote, connection_id); - if (!peer && type == "OFFER" && host_) { + bool introduced = false; + { + std::scoped_lock lock(mutex_); + introduced = authorized_remote_.contains(remote); + } + if (!peer && type == "OFFER" && (host_ || introduced)) { if (!payload.contains("sdp") || !payload["sdp"].is_object()) return; (void)create_peer(remote, connection_id, false, &payload["sdp"]); @@ -1379,7 +1411,7 @@ class QuickJoinTransport final : public SessionTransport { } } - bool host_ = false; +#include "netplay/session_links/quick_join_state.inl" #ifdef DKR_QUICK_JOIN_TESTING int construction_failure_stage_ = -1; std::function construction_hook_; diff --git a/runtime-recomp/src/game/netplay/session_links/handover_pump.inl b/runtime-recomp/src/game/netplay/session_links/handover_pump.inl new file mode 100644 index 00000000..8635d50f --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/handover_pump.inl @@ -0,0 +1,298 @@ +{ + std::string transfer_error; + // Capability flags are membership scoped. A stale UI request cannot move + // a member who left, nor overlap a race, seat swap, invitation or download. + if (links.request) { + const auto target = std::exchange(links.request, 0); + if (is_host_ && waiting && !roster.handover && !direct::busy(links)) { + const bool directory = method_ == ConnectionMethod::QuickJoin && dkr::online::hosting_mode(this) == 2; + if (directory && !dkr::online::view()->host_handover) { + links.status = "This directory has not enabled host handover yet."; + } else { + direct::Proposal p{links.scope, ++links.serial, target, links.save_owner, {}}; + p.state = digest_transfer(watch::wire::roster(roster)); + if (links.handover.offer(sender_id_, p, true, now, transfer_error)) { + reset_transfer(); + links.directory_required = directory; + links.directory_code = directory ? invite_ : std::string{}; + if (directory) { + const auto online = dkr::online::view(); + links.directory_public = online->public_desired && !online->hidden; + } + } else + links.status = transfer_error; + } + } + } + if (links.consent) { + const bool accept = *links.consent; + links.consent.reset(); + links.local_consent = accept; + if (const auto& p = links.handover.proposal(); p && p->successor == sender_id_) { + direct::Write value; + value.number(p->serial).number(accept, 1); + transfer_send(p->before.host, direct::Kind::Accept, std::move(value.bytes)); + } + } + if (links.cancel) { + links.cancel = false; + if (const auto& p = links.handover.proposal(); + p && links.handover.cancel(sender_id_, p->serial, "Host transfer cancelled.", transfer_error)) { + direct::Write value; + value.number(p->serial); + if (sender_id_ == p->before.host) + transfer_all(direct::Kind::Cancel, value.bytes); + else + transfer_send(p->before.host, direct::Kind::Cancel, std::move(value.bytes)); + } + } + const auto prior = links.handover.phase(); + links.handover.service(links.scope, waiting && !roster.handover, now); + if (links.handover.phase() == direct::Phase::Cancelled && prior != direct::Phase::Cancelled) { + if (const auto& p = links.handover.proposal(); p && sender_id_ == p->before.host) { + direct::Write v; + v.number(p->serial); + transfer_all(direct::Kind::Cancel, v.bytes); + } + links.status = links.handover.status(); + } + const auto proposal = links.handover.proposal(); + if (proposal && links.handover.phase() == direct::Phase::Preparing && sender_id_ == proposal->successor && + links.local_consent.value_or(false) && !links.registration_started) { + links.successor_keys = secure::generate_key_pair(); + links.successor_capability = secure::generate_key(); + const auto bootstrap = "dkr-r-quick-v1\n" + hex64(match_id_) + "\n" + hex64(sender_id_) + "\n" + + secure::encode_key(links.successor_keys.public_key) + "\n" + + secure::encode_key(links.successor_capability) + "\n" + + std::to_string(unix_seconds() + 21600U); + links.registration_started = direct::prepare_host(*transport_, bootstrap, transfer_error); + if (!links.registration_started) + links.status = transfer_error; + } + if (proposal && links.handover.phase() == direct::Phase::Preparing && sender_id_ == proposal->successor && + links.registration_started && + (!transport_->quick_join() || transport_->rekey_status() == QuickJoinRekeyStatus::Committed)) { + links.registration_ready = true; + links.successor_public = links.successor_keys.public_key; + links.successor_endpoint = transport_->quick_join() + ? direct::local_peer_name(*transport_) + : std::string("127.0.0.1:") + std::to_string(transport_->local_port()); + links.successor_invite = transport_->quick_join() ? transport_->quick_join_code() : links.successor_endpoint; + } + if (proposal && sender_id_ == proposal->before.host && links.registration_ready && links.prepared_bytes.empty() && + links.handover.phase() == direct::Phase::Preparing) { + auto room = lobby_payload(); + room.generation = roster.generation; + room.phase = RoomPhase::Waiting; + const auto snapshot = watch::wire::roster(roster), room_bytes = protocol::encode_lobby_state(room); + auto keys = links.keys; + for (const auto& peer : party->peers) + keys[{std::min(sender_id_, peer.id), std::max(sender_id_, peer.id)}] = peer.key; + direct::Write inventory; + inventory.number(keys.size(), 1); + for (const auto& [pair, key] : keys) + inventory.number(pair.first).number(pair.second).data(key); + links.inventory_bytes = std::move(inventory.bytes); + links.inventory_hash = digest_transfer(links.inventory_bytes); + direct::Write bundle; + bundle.number(proposal->serial) + .number(proposal->successor) + .number(proposal->save_owner) + .data(links.successor_public) + .data(links.successor_capability) + .text(links.successor_endpoint) + .text(links.successor_invite) + .number(manifest_class_hash(room_view_.manifest)) + .number(party->save_hash) + .number(party->save_generation, 4) + .data(links.inventory_hash) + .number(mod_manifest_bytes_, 4) + .number(snapshot.size(), 4) + .data(snapshot) + .number(room_bytes.size(), 4) + .data(room_bytes) + .data(party->seed) + .number(links.save_paks.size(), 4) + .data(links.save_paks) + .number(links.save_records.size(), 4) + .data(links.save_records) + .number(party->maximum_racers, 1) + .number(party->allow_spectators, 1) + .number(party->launch_serial); + bundle.number(roster.members.size(), 1); + for (const auto& member : roster.members) { + const auto architecture = links.architectures.find(member.id); + if (architecture == links.architectures.end() || architecture->second.empty() || + architecture->second.size() > 128) { + links.status = + "A member's platform identity is not available. Please rejoin before transferring the host."; + bundle.bytes.clear(); + break; + } + bundle.number(member.id).text(architecture->second); + } + if (!bundle.bytes.empty() && bundle.bytes.size() <= direct::MaximumTransferBytes && + links.handover.bind(sender_id_, proposal->serial, digest_transfer(bundle.bytes), transfer_error)) { + links.prepared_bytes = std::move(bundle.bytes); + links.expected_transfer = links.prepared_bytes.size(); + links.prepared_state = parse_transfer(true); + } else + links.status = + transfer_error.empty() ? "The transfer exceeds the bounded session save size." : transfer_error; + } + if (proposal && links.prepared_state && links.handover.phase() == direct::Phase::Preparing) { + bool routes = true; + for (const auto& member : proposal->before.members) { + if (member.id == sender_id_) + continue; + if (sender_id_ != proposal->successor && member.id != proposal->successor) + continue; + const auto* peer = party->peer(member.id); + const auto address = member.id == host_sender_id_ ? host_address_ : peer ? peer->address : PeerAddress{}; + if (!address) { + routes = false; + break; + } + for (const auto lane : + {TransportTrafficClass::Control, TransportTrafficClass::Authoritative, TransportTrafficClass::Realtime, + TransportTrafficClass::Replica, TransportTrafficClass::Checkpoint}) + routes = routes && transport_->traffic_ready(address, lane); + const auto sample = links.samples.find({sender_id_, member.id}); + routes = routes && sample != links.samples.end() && sample->second.observations && + now - sample->second.measured < std::chrono::seconds(5); + } + if (routes && + (sender_id_ != proposal->successor || + (links.inventory_ready && (manifest_.mod_manifest_hash.empty() || links.mod_ready))) && + (!links.directory_required || sender_id_ != proposal->successor || links.directory_accepted)) + links.handover.prepared(sender_id_, proposal->serial, links.handover.proposal()->state, true, now, + transfer_error); + } + if (proposal && links.directory_required && now >= links.directory_send && links.prepared_state && + !links.released) { + links.directory_send = now + std::chrono::seconds(2); + const auto current = links.handover.proposal(); + const auto online = dkr::online::view(); + if (online->connected && online->signed_in && online->host_handover && + (sender_id_ != current->successor || !links.directory_public || !online->hidden) && + ((sender_id_ == current->successor && links.handover.phase() == direct::Phase::Preparing) || + (sender_id_ == current->before.host && ((links.handover.complete() && !links.directory_committed) || + links.handover.phase() == direct::Phase::Preparing)))) { + dkr::online::respond(this, {{"type", sender_id_ == current->successor ? "transfer_accept" + : links.handover.complete() ? "transfer_commit" + : "transfer_prepare"}, + {"serial", std::to_string(current->serial)}, + {"epoch", hex64(match_id_)}, + {"digest", secure::encode_key(current->state)}, + {"code", links.directory_code}, + {"nextCode", links.successor_invite}, + {"sender", std::to_string(current->successor)}}); + } + } + if (now >= links.transfer_send && proposal) { + links.transfer_send = now + std::chrono::milliseconds(200); + const auto phase = links.handover.phase(); + const auto current = links.handover.proposal(); + if (sender_id_ == current->successor && links.released && !links.finished) { + bool realtime_ready = true; + for (const auto& member : party->party.snapshot().members) + if (member.port && member.id != sender_id_) { + const auto* peer = party->peer(member.id); + realtime_ready = realtime_ready && peer && peer->rtt_count && + now - peer->rtt_at < std::chrono::seconds(5) && + now - peer->heard < std::chrono::seconds(5); + } + if (realtime_ready) + transfer_send(current->before.host, direct::Kind::Activated, transfer_identity()); + } + if (sender_id_ == current->successor && phase == direct::Phase::Offered && links.local_consent) { + direct::Write value; + value.number(current->serial).number(*links.local_consent, 1); + transfer_send(current->before.host, direct::Kind::Accept, std::move(value.bytes)); + } + if (sender_id_ == current->before.host && phase == direct::Phase::Cancelled) { + direct::Write value; + value.number(current->serial); + transfer_all(direct::Kind::Cancel, value.bytes); + } + if (sender_id_ == current->before.host && phase == direct::Phase::Offered) { + direct::Write value; + value.number(current->serial).number(current->successor).number(current->save_owner).data(current->state); + value.number(links.directory_required, 1).number(links.directory_public, 1).text(links.directory_code); + transfer_all(direct::Kind::Offer, value.bytes); + } + if (phase == direct::Phase::Preparing) { + if (sender_id_ == current->successor && links.registration_ready) { + direct::Write value; + value.number(current->serial) + .data(links.successor_public) + .data(links.successor_capability) + .text(links.successor_endpoint) + .text(links.successor_invite); + transfer_send(current->before.host, direct::Kind::Registration, std::move(value.bytes)); + } + if (sender_id_ == current->before.host) { + direct::Write consent; + consent.number(current->serial).number(1, 1); + transfer_all(direct::Kind::Accept, consent.bytes); + if (links.prepared_state) { + direct::Write prepare; + prepare.number(current->serial) + .data(current->state) + .number(links.prepared_bytes.size(), 4) + .text(links.successor_endpoint); + transfer_all(direct::Kind::Prepare, prepare.bytes); + if (!links.handover.ready(current->successor)) + for (std::size_t at = 0; at < links.inventory_bytes.size(); at += direct::TransferChunk) { + direct::Write chunk; + chunk.number(current->serial) + .number(links.inventory_bytes.size(), 4) + .number(at, 4) + .data(std::span(links.inventory_bytes) + .subspan(at, + std::min(direct::TransferChunk, links.inventory_bytes.size() - at))); + transfer_send(current->successor, direct::Kind::Inventory, std::move(chunk.bytes)); + } + for (const auto& member : current->before.members) + if (member.id != sender_id_ && !links.handover.ready(member.id)) { + const auto offset = links.transfer_offsets[member.id]; + for (unsigned n = 0; + n < 8 && offset + n * direct::TransferChunk < links.prepared_bytes.size(); ++n) { + const auto at = offset + n * direct::TransferChunk, + count = std::min(direct::TransferChunk, links.prepared_bytes.size() - at); + direct::Write chunk; + chunk.number(current->serial) + .number(at, 4) + .data(std::span(links.prepared_bytes).subspan(at, count)); + transfer_send(member.id, direct::Kind::SaveChunk, std::move(chunk.bytes)); + } + } + } + } else if (links.handover.ready(sender_id_)) + transfer_send(current->before.host, direct::Kind::Prepared, transfer_identity()); + } + if (sender_id_ == current->before.host && links.handover.can_commit()) { + links.handover.commit(sender_id_, current->serial, current->state, transfer_error); + links.handover.acknowledge(sender_id_, current->serial, current->state, transfer_error); + } + if (sender_id_ == current->before.host && links.handover.phase() == direct::Phase::Committing) + transfer_all(direct::Kind::Commit, transfer_identity()); + if (sender_id_ == current->before.host && links.handover.complete() && + (!links.directory_required || links.directory_committed)) { + if (!links.released && apply_transfer()) + links.activated.insert(sender_id_); + if (links.released) { + transfer_all(direct::Kind::Release, transfer_identity()); + if (links.activated.size() == current->before.members.size()) { + if (!links.finished) { + links.finished = true; + links.finished_until = now + std::chrono::seconds(60); + links.status = "Host transferred. Ready to race."; + } + if (now < links.finished_until) + transfer_all(direct::Kind::Finished, transfer_identity()); + } + } + } + } +} diff --git a/runtime-recomp/src/game/netplay/session_links/handover_service.inl b/runtime-recomp/src/game/netplay/session_links/handover_service.inl new file mode 100644 index 00000000..90e7b7d1 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/handover_service.inl @@ -0,0 +1,409 @@ +// Native host-transfer coordinator. All calls run under the session owner lock. +auto digest_transfer = [](std::span bytes) { + direct::Digest result{}; + crypto_blake2b(result.data(), result.size(), bytes.data(), bytes.size()); + return result; +}; +const bool waiting = !party->launch && !party->running && !party->stopping && !launch_countdown_active_ && + launch_stage_ == LaunchStage::Idle && !connection_test_active_ && + pending_invitation_ == std::nullopt && + std::none_of(pending_joins_.begin(), pending_joins_.end(), [](const auto& p) { return p.active; }); +auto transfer_send = [&](direct::Id target, direct::Kind kind, std::vector bytes = {}) { + const auto& p = links.handover.proposal(); + if (!p) + return false; + return party->enqueue({target, watch::LinkKind::Extension, TransportTrafficClass::Control, + direct::encode({kind, match_id_, p->before.generation, std::move(bytes)})}); +}; +auto transfer_all = [&](direct::Kind kind, const std::vector& bytes) { + if (const auto& p = links.handover.proposal()) + for (const auto& m : p->before.members) + if (m.id != sender_id_) + transfer_send(m.id, kind, bytes); +}; +auto transfer_identity = [&] { + direct::Write out; + if (const auto& p = links.handover.proposal()) + out.number(p->serial).data(p->state); + return out.bytes; +}; +auto transfer_identity_ok = [&](direct::Read& r) { + const auto digest = r.data(32); + const auto& p = links.handover.proposal(); + return p && digest.size() == 32 && std::equal(digest.begin(), digest.end(), p->state.begin()); +}; +auto reset_transfer = [&] { + links.registration_started = links.registration_ready = links.prepared_state = links.released = links.finished = + false; + links.successor_endpoint.clear(); + links.successor_invite.clear(); + links.prepared_bytes.clear(); + links.assembly = {}; + links.expected_transfer = 0; + links.activated.clear(); + links.transfer_offsets.clear(); + links.transfer_send = {}; + links.local_consent.reset(); + links.inventory_assembly = {}; + links.inventory_bytes.clear(); + links.pending_keys.clear(); + links.inventory_hash = {}; + links.inventory_ready = false; + links.directory_required = links.directory_public = links.directory_accepted = links.directory_committed = false; + links.directory_code.clear(); + links.directory_send = {}; + links.mod_requested = links.mod_ready = false; +}; +auto parse_transfer = [&](bool install) -> bool { + const auto& p = links.handover.proposal(); + if (!p || links.prepared_bytes.empty() || digest_transfer(links.prepared_bytes) != p->state) + return false; + direct::Read r{links.prepared_bytes}; + if (r.number() != p->serial || r.number() != p->successor || r.number() != p->save_owner) + return false; + const auto pub = r.data(32), cap = r.data(32); + const auto endpoint = r.text(), invite = r.text(256); + const auto compatibility = r.number(), save_hash = r.number(), save_generation = r.number(4); + const auto inventory_hash = r.data(32); + const auto manifest_bytes = r.number(4); + const auto roster_bytes = r.data(r.number(4)), room_bytes = r.data(r.number(4)), seed = r.data(512); + const auto paks = r.data(r.number(4)), records = r.data(r.number(4)); + const auto maximum = r.number(1), spectators = r.number(1), launch_serial = r.number(); + std::map architectures; + const auto architecture_count = r.number(1); + if (architecture_count != party->party.snapshot().members.size()) + return false; + for (unsigned i = 0; i < architecture_count; ++i) { + const auto id = r.number(); + const auto architecture = r.text(128); + if (architecture.empty() || !party->party.find(id) || !architectures.emplace(id, architecture).second) + return false; + } + const auto own_architecture = architectures.find(sender_id_); + if (own_architecture == architectures.end() || own_architecture->second != manifest_.architecture) + return false; + if (!r.done() || pub.size() != 32 || cap.size() != 32 || inventory_hash.size() != 32 || seed.size() != 512 || + (!paks.empty() && paks.size() != 131072) || records.size() > 20 + 8192 * 76 || maximum < 1 || maximum > 4 || + spectators > 1) + return false; + watch::PartySnapshot prepared; + protocol::LobbyStatePayload room; + std::string error; + if (!watch::wire::roster(roster_bytes, prepared, error) || !protocol::decode_lobby_state(room_bytes, room, error) || + prepared.host != p->before.host || prepared.generation != p->before.generation || prepared.handover || + prepared.members != party->party.snapshot().members || prepared.controls != party->party.snapshot().controls || + compatibility != manifest_class_hash(room_view_.manifest) || !save_generation || + stable_hash(std::string_view(reinterpret_cast(seed.data()), seed.size())) != save_hash) + return false; + if (install) { + std::copy(pub.begin(), pub.end(), links.successor_public.begin()); + std::copy(cap.begin(), cap.end(), links.successor_capability.begin()); + links.successor_endpoint = endpoint; + links.successor_invite = invite; + links.save_owner = p->save_owner; + std::copy(inventory_hash.begin(), inventory_hash.end(), links.inventory_hash.begin()); + links.save_paks = paks; + links.save_records = records; + party->seed = seed; + party->maximum_racers = unsigned(maximum); + mod_manifest_bytes_ = std::uint32_t(manifest_bytes); + party->allow_spectators = spectators != 0; + party->launch_serial = launch_serial; + party->save_generation = std::uint32_t(save_generation); + party->save_hash = save_hash; + session_save_ = seed; + session_save_generation_ = party->save_generation; + const auto local_architecture = manifest_.architecture; + manifest_ = room_view_.manifest; + manifest_.architecture = local_architecture; + links.architectures = std::move(architectures); + other_architecture_senders_.clear(); + for (const auto& [id, architecture] : links.architectures) + if (id != sender_id_ && architecture != local_architecture) + other_architecture_senders_.insert(id); + manifest_.session_save_hash = save_hash; + room_view_.manifest = manifest_; + room_view_.name = room.room_name; + room_view_.visibility = room.visibility; + room_view_.rules = room.rules; + input_delay_ = room.input_delay_frames; + } + return true; +}; +auto apply_transfer = [&]() -> bool { + const auto& p = links.handover.proposal(); + if (!p || links.last_applied == p->serial) + return bool(p); + if (!links.prepared_state || !parse_transfer(true)) + return false; + std::string error; + const bool successor = sender_id_ == p->successor; + // Preserve the existing key's outbound nonce domain before adding a host + // route to PartyLink. Membership changes never reset replay or AEAD state. + if (!is_host_ && !party->peer(host_sender_id_)) { + watch::LinkPeer old; + old.id = host_sender_id_; + old.address = host_address_; + old.key = key_; + old.sequence = outbound_sequence(host_address_, key_); + old.heard = now; + party->peers.push_back(old); + } + auto* next = successor ? nullptr : party->peer(p->successor); + if (!successor && !next) + return false; + if (!direct::apply_host_role(*transport_, successor, links.successor_endpoint, error)) { + links.status = error; + return false; + } + if (!party->party.transfer_host(p->before.host, p->successor, p->before.generation + 1, error)) { + links.status = error; + return false; + } + for (const auto& peer : party->peers) { + direct::install(this, match_id_, peer.id, peer.address, peer.key); + links.introduced.try_emplace( + peer.id, direct::Introduction{peer.id, peer.key, direct::peer_name(*transport_, peer.address), now}); + } + if (successor) { + // Routing roles changed. Prove fresh realtime round trips in the new + // host role before publishing Finished or admitting the first Start. + for (auto& peer : party->peers) { + peer.rtt_count = peer.rtt_index = 0; + peer.rtts = {}; + peer.rtt_at = peer.ping_sent = {}; + peer.ping_window = {}; + } + links.keys = links.pending_keys; + host_key_pair_ = links.successor_keys; + invitation_capability_ = links.successor_capability; + invite_ = transport_->quick_join() ? links.successor_invite + : make_invite(advertised_host_.empty() ? "127.0.0.1" : advertised_host_); + const auto room = room_view_; + const auto* me = party->party.find(sender_id_); + if (!lobby_.create(hex64(match_id_), "dkr-r/" + invite_, room.name, room.visibility, std::to_string(sender_id_), + me ? me->name : local_name_, manifest_, room.rules, error)) { + links.status = error; + return false; + } + room_view_ = lobby_.room(); + room_view_.generation = party->party.snapshot().generation; + // Existing waiting members are projected from Party, not reassigned by + // the four-slot legacy lobby. Their controller leases stay unchanged. + peers_ = {}; + state_ = ConnectionState::Hosting; + } else { + host_address_ = next->address; + key_ = next->key; + host_public_ = links.successor_public; + invitation_capability_ = links.successor_capability; + invite_ = links.successor_invite; + state_ = ConnectionState::Lobby; + peers_ = {}; + } + is_host_ = successor; + host_sender_id_ = p->successor; + party->host = successor; + party->authority = p->successor; + party->ready.clear(); + party->advertised = {}; + last_admission_response_ = now; + last_client_request_ = now; + links.last_applied = p->serial; + links.released = true; + links.status = "Host transferred. Confirming every connection."; + return true; +}; +auto handle_transfer = [&](direct::Id source, const direct::Packet& packet) { + std::string error; + direct::Read r{packet.body}; + if (packet.kind == direct::Kind::Offer) { + if (source != host_sender_id_ || is_host_ || !waiting) + return; + direct::Proposal p; + p.before = links.scope; + p.serial = r.number(); + p.successor = r.number(); + p.save_owner = r.number(); + const auto digest = r.data(32); + const auto directory = r.number(1), public_room = r.number(1); + const auto code = r.text(); + if (!r.done() || digest.size() != 32 || directory > 1 || public_room > 1 || + (directory && !valid_quick_join_code(code)) || (!directory && !code.empty())) + return; + std::copy(digest.begin(), digest.end(), p.state.begin()); + for (auto& m : p.before.members) + m.capable = true; + if (links.handover.offer(source, p, waiting, now, error)) { + if (links.serial != p.serial) { + reset_transfer(); + links.serial = p.serial; + } + links.directory_required = directory != 0; + links.directory_public = public_room != 0; + links.directory_code = code; + for (const auto& m : p.before.members) + links.capable.insert(m.id); + links.scope = p.before; + } else + links.status = error; + return; + } + const auto proposal = links.handover.proposal(); + if (!proposal || packet.generation != proposal->before.generation) + return; + const auto serial = r.number(); + if (serial != proposal->serial) + return; + if (packet.kind == direct::Kind::Accept) { + const auto accepted = r.number(1); + if (!r.done() || accepted > 1 || (source != proposal->successor && source != proposal->before.host)) + return; + // Relayed consent is sufficient for observers, but the candidate + // must have accepted locally before opening a new host registration. + if (sender_id_ == proposal->successor && accepted && !links.local_consent.value_or(false)) + return; + if (links.handover.consent(proposal->successor, serial, accepted != 0, now, error) && + sender_id_ == proposal->before.host) { + direct::Write consent; + consent.number(serial).number(accepted, 1); + transfer_all(direct::Kind::Accept, consent.bytes); + } + } else if (packet.kind == direct::Kind::Registration) { + if (sender_id_ != proposal->before.host || source != proposal->successor || + links.handover.phase() != direct::Phase::Preparing || !links.prepared_bytes.empty()) + return; + const auto pub = r.data(32), cap = r.data(32); + const auto endpoint = r.text(), invite = r.text(256); + if (!r.done() || pub.size() != 32 || cap.size() != 32 || endpoint.empty() || invite.empty()) + return; + auto* peer = party->peer(source); + if (!peer || !direct::alias_peer(*transport_, peer->address, endpoint, error)) + return; + std::copy(pub.begin(), pub.end(), links.successor_public.begin()); + std::copy(cap.begin(), cap.end(), links.successor_capability.begin()); + links.successor_endpoint = endpoint; + links.successor_invite = invite; + links.registration_ready = true; + } else if (packet.kind == direct::Kind::Prepare) { + if (source != proposal->before.host || links.handover.phase() != direct::Phase::Preparing) + return; + const auto digest = r.data(32); + const auto total = r.number(4); + const auto endpoint = r.text(); + if (!r.done() || digest.size() != 32 || !total || total > direct::MaximumTransferBytes) + return; + direct::Digest hash; + std::copy(digest.begin(), digest.end(), hash.begin()); + if (links.expected_transfer) { + if (links.expected_transfer != total || proposal->state != hash) + return; + } else if (!links.handover.bind(source, serial, hash, error)) + return; + if (auto* peer = party->peer(proposal->successor); peer && links.successor_endpoint != endpoint) + if (!direct::alias_peer(*transport_, peer->address, endpoint, error)) + return; + links.successor_endpoint = endpoint; + links.expected_transfer = std::size_t(total); + } else if (packet.kind == direct::Kind::SaveChunk) { + if (source != proposal->before.host || !links.expected_transfer || + links.handover.phase() != direct::Phase::Preparing) + return; + const auto offset = r.number(4); + const auto data = r.data(r.bytes.size() - std::min(r.at, r.bytes.size())); + if (!r.done() || !links.assembly.accept(serial, links.expected_transfer, std::size_t(offset), data)) + return; + std::size_t through = 0; + for (bool v : links.assembly.received) { + if (!v) + break; + through += direct::TransferChunk; + } + through = std::min(through, links.expected_transfer); + direct::Write receipt; + receipt.number(serial).number(through, 4); + transfer_send(source, direct::Kind::SaveReceipt, std::move(receipt.bytes)); + if (links.assembly.complete() && !links.prepared_state) { + links.prepared_bytes = links.assembly.bytes; + links.prepared_state = parse_transfer(true); + } + } else if (packet.kind == direct::Kind::Inventory) { + if (source != proposal->before.host || sender_id_ != proposal->successor || !links.prepared_state || + links.handover.phase() != direct::Phase::Preparing) + return; + const auto total = r.number(4), offset = r.number(4); + const auto data = r.data(r.bytes.size() - std::min(r.at, r.bytes.size())); + if (!r.done() || total > 1 + 66 * 48 || + !links.inventory_assembly.accept(serial, std::size_t(total), std::size_t(offset), data)) + return; + if (links.inventory_assembly.complete() && + digest_transfer(links.inventory_assembly.bytes) == links.inventory_hash) { + direct::Read inventory{links.inventory_assembly.bytes}; + const auto count = inventory.number(1); + std::map keys; + if (count > 66) + return; + for (unsigned i = 0; i < count; ++i) { + const auto a = inventory.number(), b = inventory.number(); + const auto bytes = inventory.data(32); + if (a >= b || !party->party.find(a) || !party->party.find(b) || bytes.size() != 32 || + keys.contains({a, b})) + return; + secure::Key key; + std::copy(bytes.begin(), bytes.end(), key.begin()); + keys.emplace(direct::Pair{a, b}, key); + } + if (inventory.done()) { + links.pending_keys = std::move(keys); + links.inventory_ready = true; + } + } + } else if (packet.kind == direct::Kind::SaveReceipt) { + if (sender_id_ != proposal->before.host) + return; + const auto offset = r.number(4); + if (!r.done() || offset > links.prepared_bytes.size() || + (offset != links.prepared_bytes.size() && offset % direct::TransferChunk)) + return; + links.transfer_offsets[source] = std::max(links.transfer_offsets[source], std::size_t(offset)); + } else if (packet.kind == direct::Kind::Prepared) { + if (sender_id_ != proposal->before.host || !transfer_identity_ok(r) || !r.done()) + return; + links.handover.prepared(source, serial, proposal->state, true, now, error); + } else if (packet.kind == direct::Kind::Commit) { + if (source != proposal->before.host || !links.prepared_state || !links.handover.ready(sender_id_) || + !transfer_identity_ok(r) || !r.done()) + return; + if (links.handover.phase() == direct::Phase::Preparing) + for (const auto& member : proposal->before.members) + links.handover.prepared(member.id, serial, proposal->state, true, now, error); + if (links.handover.commit(source, serial, proposal->state, error)) + transfer_send(source, direct::Kind::Acknowledge, transfer_identity()); + } else if (packet.kind == direct::Kind::Acknowledge) { + if (sender_id_ == proposal->before.host && transfer_identity_ok(r) && r.done()) + links.handover.acknowledge(source, serial, proposal->state, error); + } else if (packet.kind == direct::Kind::Release) { + if (source != proposal->before.host || !transfer_identity_ok(r) || !r.done() || + (links.handover.phase() != direct::Phase::Committing && links.handover.phase() != direct::Phase::Committed)) + return; + if (apply_transfer() && sender_id_ != proposal->successor) + transfer_send(source, direct::Kind::Activated, transfer_identity()); + } else if (packet.kind == direct::Kind::Activated) { + if (sender_id_ == proposal->before.host && links.released && transfer_identity_ok(r) && r.done()) + links.activated.insert(source); + } else if (packet.kind == direct::Kind::Finished) { + if (source == proposal->before.host && links.released && transfer_identity_ok(r) && r.done()) { + for (const auto& member : proposal->before.members) + links.handover.acknowledge(member.id, serial, proposal->state, error); + links.finished = true; + links.status = "Host transferred. Ready to race."; + } + } else if (packet.kind == direct::Kind::Cancel) { + if (!r.done() || (source != proposal->before.host && source != proposal->successor)) + return; + if (links.handover.cancel(source, serial, "Host transfer cancelled. The original host is still in charge.", + error) && + sender_id_ == proposal->before.host) + transfer_all(direct::Kind::Cancel, packet.body); + } +}; diff --git a/runtime-recomp/src/game/netplay/session_links/menu_control.hpp b/runtime-recomp/src/game/netplay/session_links/menu_control.hpp new file mode 100644 index 00000000..a03b37b9 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/menu_control.hpp @@ -0,0 +1,33 @@ +#pragma once +#include + +namespace dkr::runtime::netplay::links::menu_control { +// Construction context only. Each owned world retains this agreed port; tick +// and replay never consult a live lobby or another thread's UI state. +inline thread_local unsigned construction_port = 0; +class CreationPort final { + unsigned previous_; + + public: + explicit CreationPort(unsigned port) : previous_(construction_port) { + construction_port = port < 4 ? port : 0; + } + ~CreationPort() { + construction_port = previous_; + } + CreationPort(const CreationPort&) = delete; + CreationPort& operator=(const CreationPort&) = delete; +}; +inline unsigned creating_port() { + return construction_port; +} +template +auto input(const Inputs& values, unsigned authority, unsigned guest_port, bool host_only, unsigned assigned) { + using Value = std::remove_cvref_t; + if (authority >= 4 || guest_port >= 4) + return Value{}; + if (host_only) + return guest_port == 0 ? values[authority] : Value{}; + return !assigned || (assigned & (1U << guest_port)) ? values[guest_port] : Value{}; +} +} // namespace dkr::runtime::netplay::links::menu_control diff --git a/runtime-recomp/src/game/netplay/session_links/mod_host.inl b/runtime-recomp/src/game/netplay/session_links/mod_host.inl new file mode 100644 index 00000000..4f3b9619 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/mod_host.inl @@ -0,0 +1,66 @@ +// Included at namespace scope by the retained mod-sync owner composition. +namespace dkr::mods::online { +bool ModSync::cached_host_active() const { + const auto current = snapshot(); + return running_.load() && current.phase == SyncPhase::HostReady && current.manifest && current.profile && + current.runtime; +} +bool ModSync::promote_cached_host(SyncSettings settings, std::string& error) { + auto ready = snapshot(); + if ((ready.phase != SyncPhase::Verified && ready.phase != SyncPhase::HostReady) || !ready.manifest || + !ready.profile || !ready.runtime || ready.profile->digest != identity(*ready.manifest)) { + error = "The successor has no matching verified mod session."; + return false; + } + if (!start(SyncPhase::HostPreparing)) { + error.clear(); + return false; + } + try { + thread_ = std::jthread([this, settings = std::move(settings), + ready = std::move(ready)](std::stop_token stop) mutable { + try { + const auto root = private_storage_path(settings.online_root) / "payloads"; + auto bundle = std::make_shared(); + bundle->manifest = *ready.manifest; + for (const auto& item : bundle->manifest.payloads) { + require_running(stop); + check_storage(root / item.digest, false); + auto bytes = std::make_shared(read_file(root / item.digest, std::size_t(item.size))); + if (bytes->size() != item.size || sha256(*bytes) != item.digest) + throw Error("A cached online mod changed. Host transfer was cancelled."); + bundle->payloads.emplace(item.digest, std::move(bytes)); + } + require_running(stop); + ready.phase = SyncPhase::HostReady; + ready.error.clear(); + ready.stage = "Shared session mods are ready for hosting"; + publish(ready); + host_loop(std::move(bundle), stop); + } catch (const std::exception& e) { + if (!stop.stop_requested()) { + ready.phase = SyncPhase::Verified; + ready.error = e.what(); + publish(std::move(ready)); + } + } catch (...) { + if (!stop.stop_requested()) { + ready.phase = SyncPhase::Verified; + ready.error = "The shared mod session could not be prepared for hosting."; + publish(std::move(ready)); + } + } + running_.store(false); + }); + } catch (const std::exception& e) { + running_.store(false); + ready.phase = SyncPhase::Verified; + ready.error = e.what(); + publish(std::move(ready)); + error = e.what(); + return false; + } + error.clear(); + return true; +} +} // namespace dkr::mods::online diff --git a/runtime-recomp/src/game/netplay/session_links/mod_owner_ui.inl b/runtime-recomp/src/game/netplay/session_links/mod_owner_ui.inl new file mode 100644 index 00000000..9bb034d7 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/mod_owner_ui.inl @@ -0,0 +1,36 @@ +// The frontend owns the existing mod worker. The network owner only consumes +// its readiness bit; it never scans, reads or prepares mod files under locks. +{ + namespace watch = dkr::runtime::spectators; + namespace links = dkr::runtime::netplay::links; + auto hub = watch::party_link(&session()); + bool candidate = false, requested = false; + { + std::scoped_lock lock(hub->mutex); + const auto& p = hub->links.handover.proposal(); + candidate = + hub->enabled && p && p->successor == hub->local && hub->links.handover.phase() == links::Phase::Preparing; + requested = hub->links.mod_requested; + } + if (candidate && !network.room.manifest.mod_manifest_hash.empty()) { + if (g_online_mod_sync->cached_host_active() && view.manifest && + identity(*view.manifest) == network.room.manifest.mod_manifest_hash) { + std::scoped_lock lock(hub->mutex); + hub->links.mod_ready = true; + } else if (requested && view.phase == SyncPhase::Verified && !view.error.empty()) { + std::scoped_lock lock(hub->mutex); + hub->links.status = view.error; + hub->links.cancel = true; + } else if (!requested && (view.phase == SyncPhase::Verified || view.phase == SyncPhase::HostReady)) { + std::string error; + if (g_online_mod_sync->promote_cached_host(OnlineModSettings(), error)) { + std::scoped_lock lock(hub->mutex); + hub->links.mod_requested = true; + } else if (!error.empty()) { + std::scoped_lock lock(hub->mutex); + hub->links.status = error; + hub->links.cancel = true; + } + } + } +} diff --git a/runtime-recomp/src/game/netplay/session_links/owner_service.inl b/runtime-recomp/src/game/netplay/session_links/owner_service.inl new file mode 100644 index 00000000..dc6c1df6 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/owner_service.inl @@ -0,0 +1,264 @@ +// Session links' explicit owner boundary. Requires mutex_ and party.mutex. +void DirectSession::service_session_links_locked(dkr::runtime::spectators::PartyLink& value, + std::chrono::steady_clock::time_point now) { + namespace watch = dkr::runtime::spectators; + auto* party = &value; + namespace direct = dkr::runtime::netplay::links; + auto& links = party->links; + const auto& roster = party->party.snapshot(); + if (links.scope.room != match_id_) { + direct::forget(this); + links.reset(); + links.save_owner = roster.host; + } + std::erase_if(links.capable, [&](auto id) { return !party->party.find(id); }); + std::erase_if(links.capacity, [&](const auto& entry) { return !party->party.find(entry.first); }); + const auto departed = [&](const auto& entry) { return !party->party.find(entry.first); }; + std::erase_if(links.pings, departed); + std::erase_if(links.rtts, departed); + std::erase_if(links.last_probe, departed); + std::erase_if(links.probe_results, departed); + std::erase_if(links.samples, [&](const auto& entry) { + return !party->party.find(entry.first.first) || !party->party.find(entry.first.second); + }); + links.capable.insert(sender_id_); + links.architectures.insert_or_assign(sender_id_, manifest_.architecture); + direct::Scope scope{match_id_, roster.host, roster.generation}; + for (const auto& m : roster.members) + scope.members.push_back({m.id, m.port ? int(*m.port) : -1, links.capable.contains(m.id)}); + links.scope = scope; + auto emit = [&](std::uint64_t target, direct::Kind kind, std::vector bytes = {}) { + const auto traffic = kind == direct::Kind::Ping || kind == direct::Kind::Pong ? TransportTrafficClass::Realtime + : TransportTrafficClass::Control; + return party->enqueue({target, watch::LinkKind::Extension, traffic, + direct::encode({kind, match_id_, roster.generation, std::move(bytes)})}); + }; +#include "handover_service.inl" + for (auto it = links.keys.begin(); it != links.keys.end();) { + if (!party->party.find(it->first.first) || !party->party.find(it->first.second)) { + crypto_wipe(it->second.data(), it->second.size()); + it = links.keys.erase(it); + } else + ++it; + } + for (auto it = links.introduced.begin(); it != links.introduced.end();) { + if (!party->party.find(it->first)) { + direct::revoke(this, it->first); + if (!is_host_) { + if (const auto* peer = party->peer(it->first)) + transport_->release_peer_route(peer->address); + std::erase_if(party->peers, [&](const auto& p) { return p.id == it->first; }); + } + it = links.introduced.erase(it); + } else + ++it; + } + if (now >= links.hello) { + links.hello = now + std::chrono::seconds(1); + direct::Write hello; + hello.number(direct::ProtocolVersion, 1); + if (!is_host_) + emit(host_sender_id_, direct::Kind::Hello, std::move(hello.bytes)); + } + for (unsigned work = 0; work < 32 && !links.incoming.empty(); ++work) { + auto incoming = std::move(links.incoming.front()); + links.incoming.pop_front(); + const auto source = incoming.source; + const auto& packet = incoming.packet; + const auto& transfer = links.handover.proposal(); + const bool transferring = + transfer && packet.kind >= direct::Kind::Offer && packet.generation == transfer->before.generation; + if (packet.room != match_id_ || (!transferring && packet.generation != roster.generation) || + !party->party.find(source)) + continue; + direct::Read read{packet.body}; + if (packet.kind == direct::Kind::Hello) { + const auto version = read.number(1); + const auto save_owner = !is_host_ && read.at < read.bytes.size() ? read.number() : 0; + if (version == direct::ProtocolVersion && read.done() && (is_host_ || source == host_sender_id_)) { + links.capable.insert(source); + if (is_host_) { + direct::Write hello; + hello.number(direct::ProtocolVersion, 1).number(links.save_owner); + emit(source, direct::Kind::Hello, std::move(hello.bytes)); + } else if (save_owner) + links.save_owner = save_owner; + } + } else if (packet.kind == direct::Kind::Introduce) { + if (is_host_ || source != host_sender_id_) + continue; + const auto id = read.number(); + const auto bytes = read.data(32); + const auto endpoint = read.text(); + const auto* remote = party->party.find(id); + if (!read.done() || !remote || id == sender_id_ || id == host_sender_id_ || bytes.size() != 32) + continue; + const bool racers = remote->role == watch::Role::Racer && !party->local_watching(); + const auto& proposal = links.handover.proposal(); + const bool transfer = proposal && links.handover.phase() == direct::Phase::Preparing && + (proposal->successor == id || proposal->successor == sender_id_); + if (!racers && !transfer) + continue; + secure::Key key; + std::copy(bytes.begin(), bytes.end(), key.begin()); + if (const auto old = links.introduced.find(id); old != links.introduced.end() && old->second.key != key) + continue; + PeerAddress address; + std::string error; + if (const auto old = links.introduced.find(id); + old != links.introduced.end() && old->second.endpoint != endpoint) + if (auto* peer = party->peer(id); + peer && !direct::alias_peer(*transport_, peer->address, endpoint, error)) + continue; + if (!direct::introduce_peer(*transport_, endpoint, sender_id_ < id, address, error)) + continue; + auto* peer = party->peer(id); + if (peer && (!(peer->address == address) || peer->key != key)) + continue; + if (!direct::install(this, match_id_, id, address, key)) + continue; + if (!peer) { + watch::LinkPeer value; + value.id = id; + value.address = address; + value.key = key; + value.heard = now; + party->peers.push_back(value); + } + links.capable.insert(id); + links.introduced.insert_or_assign(id, direct::Introduction{id, key, endpoint, now}); + transport_->retain_peer_route(address); + } else if (packet.kind == direct::Kind::Ping) { + const auto token = read.number(); + if (!read.done() || !token) + continue; + if (source != host_sender_id_ && !links.introduced.contains(source) && !is_host_) + continue; + direct::Write pong; + pong.number(token); + emit(source, direct::Kind::Pong, std::move(pong.bytes)); + } else if (packet.kind == direct::Kind::Pong) { + const auto token = read.number(); + if (!read.done()) + continue; + auto pending = links.pings.find(source); + if (pending == links.pings.end()) + continue; + const auto sent = pending->second.find(token); + if (sent == pending->second.end() || now < sent->second) + continue; + const auto elapsed = std::chrono::duration_cast(now - sent->second).count(); + pending->second.erase(sent); + if (elapsed > 5000) + continue; + auto& values = links.rtts[source]; + values.push_back(unsigned(elapsed)); + if (values.size() > 32) + values.pop_front(); + std::vector sorted(values.begin(), values.end()); + std::sort(sorted.begin(), sorted.end()); + auto& outcomes = links.probe_results[source]; + outcomes.push_back(true); + if (outcomes.size() > 32) + outcomes.pop_front(); + const auto losses = std::count(outcomes.begin(), outcomes.end(), false); + links.samples[{sender_id_, source}] = {sorted[(sorted.size() - 1) * 95 / 100], + unsigned(1000U * losses / outcomes.size()), unsigned(values.size()), + now}; + } else if (packet.kind == direct::Kind::Report) { + if (!is_host_) + continue; + const auto other = read.number(), p95 = read.number(2), loss = read.number(2), samples = read.number(1); + if (!read.done() || !party->party.find(other) || other == source || p95 > 5000 || loss > 1000 || + samples > 32) + continue; + links.samples[{source, other}] = {unsigned(p95), unsigned(loss), unsigned(samples), now}; + } else + handle_transfer(source, packet); + } + if (is_host_ && now >= links.introduce) { + links.introduce = now + std::chrono::seconds(1); + for (const auto& a : roster.members) + for (const auto& b : roster.members) { + if (a.id >= b.id || a.id == sender_id_ || b.id == sender_id_ || !links.capable.contains(a.id) || + !links.capable.contains(b.id)) + continue; + const bool racers = a.role == watch::Role::Racer && b.role == watch::Role::Racer; + const auto& proposal = links.handover.proposal(); + const bool transfer = proposal && links.handover.phase() == direct::Phase::Preparing && + (proposal->successor == a.id || proposal->successor == b.id); + if (!racers && !transfer) + continue; + auto* first = party->peer(a.id); + auto* second = party->peer(b.id); + if (!first || !second) + continue; + auto key = links.keys.find({a.id, b.id}); + if (key == links.keys.end()) + key = links.keys.emplace(direct::Pair{a.id, b.id}, secure::generate_key()).first; + const auto first_name = direct::peer_name(*transport_, first->address), + second_name = direct::peer_name(*transport_, second->address); + if (first_name.empty() || second_name.empty()) + continue; + direct::Write for_first; + for_first.number(b.id).data(key->second).text(second_name); + direct::Write for_second; + for_second.number(a.id).data(key->second).text(first_name); + emit(a.id, direct::Kind::Introduce, std::move(for_first.bytes)); + emit(b.id, direct::Kind::Introduce, std::move(for_second.bytes)); + } + } + if (now >= links.probe) { + links.probe = now + std::chrono::milliseconds(500); + links.live_routes.clear(); + auto probe = [&](std::uint64_t id, const PeerAddress& address) { + if (!transport_->traffic_ready(address, TransportTrafficClass::Control)) + return; + if (party->participant(sender_id_) && party->participant(id) && + transport_->traffic_ready(address, TransportTrafficClass::Realtime)) + links.live_routes.insert(id); + auto& pending = links.pings[id]; + std::erase_if(pending, [&](const auto& p) { + if (now - p.second <= std::chrono::seconds(5)) + return false; + auto& results = links.probe_results[id]; + results.push_back(false); + if (results.size() > 32) + results.pop_front(); + return true; + }); + if (pending.size() >= 12) + return; + const auto token = + std::uint64_t(std::chrono::duration_cast(now.time_since_epoch()).count()); + pending[token] = now; + direct::Write ping; + ping.number(token); + emit(id, direct::Kind::Ping, std::move(ping.bytes)); + }; + if (is_host_) { + for (const auto& peer : party->peers) + if (links.capable.contains(peer.id)) + probe(peer.id, peer.address); + } else { + if (links.capable.contains(host_sender_id_)) + probe(host_sender_id_, host_address_); + for (const auto& [id, intro] : links.introduced) + if (auto* peer = party->peer(id)) + probe(id, peer->address); + } + } + if (!is_host_ && now >= links.report) { + links.report = now + std::chrono::seconds(1); + for (const auto& [pair, sample] : links.samples) + if (pair.first == sender_id_ && now - sample.measured < std::chrono::seconds(5)) { + direct::Write report; + report.number(pair.second) + .number(sample.p95_ms, 2) + .number(sample.loss_per_mille, 2) + .number(sample.observations, 1); + emit(host_sender_id_, direct::Kind::Report, std::move(report.bytes)); + } + } +#include "handover_pump.inl" +} diff --git a/runtime-recomp/src/game/netplay/session_links/policy.cpp b/runtime-recomp/src/game/netplay/session_links/policy.cpp new file mode 100644 index 00000000..6dcacdb0 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/policy.cpp @@ -0,0 +1,270 @@ +#include "session_log.hpp" +#include "policy.hpp" +#include +#include +#include +#include +#include + +namespace dkr::runtime::netplay::links { +namespace { +bool fail(std::string& error, std::string reason) { + error = std::move(reason); + return false; +} +const Member* member(const Scope& scope, Id id) { + const auto at = + std::find_if(scope.members.begin(), scope.members.end(), [id](const Member& m) { return m.id == id; }); + return at == scope.members.end() ? nullptr : &*at; +} +std::size_t index(const Scope& scope, Id id) { + const auto at = + std::find_if(scope.members.begin(), scope.members.end(), [id](const Member& m) { return m.id == id; }); + return std::size_t(at - scope.members.begin()); +} +} // namespace + +bool valid(const Scope& scope) { + if (!scope.room || !scope.host || !scope.generation || scope.members.empty() || + scope.members.size() > MaximumMembers || !member(scope, scope.host)) + return false; + std::set ids; + std::set ports; + for (const auto& m : scope.members) + if (!m.id || !ids.insert(m.id).second || m.port < -1 || m.port >= int(MaximumRacers) || + (m.port >= 0 && !ports.insert(m.port).second)) + return false; + return scope.members.size() - ports.size() <= MaximumMembers - MaximumRacers; +} + +bool input_pair(const Scope& scope, Id a, Id b) { + const auto* first = member(scope, a); + const auto* second = member(scope, b); + return valid(scope) && a != b && first && second && first->port >= 0 && second->port >= 0 && first->capable && + second->capable; +} +bool input_owner(const Scope& scope, Id sender, unsigned port) { + const auto* owner = member(scope, sender); + return valid(scope) && port < MaximumRacers && owner && owner->capable && owner->port == int(port); +} + +std::optional recommend(const Scope& scope, const std::map& samples, + const std::map& capacities, Clock::time_point now) { + if (!valid(scope)) + return {}; + std::optional best, current; + for (const auto& candidate : scope.members) { + if (!candidate.capable) + continue; + const auto capacity = capacities.find(candidate.id); + if (capacity != capacities.end() && capacity->second.measured && + (capacity->second.sampled > now || now - capacity->second.sampled > std::chrono::seconds(10) || + capacity->second.step_p95_us >= 25000 || capacity->second.background_saturated)) + continue; + Recommendation score{candidate.id}; + score.capacity_measured = capacity != capacities.end() && capacity->second.measured; + bool measured = true; + for (const auto& racer : scope.members) { + if (racer.port < 0 || racer.id == candidate.id) + continue; + const auto at = samples.find({candidate.id, racer.id}); + if (at == samples.end() || at->second.observations < 8 || at->second.measured > now || + now - at->second.measured > std::chrono::seconds(5)) { + measured = false; + break; + } + score.worst_p95_ms = std::max(score.worst_p95_ms, at->second.p95_ms); + score.worst_loss_per_mille = std::max(score.worst_loss_per_mille, at->second.loss_per_mille); + } + if (!measured) + continue; + if (candidate.id == scope.host) + current = score; + const auto rank = [](const Recommendation& value) { + return std::tuple{value.worst_loss_per_mille, value.worst_p95_ms, value.member}; + }; + if (!best || rank(score) < rank(*best)) + best = score; + } + if (!best || best->member == scope.host) + return {}; + // Avoid presenting a recommendation from incomplete comparisons or tiny + // fluctuations. Missing host capacity is a separate, explicit reason. + if (current && best->worst_loss_per_mille >= current->worst_loss_per_mille && + best->worst_p95_ms + 20 >= current->worst_p95_ms) + return {}; + best->reason = !best->capacity_measured + ? "Shorter measured network paths. Processing headroom has not been measured." + : current ? "More consistent measured connections to the racers." + : "Measured connections and processing headroom are available on this player."; + return best; +} + +bool Handover::expected(Id authenticated, Id serial) const { + return proposal_ && proposal_->serial == serial && member(proposal_->before, authenticated); +} +bool Handover::offer(Id authenticated, Proposal value, bool waiting, Clock::time_point now, std::string& error) { + if (proposal_ && *proposal_ == value && authenticated == value.before.host && phase_ != Phase::Cancelled) { + error.clear(); + return true; + } + if (!waiting || phase_ == Phase::Offered || phase_ == Phase::Preparing || phase_ == Phase::Committing) + return fail(error, "Finish the current operation before transferring host."); + if (!valid(value.before) || authenticated != value.before.host || !value.serial || + value.serial <= highest_serial_ || value.successor == value.before.host || + !member(value.before, value.successor) || !value.save_owner || + value.before.generation == std::numeric_limits::max() || + std::all_of(value.state.begin(), value.state.end(), [](auto b) { return b == 0; }) || + !std::all_of(value.before.members.begin(), value.before.members.end(), [](const auto& m) { return m.capable; })) + return fail(error, "Every connected player must support this host transfer."); + highest_serial_ = value.serial; + proposal_ = std::move(value); + prepared_ = {}; + acknowledged_ = {}; + phase_ = Phase::Offered; + deadline_ = now + std::chrono::seconds(20); + status_ = "Waiting for the new host to accept."; + error.clear(); + return true; +} +bool Handover::consent(Id authenticated, Id serial, bool accept, Clock::time_point now, std::string& error) { + if (!expected(authenticated, serial) || authenticated != proposal_->successor) + return fail(error, "Only the proposed host can accept this transfer."); + if (!accept && (phase_ == Phase::Offered || phase_ == Phase::Preparing)) + return cancel(authenticated, serial, "The proposed host declined.", error); + if (accept && phase_ == Phase::Preparing) { + error.clear(); + return true; + } + if (!accept || phase_ != Phase::Offered || now > deadline_) + return fail(error, "That host transfer is no longer waiting for acceptance."); + phase_ = Phase::Preparing; + deadline_ = now + std::chrono::seconds(120); + status_ = "Preparing the new host connections."; + error.clear(); + return true; +} +bool Handover::bind(Id authenticated, Id serial, const Digest& digest, std::string& error) { + if (!expected(authenticated, serial) || authenticated != proposal_->before.host || phase_ != Phase::Preparing || + std::any_of(prepared_.begin(), prepared_.end(), [](bool b) { return b; }) || + std::all_of(digest.begin(), digest.end(), [](auto b) { return !b; })) + return fail(error, "The prepared host transfer cannot change after a readiness vote."); + proposal_->state = digest; + error.clear(); + return true; +} +bool Handover::prepared(Id authenticated, Id serial, const Digest& digest, bool routes_ready, Clock::time_point now, + std::string& error) { + if (!expected(authenticated, serial) || phase_ != Phase::Preparing || now > deadline_ || !routes_ready || + digest != proposal_->state) + return fail(error, "The host transfer state or connections are not ready."); + prepared_[index(proposal_->before, authenticated)] = true; + error.clear(); + return true; +} +bool Handover::can_commit() const { + return proposal_ && phase_ == Phase::Preparing && + std::all_of(prepared_.begin(), prepared_.begin() + proposal_->before.members.size(), + [](bool b) { return b; }); +} +bool Handover::commit(Id authenticated, Id serial, const Digest& digest, std::string& error) { + if (!expected(authenticated, serial) || authenticated != proposal_->before.host || digest != proposal_->state) + return fail(error, "Only the current host can commit the prepared transfer."); + if (phase_ == Phase::Committing || phase_ == Phase::Committed) { + error.clear(); + return true; + } + if (!can_commit()) + return fail(error, "Every connected player must prepare before host ownership changes."); + phase_ = Phase::Committing; + status_ = "Transferring host. Waiting for acknowledgements."; + error.clear(); + return true; +} +bool Handover::acknowledge(Id authenticated, Id serial, const Digest& digest, std::string& error) { + if (!expected(authenticated, serial) || digest != proposal_->state || + (phase_ != Phase::Committing && phase_ != Phase::Committed)) + return fail(error, "That acknowledgement does not belong to this host transfer."); + acknowledged_[index(proposal_->before, authenticated)] = true; + if (complete()) { + phase_ = Phase::Committed; + status_ = "Host transferred."; + } + error.clear(); + return true; +} +bool Handover::complete() const { + return proposal_ && (phase_ == Phase::Committing || phase_ == Phase::Committed) && + std::all_of(acknowledged_.begin(), acknowledged_.begin() + proposal_->before.members.size(), + [](bool b) { return b; }); +} +bool Handover::cancel(Id authenticated, Id serial, std::string reason, std::string& error) { + if (!expected(authenticated, serial) || + (authenticated != proposal_->before.host && authenticated != proposal_->successor) || + (phase_ != Phase::Offered && phase_ != Phase::Preparing)) + return fail(error, "A committed host transfer cannot be rolled back."); + dkr::runtime::session_log::write( + "[online][handover-cancel] at-us=%llu actor=%llu serial=%llu phase=%u reason=%s\n", + (unsigned long long)std::chrono::duration_cast(Clock::now().time_since_epoch()) + .count(), + (unsigned long long)authenticated, (unsigned long long)serial, unsigned(phase_), reason.c_str()); + phase_ = Phase::Cancelled; + status_ = std::move(reason); + error.clear(); + return true; +} +void Handover::service(const Scope& current, bool waiting, Clock::time_point now) { + if (!proposal_ || (phase_ != Phase::Offered && phase_ != Phase::Preparing)) + return; + if (current != proposal_->before || !waiting || now > deadline_) { + const auto reason = current != proposal_->before ? "scope" : !waiting ? "busy" : "deadline"; + dkr::runtime::session_log::write( + "[online][handover-cancel] reason=%s serial=%llu host=%llu/%llu generation=%llu/%llu members=%zu/%zu waiting=%u\n", + reason, (unsigned long long)proposal_->serial, (unsigned long long)current.host, + (unsigned long long)proposal_->before.host, (unsigned long long)current.generation, + (unsigned long long)proposal_->before.generation, current.members.size(), proposal_->before.members.size(), + unsigned(waiting)); + if (current != proposal_->before) + for (const auto& m : current.members) { + const auto* old = member(proposal_->before, m.id); + if (!old || *old != m) + dkr::runtime::session_log::write("[online][handover-cancel] member=%llu port=%d/%d capable=%u/%u\n", + (unsigned long long)m.id, m.port, old ? old->port : -2, + unsigned(m.capable), old ? unsigned(old->capable) : 0); + } + phase_ = Phase::Cancelled; + status_ = + current != proposal_->before + ? "Host transfer cancelled because the lobby changed. The original host is still in charge." + : !waiting + ? "Host transfer cancelled because another lobby operation started. The original host is still in charge." + : "Host transfer timed out. The original host is still in charge."; + } + // Once committed, never restore old authority because an ACK was lost. + // The owner must retransmit the commit and hold race start until complete. +} +bool Handover::ready(Id id) const { + return proposal_ && member(proposal_->before, id) && prepared_[index(proposal_->before, id)]; +} +bool Handover::acknowledged(Id id) const { + return proposal_ && member(proposal_->before, id) && acknowledged_[index(proposal_->before, id)]; +} +std::optional Handover::result() const { + if (!proposal_ || (phase_ != Phase::Committing && phase_ != Phase::Committed)) + return {}; + auto result = proposal_->before; + result.host = proposal_->successor; + ++result.generation; + return result; +} +void Handover::reset() { + phase_ = Phase::Idle; + proposal_.reset(); + prepared_ = {}; + acknowledged_ = {}; + deadline_ = {}; + highest_serial_ = 0; + status_.clear(); +} + +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/policy.hpp b/runtime-recomp/src/game/netplay/session_links/policy.hpp new file mode 100644 index 00000000..5cf7ad62 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/policy.hpp @@ -0,0 +1,108 @@ +#pragma once + +#include "netplay/secure_channel.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dkr::runtime::netplay::links { + +using Id = std::uint64_t; +using Clock = std::chrono::steady_clock; +using Digest = std::array; +inline constexpr unsigned MaximumMembers = 12, MaximumRacers = 4; + +struct Member { + Id id = 0; + int port = -1; + bool capable = false; + bool operator==(const Member&) const = default; +}; + +struct Scope { + Id room = 0, host = 0, generation = 0; + std::vector members; + bool operator==(const Scope&) const = default; +}; + +bool valid(const Scope&); +bool input_pair(const Scope&, Id first, Id second); +bool input_owner(const Scope&, Id sender, unsigned port); + +// A sample describes the complete authenticated endpoint path. It must not be +// populated with the RTT to a proxy or a signaling service. +struct Sample { + unsigned p95_ms = 0, loss_per_mille = 0, observations = 0; + Clock::time_point measured{}; +}; +struct Capacity { + unsigned step_p95_us = 0; + bool measured = false, background_saturated = false; + Clock::time_point sampled{}; +}; +struct Recommendation { + Id member = 0; + unsigned worst_p95_ms = 0, worst_loss_per_mille = 0; + std::string reason; + bool capacity_measured = false; +}; +using Pair = std::pair; +std::optional recommend(const Scope&, const std::map&, const std::map&, + Clock::time_point now); + +// The host can change independently of controller-port and persistent-save +// ownership. The prepared digest binds their full native session snapshot. +struct Proposal { + Scope before; + Id serial = 0, successor = 0, save_owner = 0; + Digest state{}; + bool operator==(const Proposal&) const = default; +}; +enum class Phase { Idle, Offered, Preparing, Committing, Committed, Cancelled }; + +class Handover final { + public: + bool offer(Id authenticated, Proposal, bool waiting, Clock::time_point now, std::string& error); + bool consent(Id authenticated, Id serial, bool accept, Clock::time_point now, std::string& error); + bool bind(Id authenticated, Id serial, const Digest&, std::string& error); + bool prepared(Id authenticated, Id serial, const Digest&, bool routes_ready, Clock::time_point now, + std::string& error); + bool commit(Id authenticated, Id serial, const Digest&, std::string& error); + bool acknowledge(Id authenticated, Id serial, const Digest&, std::string& error); + bool cancel(Id authenticated, Id serial, std::string reason, std::string& error); + void service(const Scope& current, bool waiting, Clock::time_point now); + void reset(); + Phase phase() const { + return phase_; + } + const std::optional& proposal() const { + return proposal_; + } + const std::string& status() const { + return status_; + } + bool can_commit() const; + bool complete() const; + bool frozen() const { + return phase_ == Phase::Committing; + } + bool ready(Id member) const; + bool acknowledged(Id member) const; + std::optional result() const; + + private: + bool expected(Id, Id serial) const; + Phase phase_ = Phase::Idle; + std::optional proposal_; + std::array prepared_{}, acknowledged_{}; + Clock::time_point deadline_{}; + Id highest_serial_ = 0; + std::string status_; +}; + +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/qualification.hpp b/runtime-recomp/src/game/netplay/session_links/qualification.hpp new file mode 100644 index 00000000..791dec93 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/qualification.hpp @@ -0,0 +1,106 @@ +#pragma once +#include "party_link.hpp" +#include +#include +#include + +namespace dkr::runtime::netplay::links { +// Opt-in only inside the existing disposable-profile --self-test-owned check. +// Ordinary launcher/overlay sessions never enable automatic consent. +class HandoverQualification { + bool enabled_ = false, reported_ = false; + Clock::time_point route_report_{}; + + public: + explicit HandoverQualification(bool disposable) { + const auto* value = disposable ? std::getenv("DKR_OWNED_CHECK_HANDOVER") : nullptr; + enabled_ = value && std::string_view(value) == "1"; + } + bool enabled() const { + return enabled_; + } + bool pulse(const void* session, std::string& error) { + if (!enabled_) + return true; + auto hub = dkr::runtime::spectators::party_link(session); + std::scoped_lock lock(hub->mutex); + auto& state = hub->links; + if (state.handover.phase() == Phase::Cancelled) { + error = state.handover.status(); + return false; + } + if (!hub->enabled || hub->party.snapshot().members.size() != 12) + return false; + if (Clock::now() >= route_report_ && !state.finished) { + route_report_ = Clock::now() + std::chrono::seconds(5); + std::fprintf( + stderr, + "[online][handover-check] phase=%u local=%llu registration=%u/%u prepared-state=%u bytes=%zu/%zu inventory=%u status=%s\n", + unsigned(state.handover.phase()), static_cast(hub->local), + unsigned(state.registration_started), unsigned(state.registration_ready), + unsigned(state.prepared_state), state.prepared_bytes.size(), state.expected_transfer, + unsigned(state.inventory_ready), state.status.c_str()); + if (const auto& p = state.handover.proposal()) + for (const auto& m : p->before.members) { + const auto sample = state.samples.find({hub->local, m.id}); + std::fprintf(stderr, "[online][handover-check] member=%llu prepared=%u pongs=%u age-ms=%lld\n", + static_cast(m.id), unsigned(state.handover.ready(m.id)), + sample == state.samples.end() ? 0 : sample->second.observations, + sample == state.samples.end() + ? -1 + : static_cast(std::chrono::duration_cast( + Clock::now() - sample->second.measured) + .count())); + } + } + if (state.last_applied && state.finished) { + const auto& p = state.handover.proposal(); + if (!p || state.save_owner != p->save_owner) { + error = "Host transfer changed the agreed save owner."; + return false; + } + for (const auto& before : p->before.members) { + const auto* member = hub->party.find(before.id); + if (!member || int(member->port ? *member->port : 255) != (before.port < 0 ? 255 : before.port)) { + error = "Host transfer changed a controller port."; + return false; + } + } + if (!reported_) { + reported_ = true; + std::fprintf( + stderr, + "[online][handover-check] complete members=12 ports-preserved=1 save-owner-preserved=1 host=%llu\n", + static_cast(hub->party.snapshot().host)); + } + if (hub->host && Clock::now() >= route_report_) { + route_report_ = Clock::now() + std::chrono::seconds(5); + for (const auto& m : hub->party.snapshot().members) + if (m.port && m.id != hub->local) { + const auto* peer = hub->peer(m.id); + const auto sample = state.samples.find({hub->local, m.id}); + std::fprintf( + stderr, "[online][handover-check] racer=%llu heartbeats=%u heard-ms=%lld direct-pongs=%u\n", + static_cast(m.id), peer ? peer->rtt_count : 0, + peer ? static_cast( + std::chrono::duration_cast(Clock::now() - peer->heard) + .count()) + : -1, + sample == state.samples.end() ? 0 : sample->second.observations); + } + } + return true; + } + const auto& proposal = state.handover.proposal(); + if (proposal && proposal->successor == hub->local && state.handover.phase() == Phase::Offered) + state.consent = true; + if (hub->host && !busy(state)) { + const auto target = std::find_if(hub->party.snapshot().members.begin(), hub->party.snapshot().members.end(), + [](const auto& m) { return m.port && *m.port == 1; }); + if (target != hub->party.snapshot().members.end()) + state.request = target->id; + } + return false; + } +}; +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/quick_join_api.inl b/runtime-recomp/src/game/netplay/session_links/quick_join_api.inl new file mode 100644 index 00000000..b9cf40f7 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/quick_join_api.inl @@ -0,0 +1,166 @@ +std::string local_peer_name() const override { + std::scoped_lock lock(mutex_); + return local_peer_id_; +} +std::string peer_name(const PeerAddress& address) const override { + std::scoped_lock lock(mutex_); + for (const auto& [id, peer] : peers_) + if (peer->address == address) { + const auto alias = peer_aliases_.find(id); + return alias == peer_aliases_.end() ? peer->remote_id : alias->second; + } + return {}; +} +std::string signal_name(std::uint64_t id, std::string_view fallback) const { + std::scoped_lock lock(mutex_); + const auto alias = peer_aliases_.find(id); + return alias == peer_aliases_.end() ? std::string(fallback) : alias->second; +} +std::size_t pinned_route_count_locked() const { + std::set ids; + for (const auto& [name, route] : pinned_routes_) + ids.insert(route.first); + return ids.size(); +} +bool introduce_peer(std::string_view name, bool initiate, PeerAddress& address, std::string& error) override { + if (name.empty() || name.size() > 128 || + name.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") != name.npos) { + error = "Invalid introduced Quick Join peer."; + return false; + } + bool exists = false; + { + std::scoped_lock lock(mutex_); + if (name == local_peer_id_ || + (authorized_remote_.size() >= 12 && !authorized_remote_.contains(std::string(name)))) { + error = "The introduced peer exceeds this lobby's limits."; + return false; + } + const std::string remote(name); + authorized_remote_.insert(remote); + auto pinned = pinned_routes_.find(remote); + if (pinned == pinned_routes_.end()) { + const auto id = next_peer_identifier_.fetch_add(1U, std::memory_order_relaxed); + pinned = pinned_routes_.emplace(remote, std::pair{id, quick_address(id)}).first; + } + address = pinned->second.second; + exists = std::any_of(peers_.begin(), peers_.end(), [&](const auto& p) { + const auto alias = peer_aliases_.find(p.first); + return (p.second->remote_id == name || (alias != peer_aliases_.end() && alias->second == name)) && + p.second->current.load() && + (p.second->route_ready.load() || + std::chrono::steady_clock::now() - p.second->created < std::chrono::seconds(10)); + }); + } + if (initiate && !exists) { + try { + create_offer(std::string(name)); + } catch (...) { + error = "The direct peer route could not be prepared."; + return false; + } + } + error.clear(); + return true; +} +bool prepare_host(std::string bootstrap, std::string& error) override { + if (host_) { + error = "This player is already hosting."; + return false; + } + preparing_host_.store(true); + if (!rekey_quick_join(std::move(bootstrap), error)) { + preparing_host_.store(false); + return false; + } + return true; +} +bool alias_peer(const PeerAddress& address, std::string_view name, std::string& error) override { + if (name.empty() || name.size() > 128 || + name.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") != name.npos) { + error = "Invalid introduced peer alias."; + return false; + } + std::scoped_lock lock(mutex_); + for (const auto& [id, peer] : peers_) + if (peer->address == address) { + if (const auto pinned = pinned_routes_.find(std::string(name)); + pinned != pinned_routes_.end() && pinned->second.first != id) { + error = "That peer name belongs to another lobby route."; + return false; + } + authorized_remote_.erase(peer->remote_id); + if (const auto prior = peer_aliases_.find(id); prior != peer_aliases_.end()) { + authorized_remote_.erase(prior->second); + if (prior->second != peer->remote_id) + pinned_routes_.erase(prior->second); + remote_to_identifier_.erase(prior->second + "\n" + peer->connection_id); + } + const std::string alias(name); + peer_aliases_[id] = alias; + authorized_remote_.insert(alias); + pinned_routes_[alias] = {id, address}; + remote_to_identifier_[alias + "\n" + peer->connection_id] = id; + error.clear(); + return true; + } + // Admission can reserve a route before ICE creates its Peer. A quiet + // successor registration may replace that name in the meantime. + // Preserve the authenticated logical address and move its reservation; + // waiting for a connection to the retired name cannot make progress. + const auto reserved = std::find_if(pinned_routes_.begin(), pinned_routes_.end(), + [&](const auto& p) { return p.second.second == address; }); + if (reserved != pinned_routes_.end()) { + const auto id = reserved->second.first; + const std::string alias(name); + if (const auto collision = pinned_routes_.find(alias); + collision != pinned_routes_.end() && collision->second.first != id) { + error = "That peer name belongs to another lobby route."; + return false; + } + for (auto it = pinned_routes_.begin(); it != pinned_routes_.end();) { + if (it->second.first == id) { + authorized_remote_.erase(it->first); + it = pinned_routes_.erase(it); + } else + ++it; + } + std::erase_if(remote_to_identifier_, [&](const auto& p) { return p.second == id; }); + peer_aliases_[id] = alias; + authorized_remote_.insert(alias); + pinned_routes_[alias] = {id, address}; + error.clear(); + return true; + } + error = "The introduced route is no longer available."; + return false; +} +bool apply_host_role(bool host, std::string_view remote, std::string& error) override { + std::scoped_lock lock(mutex_); + if (host && (!preparing_host_.load() || rekey_state_.load() != QuickJoinRekeyStatus::Committed)) { + error = "The successor's Quick Join registration is not ready."; + return false; + } + if (!host) { + const auto route = std::find_if(peers_.begin(), peers_.end(), [&](const auto& p) { + const auto alias = peer_aliases_.find(p.first); + return (p.second->remote_id == remote || (alias != peer_aliases_.end() && alias->second == remote)) && + p.second->route_ready.load(); + }); + if (route == peers_.end()) { + error = "The successor's connection is not ready."; + return false; + } + remote_host_id_ = std::string(remote); + } + for (const auto& [id, peer] : peers_) { + const auto alias = peer_aliases_.find(id); + const auto& name = alias == peer_aliases_.end() ? peer->remote_id : alias->second; + peer->authority_route.store(!host && name == remote, std::memory_order_release); + } + host_ = host; + preparing_host_.store(false); + route_retry_requested_.store(false); + error.clear(); + return true; +} diff --git a/runtime-recomp/src/game/netplay/session_links/quick_join_state.inl b/runtime-recomp/src/game/netplay/session_links/quick_join_state.inl new file mode 100644 index 00000000..b288896d --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/quick_join_state.inl @@ -0,0 +1,3 @@ +std::atomic host_{false}, preparing_host_{false}; +std::set authorized_remote_; +std::map peer_aliases_; diff --git a/runtime-recomp/src/game/netplay/session_links/registry.cpp b/runtime-recomp/src/game/netplay/session_links/registry.cpp new file mode 100644 index 00000000..f0fed6eb --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/registry.cpp @@ -0,0 +1,99 @@ +#include "registry.hpp" +#include +#include +#include + +namespace dkr::runtime::netplay::links { +namespace { +struct Remote { + std::uint64_t room; + PeerAddress address; + secure::Key key; +}; +struct Registry { + std::mutex mutex; + std::map> sessions; +}; +Registry& registry() { + static auto* const value = new Registry; + return *value; +} +void wipe(Remote& remote) { + volatile std::uint8_t* p = remote.key.data(); + for (unsigned i = 0; i < remote.key.size(); ++i) + p[i] = 0; +} +} // namespace +bool install(const void* owner, std::uint64_t room, std::uint64_t peer, const PeerAddress& address, + const secure::Key& key) { + if (!owner || !room || !peer || !address || std::all_of(key.begin(), key.end(), [](auto c) { return c == 0; })) + return false; + auto& r = registry(); + std::scoped_lock lock(r.mutex); + auto& peers = r.sessions[owner]; + if (peers.size() >= 11 && !peers.contains(peer)) + return false; + if (auto old = peers.find(peer); old != peers.end()) { + if (old->second.room == room && old->second.address == address && old->second.key == key) + return true; + wipe(old->second); + } + peers.insert_or_assign(peer, Remote{room, address, key}); + return true; +} +std::optional receive_key(const void* owner, std::uint64_t room, std::uint64_t peer, + const PeerAddress& address) { + auto& r = registry(); + std::scoped_lock lock(r.mutex); + const auto session = r.sessions.find(owner); + if (session == r.sessions.end()) + return {}; + const auto remote = session->second.find(peer); + if (remote == session->second.end() || remote->second.room != room || remote->second.address != address) + return {}; + return remote->second.key; +} +void revoke(const void* owner, std::uint64_t peer) { + auto& r = registry(); + std::scoped_lock lock(r.mutex); + const auto session = r.sessions.find(owner); + if (session == r.sessions.end()) + return; + const auto remote = session->second.find(peer); + if (remote != session->second.end()) { + wipe(remote->second); + session->second.erase(remote); + } + if (session->second.empty()) + r.sessions.erase(session); +} +void forget(const void* owner) { + auto& r = registry(); + std::scoped_lock lock(r.mutex); + const auto session = r.sessions.find(owner); + if (session == r.sessions.end()) + return; + for (auto& [id, remote] : session->second) + wipe(remote); + r.sessions.erase(session); +} +bool retire_route(const void* owner, std::uint64_t room, const PeerAddress& address) { + auto& r = registry(); + std::scoped_lock lock(r.mutex); + const auto session = r.sessions.find(owner); + if (session == r.sessions.end()) + return false; + bool removed = false; + for (auto it = session->second.begin(); it != session->second.end();) { + if (it->second.room == room && it->second.address == address) { + wipe(it->second); + it = session->second.erase(it); + removed = true; + } else + ++it; + } + if (session->second.empty()) + r.sessions.erase(session); + return removed; +} +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/registry.hpp b/runtime-recomp/src/game/netplay/session_links/registry.hpp new file mode 100644 index 00000000..3b108911 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/registry.hpp @@ -0,0 +1,15 @@ +#pragma once +#include "netplay/datagram_socket.hpp" +#include "netplay/secure_channel.hpp" +#include + +namespace dkr::runtime::netplay::links { +// Installed only by the native owner after an authenticated host introduction. +// This key grants no host privileges; the party decoder still checks message +// kind, current controller owner and immutable input lease after AEAD validation. +bool install(const void* session, std::uint64_t room, std::uint64_t peer, const PeerAddress&, const secure::Key&); +std::optional receive_key(const void* session, std::uint64_t room, std::uint64_t peer, const PeerAddress&); +void revoke(const void* session, std::uint64_t peer); +bool retire_route(const void* session, std::uint64_t room, const PeerAddress&); +void forget(const void* session); +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/state.hpp b/runtime-recomp/src/game/netplay/session_links/state.hpp new file mode 100644 index 00000000..cbac8784 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/state.hpp @@ -0,0 +1,183 @@ +#pragma once +#include "policy.hpp" +#include "transfer.hpp" +#include +#include +#include + +namespace dkr::runtime::netplay::links { +// Version 2 transfers the authenticated architecture inventory. Older local +// playtests retain the ordinary host route and cannot enter this handover. +inline constexpr std::uint8_t ProtocolVersion = 2; +enum class Kind : std::uint8_t { + Hello = 1, + Introduce, + Ping, + Pong, + Report, + Offer, + Accept, + Prepare, + Prepared, + Commit, + Acknowledge, + Release, + Cancel, + Registration, + SaveChunk, + SaveReceipt, + Activated, + Finished, + Inventory +}; +struct Packet { + Kind kind = Kind::Hello; + Id room = 0, generation = 0; + std::vector body; +}; +inline std::vector encode(const Packet& value) { + if (!value.room || !value.generation || value.body.size() > 11500) + return {}; + std::vector result{'D', 'K', 'R', 'X', 1, 7, std::uint8_t(value.kind)}; + for (const auto v : {value.room, value.generation}) + for (unsigned i = 0; i < 8; ++i) + result.push_back(std::uint8_t(v >> (i * 8))); + result.insert(result.end(), value.body.begin(), value.body.end()); + return result; +} +inline bool decode(std::span bytes, Packet& value) { + constexpr std::array magic{'D', 'K', 'R', 'X', 1, 7}; + if (bytes.size() < 23 || bytes.size() > 11523 || !std::equal(magic.begin(), magic.end(), bytes.begin()) || + bytes[6] < 1 || bytes[6] > unsigned(Kind::Inventory)) + return false; + value = {}; + value.kind = Kind(bytes[6]); + for (unsigned i = 0; i < 8; ++i) { + value.room |= Id(bytes[7 + i]) << (8 * i); + value.generation |= Id(bytes[15 + i]) << (8 * i); + } + value.body.assign(bytes.begin() + 23, bytes.end()); + return value.room && value.generation; +} +struct Write { + std::vector bytes; + Write& number(Id value, unsigned size = 8) { + for (unsigned i = 0; i < size; ++i) + bytes.push_back(std::uint8_t(value >> (8 * i))); + return *this; + } + Write& data(std::span value) { + bytes.insert(bytes.end(), value.begin(), value.end()); + return *this; + } + Write& text(std::string_view value) { + number(value.size(), 2); + bytes.insert(bytes.end(), value.begin(), value.end()); + return *this; + } +}; +struct Read { + std::span bytes; + std::size_t at = 0; + bool good = true; + Id number(unsigned size = 8) { + if (size > 8 || at > bytes.size() || size > bytes.size() - at) { + good = false; + return 0; + } + Id value = 0; + for (unsigned i = 0; i < size; ++i) + value |= Id(bytes[at++]) << (8 * i); + return value; + } + std::vector data(std::size_t size) { + if (at > bytes.size() || size > bytes.size() - at) { + good = false; + return {}; + } + std::vector result(bytes.begin() + at, bytes.begin() + at + size); + at += size; + return result; + } + std::string text(std::size_t maximum = 128) { + const auto size = number(2); + if (size > maximum) { + good = false; + return {}; + } + const auto value = data(size); + return {value.begin(), value.end()}; + } + bool done() const { + return good && at == bytes.size(); + } +}; +struct Incoming { + Id source; + Packet packet; +}; +struct Introduction { + Id remote = 0; + secure::Key key{}; + std::string endpoint; + Clock::time_point issued{}; +}; +struct State { + Scope scope; + std::set capable; + std::map keys; + std::map introduced; + std::set live_routes; + std::map samples; + std::map capacity; + std::map architectures; + std::map> pings; + std::map> rtts; + std::map last_probe; + std::map> probe_results; + std::deque incoming; + Handover handover; + Id save_owner = 0, request = 0, last_applied = 0, serial = 0; + std::optional consent; + std::optional local_consent; + bool cancel = false; + bool registration_started = false, registration_ready = false, prepared_state = false, released = false, + finished = false; + secure::KeyPair successor_keys{}; + secure::Key successor_capability{}, successor_public{}; + std::string successor_endpoint, successor_invite; + std::set activated; + std::vector prepared_bytes, save_paks, save_records; + TransferBuffer assembly; + TransferBuffer inventory_assembly; + std::vector inventory_bytes; + Digest inventory_hash{}; + std::map pending_keys; + bool inventory_ready = false; + std::map transfer_offsets; + std::size_t expected_transfer = 0; + Clock::time_point finished_until{}; + bool directory_required = false, directory_public = false, directory_accepted = false, directory_committed = false; + bool mod_requested = false, mod_ready = false; + std::string directory_code; + Clock::time_point directory_send{}; + Clock::time_point transfer_send{}; + Clock::time_point hello{}, introduce{}, probe{}, report{}; + std::string status; + bool receive(Id source, std::span bytes) { + Packet packet; + if (incoming.size() >= 96 || !decode(bytes, packet)) + return false; + incoming.push_back({source, std::move(packet)}); + return true; + } + void reset() { + *this = State{}; + } +}; +inline bool busy(const State& state) { + const auto phase = state.handover.phase(); + return phase == Phase::Offered || phase == Phase::Preparing || phase == Phase::Committing || + (phase == Phase::Committed && !state.finished); +} +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/transfer.hpp b/runtime-recomp/src/game/netplay/session_links/transfer.hpp new file mode 100644 index 00000000..93bfdbb1 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/transfer.hpp @@ -0,0 +1,35 @@ +#pragma once +#include "policy.hpp" +#include + +namespace dkr::runtime::netplay::links { +// Waiting-room transfers are bounded independently of racing input queues. +// No file paths, private host key or account credentials enter this bundle. +inline constexpr std::size_t MaximumTransferBytes = 1024 * 1024, TransferChunk = 640; +struct TransferBuffer { + std::vector bytes; + std::vector received; + Id serial = 0; + bool accept(Id token, std::size_t total, std::size_t offset, std::span chunk) { + if (!token || !total || total > MaximumTransferBytes || offset % TransferChunk || offset >= total || + chunk.size() != std::min(TransferChunk, total - offset)) + return false; + if (serial != token) { + serial = token; + bytes.assign(total, 0); + received.assign((total + TransferChunk - 1) / TransferChunk, false); + } + if (bytes.size() != total) + return false; + const auto slot = offset / TransferChunk; + if (received[slot]) + return std::equal(chunk.begin(), chunk.end(), bytes.begin() + offset); + std::copy(chunk.begin(), chunk.end(), bytes.begin() + offset); + received[slot] = true; + return true; + } + bool complete() const { + return !received.empty() && std::all_of(received.begin(), received.end(), [](bool v) { return v; }); + } +}; +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/transport.cpp b/runtime-recomp/src/game/netplay/session_links/transport.cpp new file mode 100644 index 00000000..5773085b --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/transport.cpp @@ -0,0 +1,73 @@ +#include "transport.hpp" +#include "netplay/session_transport.hpp" +#include + +namespace dkr::runtime::netplay::links { +std::string local_peer_name(const SessionTransport& transport) { + if (const auto* native = dynamic_cast(&transport)) + return native->local_peer_name(); + return {}; +} +std::string peer_name(const SessionTransport& transport, const PeerAddress& address) { + if (const auto* native = dynamic_cast(&transport)) + return native->peer_name(address); + return transport.quick_join() ? std::string{} : DatagramSocket::describe(address); +} +bool introduce_peer(SessionTransport& transport, std::string_view endpoint, bool initiate, PeerAddress& address, + std::string& error) { + if (auto* native = dynamic_cast(&transport)) + return native->introduce_peer(endpoint, initiate, address, error); + if (transport.quick_join()) { + error = "This transport does not support introduced peers."; + return false; + } + const auto colon = endpoint.rfind(':'); + if (colon == endpoint.npos) { + error = "Invalid introduced endpoint."; + return false; + } + unsigned port = 0; + for (const auto c : endpoint.substr(colon + 1)) { + if (c < '0' || c > '9' || port > 6553) { + error = "Invalid introduced port."; + return false; + } + port = port * 10 + unsigned(c - '0'); + } + if (!port || port > 65535) { + error = "Invalid introduced port."; + return false; + } + return DatagramSocket::resolve(endpoint.substr(0, colon), std::uint16_t(port), address, error); +} +bool prepare_host(SessionTransport& transport, std::string bootstrap, std::string& error) { + if (auto* native = dynamic_cast(&transport)) + return native->prepare_host(std::move(bootstrap), error); + if (!transport.quick_join() && transport.is_open()) { + error.clear(); + return true; + } + error = "This transport cannot prepare a host handover."; + return false; +} +bool alias_peer(SessionTransport& transport, const PeerAddress& address, std::string_view name, std::string& error) { + if (auto* native = dynamic_cast(&transport)) + return native->alias_peer(address, name, error); + if (!transport.quick_join()) { + error.clear(); + return true; + } + error = "This transport cannot prepare a peer alias."; + return false; +} +bool apply_host_role(SessionTransport& transport, bool host, std::string_view remote, std::string& error) { + if (auto* native = dynamic_cast(&transport)) + return native->apply_host_role(host, remote, error); + if (!transport.quick_join()) { + error.clear(); + return true; + } + error = "This transport cannot transfer host ownership."; + return false; +} +} // namespace dkr::runtime::netplay::links diff --git a/runtime-recomp/src/game/netplay/session_links/transport.hpp b/runtime-recomp/src/game/netplay/session_links/transport.hpp new file mode 100644 index 00000000..11a52ab2 --- /dev/null +++ b/runtime-recomp/src/game/netplay/session_links/transport.hpp @@ -0,0 +1,28 @@ +#pragma once +#include +#include + +namespace dkr::runtime::netplay { +class SessionTransport; +struct PeerAddress; +namespace links { +// Optional first-party interface. The frozen SessionTransport ABI is intact. +// Only the authenticated native owner may introduce routes or change roles. +class IntroducedTransport { + public: + virtual ~IntroducedTransport() = default; + virtual std::string local_peer_name() const = 0; + virtual std::string peer_name(const PeerAddress&) const = 0; + virtual bool introduce_peer(std::string_view, bool, PeerAddress&, std::string&) = 0; + virtual bool prepare_host(std::string, std::string&) = 0; + virtual bool alias_peer(const PeerAddress&, std::string_view, std::string&) = 0; + virtual bool apply_host_role(bool, std::string_view, std::string&) = 0; +}; +std::string local_peer_name(const SessionTransport&); +std::string peer_name(const SessionTransport&, const PeerAddress&); +bool introduce_peer(SessionTransport&, std::string_view, bool, PeerAddress&, std::string&); +bool prepare_host(SessionTransport&, std::string, std::string&); +bool alias_peer(SessionTransport&, const PeerAddress&, std::string_view, std::string&); +bool apply_host_role(SessionTransport&, bool, std::string_view, std::string&); +} // namespace links +} // namespace dkr::runtime::netplay diff --git a/runtime-recomp/src/game/online_directory.cpp b/runtime-recomp/src/game/online_directory.cpp index 640a232b..676fa559 100644 --- a/runtime-recomp/src/game/online_directory.cpp +++ b/runtime-recomp/src/game/online_directory.cpp @@ -185,6 +185,8 @@ void run(std::stop_token stop) { std::uint64_t host_revision = 0; auto changed_at = Clock::time_point{}, social_at = Clock::time_point{}; std::string social_context; + std::string retired_host_epoch; + auto pending_host_until = Clock::time_point{}; while (!stop.stop_requested()) { AccountView account; AccountRequest request; @@ -313,6 +315,7 @@ void run(std::stop_token stop) { s.ui.feature_enabled = true; s.ui.running_spectators = capabilities.value("runningSpectators", false); s.ui.social_profiles = capabilities.value("socialProfiles", false); + s.ui.host_handover = capabilities.value("hostHandover", false); s.ui.status = "Connecting to DKR-R Online..."; s.update(); } @@ -409,6 +412,28 @@ void run(std::stop_token stop) { s.social_requests.erase(found); } } + if (operation == "transfer_prepare" || operation == "transfer_accept" || + operation == "transfer_commit") { + const auto data = item.value("data", Json::object()); + std::lock_guard lock(s.bridge_mutex); + for (auto& [owner, bridge] : s.bridges) { + std::lock_guard own(bridge->mutex); + if (bridge->commands.size() < 32) + bridge->commands.push_back({{"type", "host_transfer_result"}, + {"operation", operation}, + {"ok", item.value("ok", false)}, + {"data", data}, + {"error", item.value("error", Json::object())}}); + } + if (operation == "transfer_commit" && item.value("ok", false)) { + retired_host_epoch = string(data, "epoch", 80); + host_id.clear(); + host_epoch.clear(); + last_state.clear(); + host_revision = 0; + } + continue; + } if (operation == "social") { std::vector members; const auto data = item.value("data", Json::object()); @@ -484,6 +509,17 @@ void run(std::stop_token stop) { s.outbox.push_back({{"type", "cancel"}, {"id", string(data, "id", 80)}}); } } + } else if (type == "host_transferred") { + host_id = string(item, "id", 80); + host_epoch = string(item, "epoch", 80); + host_revision = item.value("revision", std::uint64_t(0)); + last_state.clear(); + pending_host_until = now + std::chrono::seconds(120); + { + std::lock_guard lock(s.mutex); + s.ui.public_desired = string(item, "visibility") == "public" && !s.ui.hidden; + s.update(); + } } else if (type == "intent" || type == "revoke") { std::lock_guard lock(s.bridge_mutex); for (auto& [owner, bridge] : s.bridges) { @@ -553,6 +589,7 @@ void run(std::stop_token stop) { social_at = now + std::chrono::seconds(5); } if (!host.is_null()) { + pending_host_until = {}; host.erase("host"); const auto epoch = string(host, "epoch", 80), serialized = host.dump(); bool updating; @@ -561,7 +598,7 @@ void run(std::stop_token stop) { updating = std::any_of(s.pending.begin(), s.pending.end(), [](const auto& p) { return p.second == "room"; }); } - if (!updating && serialized != last_state && now >= changed_at) { + if (epoch != retired_host_epoch && !updating && serialized != last_state && now >= changed_at) { send(s, {{"type", "room"}, {"revision", epoch == host_epoch ? host_revision : 0}, {"state", host}}); @@ -571,7 +608,7 @@ void run(std::stop_token stop) { s.ui.updating = true; s.update(); } - } else if (!host_id.empty()) { + } else if (!host_id.empty() && now >= pending_host_until) { send(s, {{"type", "close"}}); host_id.clear(); host_epoch.clear(); diff --git a/runtime-recomp/src/game/online_directory.hpp b/runtime-recomp/src/game/online_directory.hpp index c0acb6fd..286ab3ff 100644 --- a/runtime-recomp/src/game/online_directory.hpp +++ b/runtime-recomp/src/game/online_directory.hpp @@ -49,6 +49,7 @@ struct View { std::vector rooms; std::vector members; bool social_profiles = false; + bool host_handover = false; }; std::shared_ptr view(); void connect(bool enabled); diff --git a/runtime-recomp/src/game/online_presentation/correction_lifetime.hpp b/runtime-recomp/src/game/online_presentation/correction_lifetime.hpp new file mode 100644 index 00000000..440ff613 --- /dev/null +++ b/runtime-recomp/src/game/online_presentation/correction_lifetime.hpp @@ -0,0 +1,42 @@ +#pragma once +#include +#include +#include + +namespace dkr::runtime::netplay::experimental { +// Accessed under SubmissionDomain::mutex. Weak records do not retain image RAM +// or acquire a final strong reference whose destructor takes that same mutex. +template class CorrectionLifetime final { + struct Entry { + std::weak_ptr image; + const Image* address = nullptr; + std::uint32_t frame = 0; + bool allowed = false; + }; + std::array entries_{}; + + public: + void reset() { + entries_ = {}; + } + bool publish(const std::shared_ptr& image) { + for (auto& entry : entries_) + if (entry.image.expired()) { + entry = {image, image.get(), image->descriptor().frame, true}; + return true; + } + return false; + } + bool eligible(const Image* image) const { + for (const auto& entry : entries_) + if (entry.address == image && !entry.image.expired()) + return entry.allowed; + return false; + } + void retire(std::uint32_t first, bool correction) { + for (auto& entry : entries_) + if (!entry.image.expired() && (!correction || entry.frame >= first)) + entry.allowed = false; + } +}; +} // namespace dkr::runtime::netplay::experimental diff --git a/runtime-recomp/src/game/online_stability/host_settings_service.inl b/runtime-recomp/src/game/online_stability/host_settings_service.inl index f320e2d4..e4bfafe9 100644 --- a/runtime-recomp/src/game/online_stability/host_settings_service.inl +++ b/runtime-recomp/src/game/online_stability/host_settings_service.inl @@ -14,8 +14,9 @@ stability::HostSettingsContext context; context.spectator_capable = party->enabled; context.playing = bool(party->launch) || state_ == ConnectionState::Running || state_ == ConnectionState::Loading; - context.transition = party->stopping || party->returned || state_ == ConnectionState::Loading || - launch_countdown_active_ || (!context.playing && lobby_.room().phase != RoomPhase::Waiting); + context.transition = party->stopping || party->returned || dkr::runtime::netplay::links::busy(party->links) || + state_ == ConnectionState::Loading || launch_countdown_active_ || + (!context.playing && lobby_.room().phase != RoomPhase::Waiting); context.occupied_ports = 1; if (party->enabled) { for (const auto& member : party->party.snapshot().members) diff --git a/runtime-recomp/src/game/online_stability/live_delay.cpp b/runtime-recomp/src/game/online_stability/live_delay.cpp index 6e3e64e3..62f40e33 100644 --- a/runtime-recomp/src/game/online_stability/live_delay.cpp +++ b/runtime-recomp/src/game/online_stability/live_delay.cpp @@ -189,7 +189,7 @@ void LiveDelay::send(Member target, DelayMessage m) { m.room = room_; m.epoch = epoch_; m.controls = controls_; - m.frame = m.kind == DelayKind::Hello ? clock_frontier_ : frame_; + m.frame = (m.kind == DelayKind::Hello || m.kind == DelayKind::Report) ? clock_frontier_ : frame_; (void)control_->send(target, encode(m)); } void LiveDelay::apply(unsigned value, Clock::time_point now) { @@ -204,6 +204,14 @@ void LiveDelay::apply(unsigned value, Clock::time_point now) { current_ = value; applied_at_ = now; } +void LiveDelay::record_report(Member source, const DelayMessage& message, Clock::time_point now) { + auto& report = reports_[source]; + if (now < report.at || now - report.at > std::chrono::seconds(2)) + report.cost = {}; + report.cost.observe(message.frame, message.work_us, message.replay_us, message.interval_us); + report.message = message; + report.at = now; +} void LiveDelay::receive(const Identity& id, Member source, const DelayMessage& m, Clock::time_point now) { if (m.room != room_ || m.epoch != epoch_ || m.controls != controls_ || !id.dynamic) return; @@ -231,7 +239,7 @@ void LiveDelay::receive(const Identity& id, Member source, const DelayMessage& m return; const auto previous = reports_.find(source); if (m.sequence && (previous == reports_.end() || m.sequence > previous->second.message.sequence)) - reports_[source] = {m, now}; + record_report(source, m, now); } return; } @@ -436,8 +444,8 @@ void LiveDelay::pulse(std::uint64_t epoch, std::uint64_t controls, std::uint32_t report.room = room_; report.epoch = epoch_; report.controls = controls_; - report.frame = frame_; - reports_[id.local] = {report, now}; + report.frame = clock_frontier_; + record_report(id.local, report, now); } else send(id.host, report); late_ = waits_ = samples_ = 0; @@ -491,6 +499,8 @@ void LiveDelay::pulse(std::uint64_t epoch, std::uint64_t controls, std::uint32_t if (m.interval_us >= 100000 && std::uint64_t(m.work_us) * 2 > m.interval_us && std::uint64_t(m.replay_us) * 10 > m.interval_us) busy = true; + pressure |= found->second.cost.pressure(m.owner_late[owner], m.replay_us); + busy |= found->second.cost.busy(m.owner_late[owner], m.replay_us); } auto [policy, inserted] = policies_.try_emplace(member); if (inserted) @@ -568,12 +578,13 @@ void LiveDelay::arrival(unsigned owner, std::uint32_t frame, bool repair) { if (repair) return; samples_ = std::min(255U, samples_ + 1); + // Replaying old ticks cannot make a fresh late arrival appear on time. + const auto late = frame < clock_frontier_ ? std::min(48U, clock_frontier_ - frame) : 0; if (owner_samples_[owner] < 255) { ++owner_samples_[owner]; - ++arrival_histogram_[owner][frame < frame_ ? std::min(48U, frame_ - frame) : 0]; + ++arrival_histogram_[owner][late]; } - if (frame < frame_) { - const auto late = std::min(48U, frame_ - frame); + if (late) { late_ = std::max(late_, late); owner_late_[owner] = std::max(owner_late_[owner], late); } diff --git a/runtime-recomp/src/game/online_stability/live_delay.hpp b/runtime-recomp/src/game/online_stability/live_delay.hpp index b713009e..7112b192 100644 --- a/runtime-recomp/src/game/online_stability/live_delay.hpp +++ b/runtime-recomp/src/game/online_stability/live_delay.hpp @@ -2,6 +2,7 @@ #include "control.hpp" #include "live_prediction.hpp" +#include "replay_cost.hpp" #include #include #include @@ -132,6 +133,7 @@ class LiveDelay final { struct Report { DelayMessage message; Clock::time_point at{}; + ReplayCost cost; }; struct Proposal { DelayMessage message; @@ -139,6 +141,7 @@ class LiveDelay final { }; void send(Member target, DelayMessage message); void receive(const Identity&, Member source, const DelayMessage&, Clock::time_point now); + void record_report(Member source, const DelayMessage&, Clock::time_point now); void apply(unsigned delay, Clock::time_point now); std::shared_ptr control_; unsigned fixed_ = 0, current_ = 0, window_ = 0, fill_ = 0, late_ = 0, waits_ = 0, samples_ = 0, local_owner_ = 4; diff --git a/runtime-recomp/src/game/online_stability/lobby_ui.inl b/runtime-recomp/src/game/online_stability/lobby_ui.inl index 30915646..dfad2e34 100644 --- a/runtime-recomp/src/game/online_stability/lobby_ui.inl +++ b/runtime-recomp/src/game/online_stability/lobby_ui.inl @@ -1,4 +1,155 @@ +void DrawOlSessionLinks(float width) { + namespace watch = dkr::runtime::spectators; + namespace links = dkr::runtime::netplay::links; + auto* session = &dkr::runtime::netplay::session(); + auto hub = watch::party_link(session); + struct Snapshot { + links::Scope scope; + std::map samples; + std::map capacity; + links::Handover handover; + std::set introduced; + std::string status; + bool finished = false, directory_public = false; + }; + Snapshot state; + watch::PartySnapshot roster; + bool host = false, waiting = false; + std::uint64_t local = 0; + { + std::scoped_lock lock(hub->mutex); + if (!hub->enabled) + return; + state.scope = hub->links.scope; + state.samples = hub->links.samples; + state.capacity = hub->links.capacity; + state.handover = hub->links.handover; + state.status = hub->links.status; + state.finished = hub->links.finished; + state.directory_public = hub->links.directory_public; + for (const auto& [id, intro] : hub->links.introduced) + state.introduced.insert(id); + roster = hub->party.snapshot(); + host = hub->host; + local = hub->local; + waiting = !hub->launch && !hub->running && !hub->stopping; + } + auto name = [&](std::uint64_t id) { + const auto at = + std::find_if(roster.members.begin(), roster.members.end(), [&](const auto& m) { return m.id == id; }); + return at == roster.members.end() ? std::string("Player") : at->name; + }; + DrawOlFeature( + width, "Session networking", "Direct racer input links keep spectators outside the racing input path.", + [&](float inner) { + const auto now = links::Clock::now(); + unsigned active = 0; + for (const auto& [pair, sample] : state.samples) + if (pair.first == local && links::input_pair(state.scope, pair.first, pair.second) && + sample.observations && now - sample.measured < std::chrono::seconds(2)) + ++active; + OlParagraph(std::to_string(active) + " measured direct racer connections", 14.F, kOlSoft, inner); + if (const auto best = links::recommend(state.scope, state.samples, state.capacity, now)) { + OlParagraph("Suggested host: " + name(best->member), 16.F, kOlCream, inner, true); + OlParagraph(best->reason, 14.F, kOlSoft, inner); + } + const auto phase = state.handover.phase(); + const bool active_transfer = phase == links::Phase::Offered || phase == links::Phase::Preparing || + phase == links::Phase::Committing || + (phase == links::Phase::Committed && !state.finished); + if (!state.status.empty()) + OlParagraph(state.status, 14.F, kOlSoft, inner); + if (active_transfer) { + OlParagraph(state.handover.status(), 15.F, kOlCream, inner, true); + const auto& proposal = state.handover.proposal(); + if (proposal && proposal->successor == local && phase == links::Phase::Offered) { + const bool hidden = state.directory_public && dkr::online::view()->hidden; + if (hidden) + OlParagraph("Turn off Appear offline before accepting this public lobby.", 14.F, kOlSoft, + inner); + { + const OlDisabled disabled(hidden); + if (OlButton("Accept hosting", OlTone::Go)) { + std::scoped_lock lock(hub->mutex); + hub->links.consent = true; + } + } + PaddockGap(6.F); + if (OlButton("Decline")) { + std::scoped_lock lock(hub->mutex); + hub->links.consent = false; + } + } + if (host && phase != links::Phase::Committing && OlButton("Cancel host transfer")) { + std::scoped_lock lock(hub->mutex); + hub->links.cancel = true; + } + } else if (host && waiting) { + const bool supported = state.scope.members.size() == roster.members.size() && + std::all_of(state.scope.members.begin(), state.scope.members.end(), + [](const auto& m) { return m.capable; }); + if (!supported) + OlParagraph("Waiting for every player to confirm host-transfer support.", 14.F, kOlSoft, inner); + for (const auto& member : roster.members) + if (member.id != local) { + ImGui::PushID(std::to_string(member.id).c_str()); + const OlDisabled disabled(!supported); + if (OlButton(("Transfer host to " + member.name).c_str())) { + bool owns_save = false; + { + std::scoped_lock lock(hub->mutex); + owns_save = hub->links.save_owner == local; + } + std::vector paks, records; + std::string error; + if (owns_save) { + std::vector seed; + std::filesystem::path owner; + if (!dkr::runtime::saves::read_online_adventure(true, state.scope.room, seed, owner, + error) || + !dkr::runtime::saves::read_experimental_online_paks(true, state.scope.room, paks, + error)) { + OlNotify(error); + ImGui::PopID(); + continue; + } + const auto path = owner.parent_path() / "custom-records-v1.bin"; + std::error_code ec; + if (std::filesystem::exists(path, ec)) { + const auto size = std::filesystem::file_size(path, ec); + if (ec || size > 20 + 8192 * 76) + error = "The online records could not be prepared for transfer."; + else { + std::ifstream input(path, std::ios::binary); + records.resize(std::size_t(size)); + if (!input.read(reinterpret_cast(records.data()), + std::streamsize(records.size())) || + !dkr::runtime::saves::records::valid(records)) + error = "The online records need recovery before transferring host."; + } + } + } + if (!error.empty()) + OlNotify(error); + else { + std::scoped_lock lock(hub->mutex); + if (owns_save) { + hub->links.save_paks = std::move(paks); + hub->links.save_records = std::move(records); + } + hub->links.request = member.id; + } + } + ImGui::PopID(); + PaddockGap(4.F); + } + } else if (!waiting) + OlParagraph("Host transfers are available after returning to the lobby.", 14.F, kOlSoft, inner); + }); + PaddockGap(12.F); +} void DrawOlJoiningProgress(float width, const OnlineFrame& frame) { + DrawOlSessionLinks(width); if (frame.view.host) return; // The host retains the existing approval cards. const auto rows = dkr::online_stability::control(&dkr::runtime::netplay::session())->joins(); diff --git a/runtime-recomp/src/game/online_stability/replay_cost.hpp b/runtime-recomp/src/game/online_stability/replay_cost.hpp new file mode 100644 index 00000000..c4ab456e --- /dev/null +++ b/runtime-recomp/src/game/online_stability/replay_cost.hpp @@ -0,0 +1,34 @@ +#pragma once +#include +#include +#include + +namespace dkr::online_stability { +// Estimate correction pressure from the existing report fields. Forward work +// excludes replay; no new protocol fields or guest state are introduced. +class ReplayCost final { + std::optional frontier_; + std::uint64_t tick_us_ = 0; + + public: + void observe(std::uint32_t frame, unsigned work, unsigned replay, unsigned interval) { + const auto previous = frontier_; + frontier_ = frame; + if (!previous || frame < *previous) { + tick_us_ = 0; + return; + } + const auto advanced = frame - *previous; + if (!advanced || advanced > 240 || interval < 100000 || interval > 2000000 || replay > work) + return; + const auto sample = std::min(1000000, (work - replay) / advanced); + tick_us_ = tick_us_ ? (3 * tick_us_ + sample + 3) / 4 : sample; + } + bool pressure(unsigned late, unsigned replay) const { + return late > 1 && replay >= 33333 && tick_us_ * late > 33333; + } + bool busy(unsigned late, unsigned replay) const { + return late && replay >= 16667 && tick_us_ * late > 16667; + } +}; +} // namespace dkr::online_stability diff --git a/runtime-recomp/src/game/owner_pump.inl b/runtime-recomp/src/game/owner_pump.inl index ada6f475..4eed7715 100644 --- a/runtime-recomp/src/game/owner_pump.inl +++ b/runtime-recomp/src/game/owner_pump.inl @@ -7,6 +7,30 @@ auto owner = directory::native::owner(this); const auto online = directory::view(); const auto now = std::chrono::steady_clock::now(); + { + auto party = watch::party_link(this); + std::scoped_lock party_lock(party->mutex); + auto bridge = directory::bridge(this); + std::lock_guard bridge_lock(bridge->mutex); + std::erase_if(bridge->commands, [&](const auto& command) { + if (command.value("type", std::string{}) != "host_transfer_result") + return false; + auto& links = party->links; + const auto& proposal = links.handover.proposal(); + const auto data = command.value("data", directory::Json::object()); + if (proposal && data.value("serial", std::string{}) == std::to_string(proposal->serial) && + data.value("digest", std::string{}) == secure::encode_key(proposal->state) && + command.value("ok", false)) { + if (command.value("operation", std::string{}) == "transfer_accept") + links.directory_accepted = true; + if (command.value("operation", std::string{}) == "transfer_commit") + links.directory_committed = true; + } else if (proposal && !command.value("ok", false)) + links.status = command.value("error", directory::Json::object()) + .value("message", std::string("Waiting for the directory host transfer.")); + return true; + }); + } const bool hosting = is_host_ && method_ == ConnectionMethod::QuickJoin && state_ != ConnectionState::Offline && state_ != ConnectionState::Failed; if (!hosting) { @@ -48,7 +72,8 @@ const bool starting = launch_countdown_active_ || launch_stage_ != LaunchStage::Idle || gate->phase == dkr::runtime::party_start::Phase::Countdown || gate->phase == dkr::runtime::party_start::Phase::Committing; - const bool testing = connection_test_active_ || dkr::runtime::rollback_check::active(this); + const bool testing = connection_test_active_ || dkr::runtime::rollback_check::active(this) || + dkr::runtime::netplay::links::busy(party->links); const bool returning = party->stopping || (owned_match_end_ && !owned_match_end_->resumed); const bool live = party->running || state_ == ConnectionState::Running; const bool loading = state_ == ConnectionState::Loading || bool(party->launch); diff --git a/runtime-recomp/src/game/party.cpp b/runtime-recomp/src/game/party.cpp index 276dc5cd..9a6b6abe 100644 --- a/runtime-recomp/src/game/party.cpp +++ b/runtime-recomp/src/game/party.cpp @@ -264,6 +264,20 @@ bool Party::valid(const PartySnapshot& value, std::string& error) { error.clear(); return true; } +bool Party::transfer_host(MemberId authenticated, MemberId successor, std::uint64_t generation, std::string& error) { + if (authenticated != state_.host || successor == authenticated || !find(successor) || state_.handover || + state_.generation == UINT64_MAX || generation != state_.generation + 1) + return no(error, "The prepared host transfer no longer matches this lobby."); + auto next = state_; + next.host = successor; + next.generation = generation; + for (auto& m : next.members) + m.host = m.id == successor; + if (!valid(next, error)) + return false; + state_ = std::move(next); + return true; +} bool Party::replace_verified(PartySnapshot value, std::string& error) { if (!valid(value, error)) return false; diff --git a/runtime-recomp/src/game/party.hpp b/runtime-recomp/src/game/party.hpp index eca767b0..d2f77c6f 100644 --- a/runtime-recomp/src/game/party.hpp +++ b/runtime-recomp/src/game/party.hpp @@ -65,6 +65,7 @@ class Party final { return state_; } bool replace_verified(PartySnapshot value, std::string& error); + bool transfer_host(MemberId authenticated, MemberId successor, std::uint64_t generation, std::string& error); static bool valid(const PartySnapshot& value, std::string& error); private: diff --git a/runtime-recomp/src/game/party_link.cpp b/runtime-recomp/src/game/party_link.cpp index 7d437669..bd9ca210 100644 --- a/runtime-recomp/src/game/party_link.cpp +++ b/runtime-recomp/src/game/party_link.cpp @@ -25,8 +25,8 @@ void party_cancel_swap(const void* s) { bool party_waiting_role(const void* s, MemberId id, bool racer, std::string& e) { auto h = party_link(s); std::scoped_lock lock(h->mutex); - if (!h->enabled || !h->host || h->launch || h->running || h->stopping) { - e = "Roles can only be assigned directly while waiting in the lobby."; + if (!h->enabled || !h->host || h->launch || h->running || h->stopping || net::links::busy(h->links)) { + e = "Finish the current race or host transfer before changing roles."; return false; } std::optional port; @@ -134,6 +134,7 @@ bool PartyLink::participant(MemberId id) const { return m && m->connected && (m->host || m->role == Role::Racer); } void PartyLink::reset_connection() { + links.reset(); queue_age.reset(); for (auto& p : peers) crypto_wipe(p.key.data(), p.key.size()); @@ -228,8 +229,11 @@ bool PartyLink::admit_incoming(MemberId sender, std::span by return false; if (host && !party.find(sender)) return false; - if (!host && sender != authority) - return false; + if (!host && sender != authority) { + const auto* owner = party.find(sender); + if (!owner || owner->role != Role::Racer || !peer(sender) || bytes.size() < 21 || bytes[4] != 19) + return false; + } incoming.push_back({sender, {bytes.begin(), bytes.end()}}); incoming_bytes += bytes.size(); return true; @@ -291,16 +295,63 @@ bool party_receive(const void* session, LinkIncoming& out) { p->incoming.pop_front(); return true; } +std::size_t party_retire_checkpoint(const void* session, MemberId target, std::uint64_t match, std::uint64_t transfer) { + auto p = party_link(session); + std::scoped_lock lock(p->mutex); + std::size_t retired = 0; + if (!target || !match || !transfer) + return 0; + // Only unsent observer chunks/history from this exact game and recipient. + // Racing inputs, repair, authority, lobby and other viewers retain priority + // and identity. Already submitted SCTP data remains bounded by its channel. + for (const auto lane : {3U, 4U}) + for (auto it = p->outgoing[lane].begin(); it != p->outgoing[lane].end();) { + const auto& b = it->bytes; + const bool envelope = + b.size() >= 29 && b[0] == 'D' && b[1] == 'P' && b[2] == 'R' && b[3] == 2 && b[4] == (lane == 4 ? 3 : 7); + const auto number = [&](unsigned at) { + std::uint64_t v = 0; + for (unsigned i = 0; i < 8; ++i) + v |= std::uint64_t(b[at + i]) << (8 * i); + return v; + }; + if (it->target == target && it->kind == LinkKind::Runtime && envelope && number(5) == match && + number(21) != transfer) { + retired += b.size(); + p->outgoing_bytes -= b.size(); + it = p->outgoing[lane].erase(it); + } else + ++it; + } + return retired; +} +bool party_direct_input(const void* session, MemberId target, std::span bytes, + net::TransportTrafficClass traffic) { + auto p = party_link(session); + std::scoped_lock lock(p->mutex); + if (!p->enabled || p->host || target == p->authority || target == p->local || p->local_watching() || + bytes.size() < 21 || bytes[4] != 19 || !p->links.introduced.contains(target) || + !p->links.live_routes.contains(target)) + return false; + const auto* remote = p->party.find(target); + const auto sample = p->links.samples.find({p->local, target}); + if (!remote || remote->role != Role::Racer || sample == p->links.samples.end() || !sample->second.observations || + std::chrono::steady_clock::now() - sample->second.measured > std::chrono::seconds(2)) + return false; + return p->enqueue({target, LinkKind::Runtime, traffic, {bytes.begin(), bytes.end()}}); +} void party_ready(const void* session, bool ready) { auto p = party_link(session); std::scoped_lock lock(p->mutex); + if (net::links::busy(p->links)) + return; p->ready_requested = true; p->ready_value = ready; } void party_start(const void* session) { auto p = party_link(session); std::scoped_lock lock(p->mutex); - if (p->host) + if (p->host && !net::links::busy(p->links)) p->start_requested = true; } void party_stop(const void* session, std::string reason) { diff --git a/runtime-recomp/src/game/party_link.hpp b/runtime-recomp/src/game/party_link.hpp index 0806ed19..50a83f1a 100644 --- a/runtime-recomp/src/game/party_link.hpp +++ b/runtime-recomp/src/game/party_link.hpp @@ -6,6 +6,8 @@ #include "online_stability/traffic_meter.hpp" #include "online_stability/ping_window.hpp" #include "online_stability/live_send_capacity.hpp" +#include "netplay/session_links/state.hpp" +#include "netplay/session_links/registry.hpp" #include #include #include @@ -81,6 +83,7 @@ struct LinkView { // Public/UI functions below NEVER call DirectSession while holding this lock. // No change to DirectSession's class layout or checked-out header is required. struct PartyLink { + net::links::State links; dkr::online_stability::PingWindow ping_window; dkr::online_stability::QueueAgeMeter queue_age; mutable std::recursive_mutex mutex; @@ -132,6 +135,9 @@ bool party_watching(const void* session); bool party_send(const void* session, MemberId target, std::span bytes, net::TransportTrafficClass traffic); bool party_receive(const void* session, LinkIncoming& out); +bool party_direct_input(const void* session, MemberId target, std::span bytes, + net::TransportTrafficClass traffic); +std::size_t party_retire_checkpoint(const void* session, MemberId target, std::uint64_t match, std::uint64_t transfer); void party_ready(const void* session, bool ready); void party_start(const void* session); void party_stop(const void* session, std::string reason); diff --git a/runtime-recomp/src/game/party_runtime.cpp b/runtime-recomp/src/game/party_runtime.cpp index 53e9860a..bb835f2a 100644 --- a/runtime-recomp/src/game/party_runtime.cpp +++ b/runtime-recomp/src/game/party_runtime.cpp @@ -622,7 +622,9 @@ struct PartyRuntime::Impl { playback.request_resync("Loading the confirmed race"); held.reset(); admitted_at.reset(); - if (!server()) + const bool matching = (receiving || decoding.valid()) && last_offer && last_offer->next == at && + last_offer->control_generation == controls; + if (!server() && !matching) send(host, Msg::Need); } activated_release = std::pair{at, controls}; @@ -684,6 +686,7 @@ struct PartyRuntime::Impl { d.actions = held->magic_actions; if (!d.sender.begin(++transfer_serial, std::make_shared(wire))) throw std::runtime_error("Could not stage spectator checkpoint delivery."); + party_retire_checkpoint(key, id, match, d.sender.offer().transfer); } bool current_checkpoint() const { if (!encoded || !feed.covers(encoded->next)) @@ -864,13 +867,14 @@ struct PartyRuntime::Impl { body.n(controls).n(wire::ControllerSampleBytes, 1).data(wire::controller(sample)).data(command_bytes(c)); if (relay) racers(Msg::Input, body.b, Lane::Authoritative); - } else if (source != host) + } else if (source != host && (launch.development || !c.empty() || + !roster.accepts(source, sample.port, sample.lease, sample.cursor))) return; const auto result = driver->receive(cursor.epoch, sample.port, sample.cursor.frame - base, packed(sample.input), c); if (result == ex::InputResult::Accepted || result == ex::InputResult::Duplicate) { - if (result == ex::InputResult::Accepted && !server() && source == host && sample.port == 0 && - roster.accepts(host, 0, sample.lease, sample.cursor)) { + if (result == ex::InputResult::Accepted && !server() && source == host && + roster.accepts(host, sample.port, sample.lease, sample.cursor)) { const auto identity = dkr::online_stability::control(key)->identity(); unsigned rtt = 0; for (const auto& route : identity.routes) @@ -910,7 +914,7 @@ struct PartyRuntime::Impl { return; (void)r.n(); const bool from_host = source == host; - if (!server() && !from_host) + if (!server() && !from_host && type != Msg::LiveInputs) return; if (server() && !roster.find(source)) return; @@ -1070,7 +1074,7 @@ struct PartyRuntime::Impl { std::uint64_t(packet.first) + packet.count > freeze || std::uint64_t(packet.first) + packet.count > std::uint64_t(next().frame) + 49) return; - if (server()) + if (server() || !from_host) for (unsigned i = 0; i < packet.count; ++i) if (!roster.accepts(source, packet.owner, packet.lease, {packet.epoch, packet.first + i})) return; @@ -1375,8 +1379,22 @@ struct PartyRuntime::Impl { const auto bytes = dkr::online_stability::encode_live_inputs(live); if (server()) racers(Msg::LiveInputs, bytes, Lane::Realtime); - else + else { send(host, Msg::LiveInputs, bytes, Lane::Realtime); + for (auto id : required()) + if (id != local && id != host) { + Write direct; + direct.n('D', 1) + .n('P', 1) + .n('R', 1) + .n(2, 1) + .n(unsigned(Msg::LiveInputs), 1) + .n(match) + .n(++serial) + .data(bytes); + party_direct_input(key, id, direct.b, Lane::Realtime); + } + } return; // Exact old holes retain the independent authority repair lane. } Write body; diff --git a/runtime-recomp/src/game/record_store.inl b/runtime-recomp/src/game/record_store.inl index 27434877..352cde21 100644 --- a/runtime-recomp/src/game/record_store.inl +++ b/runtime-recomp/src/game/record_store.inl @@ -64,6 +64,18 @@ bool begin(const std::filesystem::path& path, bool restore, std::string& error) } return true; } +bool begin_memory(std::span bytes, std::string& error) { + Map next; + if (!bytes.empty() && !decode(bytes, next)) { + error = "The shared online records seed is invalid."; + return false; + } + if (!begin({}, false, error)) + return false; + std::scoped_lock lock(record_mutex); + record_seed = std::move(next); + return true; +} Bytes seed() { std::scoped_lock lock(record_mutex); return encode(record_seed); diff --git a/runtime-recomp/src/game/runtime_online_mods_ui.inl b/runtime-recomp/src/game/runtime_online_mods_ui.inl index 7b3bf4d1..e0548744 100644 --- a/runtime-recomp/src/game/runtime_online_mods_ui.inl +++ b/runtime-recomp/src/game/runtime_online_mods_ui.inl @@ -135,6 +135,9 @@ void PumpOnlineMods() { auto view = g_online_mod_sync->snapshot(); g_online_mod_notice.progress(view.stage); const auto network = session().view(); +// Cached, verified content is promoted by the existing worker, outside +// the network locks. Host transfer never enables local offline selections. +#include "netplay/session_links/mod_owner_ui.inl" if (g_stability_retry_requested && !dkr::lobby_stability::snapshot(g_online_mod_sync.get()).running) { g_stability_retry_requested = false; std::string error; diff --git a/runtime-recomp/src/game/start_gate.hpp b/runtime-recomp/src/game/start_gate.hpp index bfdb29ae..dac941ed 100644 --- a/runtime-recomp/src/game/start_gate.hpp +++ b/runtime-recomp/src/game/start_gate.hpp @@ -43,6 +43,11 @@ inline void forget(const void* owner) { std::scoped_lock lock(r.mutex); r.entries.erase(owner); } +inline bool needs_prepare(const Gate& value, std::uint64_t descriptor, std::uint64_t roster, + std::uint32_t save_generation, std::uint64_t save_hash) { + return !value.launch || value.hash != descriptor || value.roster != roster || + value.save_generation != save_generation || value.save_hash != save_hash; +} // Receipt/cancel metadata is inside the authenticated party envelope. It binds // the descriptor, current roster and verified EEPROM identity, never a slot claim. inline std::vector receipt(unsigned stage, const Gate& g) { diff --git a/runtime-recomp/tests/build_tooling_tests.py b/runtime-recomp/tests/build_tooling_tests.py index 86d9f90e..aeeea882 100644 --- a/runtime-recomp/tests/build_tooling_tests.py +++ b/runtime-recomp/tests/build_tooling_tests.py @@ -75,6 +75,38 @@ def test_new_custom_backgrounds_and_authored_shaders_are_included(self): class ReleaseMetadataTests(unittest.TestCase): + def test_playtest_version_still_requires_matching_appstream_and_tag(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for name in ( + "README.md", + "THIRD_PARTY.md", + "docs/README.md", + "docs/BUILDING.md", + "docs/PLATFORMS.md", + "packaging/RELEASE-README.md", + "packaging/MACOS-BUILD-README.md", + "packaging/linux/dkr-port.appdata.xml", + "patches/manifest.json", + ): + target = root / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("") + (root / "patches/manifest.json").write_text('{"dependencies": []}') + (root / "dependencies.lock.json").write_text('{"dependencies": []}') + with patch.object(release_metadata, "ROOT", root): + for number in (1, 12): + version = f"1.0.16-playtest.{number}" + (root / "VERSION").write_text(version) + metadata = root / "packaging/linux/dkr-port.appdata.xml" + metadata.write_text(f'') + self.assertEqual(release_metadata.main(["--tag", f"Version{version}"]), 0) + with self.assertRaisesRegex(RuntimeError, "doesn't match VERSION"): + release_metadata.main(["--tag", "Version1.0.15"]) + metadata.write_text('') + with self.assertRaisesRegex(RuntimeError, "AppStream"): + release_metadata.main([]) + def test_current_release_metadata(self): self.assertEqual(release_metadata.main(), 0) @@ -120,6 +152,8 @@ def test_invalid_version_is_rejected(self): "1.0.5-beta.15-playtest.0", "1.0.5-beta.15-playtest.15-fix.0", "1.0.5-garbage", + "1.0.16-playtest.0", + "1.0.16-playtest.1-extra", ): with self.subTest(version=version): (root / "VERSION").write_text(version) diff --git a/runtime-recomp/tests/display_session_tests.cpp b/runtime-recomp/tests/display_session_tests.cpp index 1f05785b..6cab51af 100644 --- a/runtime-recomp/tests/display_session_tests.cpp +++ b/runtime-recomp/tests/display_session_tests.cpp @@ -35,6 +35,10 @@ int main() { assert((display::resolve({Aspect::Deck, 800, 1}, 1920, 1080).render == display::Size{1280, 800})); assert((display::resolve({Aspect::Window, 0, 1}, 1280, 800).render == display::Size{1280, 800})); assert((display::resolve({Aspect::Window, 0, 1}, 1920, 1080).render == display::Size{1920, 1080})); + // Captured Gamescope window dimensions: native Auto avoids the legacy + // integer mode's extra pixels, without changing that explicit preference. + assert((display::resolve({Aspect::Window, 0, 1}, 1600, 1000).render == display::Size{1600, 1000})); + assert((display::resolve({Aspect::Window, -1, 1}, 1600, 1000).render == display::Size{1920, 1200})); for (int resolution = 0; resolution <= 2; ++resolution) for (int aspect = 0; aspect < 2; ++aspect) for (int sample : {1, 2, 4, 8}) { diff --git a/runtime-recomp/tests/dkr_json_schema_tests.py b/runtime-recomp/tests/dkr_json_schema_tests.py index 352192b0..65845095 100644 --- a/runtime-recomp/tests/dkr_json_schema_tests.py +++ b/runtime-recomp/tests/dkr_json_schema_tests.py @@ -191,7 +191,7 @@ def test_top_level_shape(self): def test_tracked_samples_validate(self): samples = tracked_samples() - self.assertTrue(any("modding/examples" in str(path) for path in samples)) + self.assertTrue(any("modding/examples" in path.as_posix() for path in samples)) for path in samples: with self.subTest(path=path.relative_to(ROOT).as_posix()): meta = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique_object) diff --git a/runtime-recomp/tests/online_mod_sync_tests.cpp b/runtime-recomp/tests/online_mod_sync_tests.cpp index 76497739..4b17d76e 100644 --- a/runtime-recomp/tests/online_mod_sync_tests.cpp +++ b/runtime-recomp/tests/online_mod_sync_tests.cpp @@ -5,6 +5,7 @@ #include #include #include +#include using namespace dkr::mods; using namespace dkr::mods::online; namespace { @@ -17,6 +18,7 @@ void check(bool value) { struct Hub { std::mutex mutex; bool hosting = false, game_active = false; + unsigned host_slot = 0; std::optional offer; std::array, 4> packets; std::array admitted{}, verified{}, left{}, consent_dropped{}, prepare_dropped{}, chunk_dropped{}; @@ -31,18 +33,18 @@ class Link : public SyncLink { SyncNetworkView view() const override { std::lock_guard lock(hub_.mutex); SyncNetworkView result; - result.host = slot_ == 0; + result.host = slot_ == hub_.host_slot; result.hosting = result.host && hub_.hosting; - result.joining = slot_ && !hub_.admitted[slot_] && !hub_.left[slot_]; + result.joining = !result.host && !hub_.admitted[slot_] && !hub_.left[slot_]; result.game_active = hub_.game_active; result.session_active = hub_.hosting || hub_.game_active; - result.lobby = slot_ && hub_.admitted[slot_]; + result.lobby = !result.host && hub_.admitted[slot_]; result.failed = hub_.left[slot_]; result.failure_reason = hub_.failure_reason[slot_]; - if (slot_ && hub_.hosting) + if (!result.host && hub_.hosting) result.offer = hub_.offer; - for (unsigned i = 1; i < 4; ++i) - if (!hub_.admitted[i] && !hub_.left[i]) + for (unsigned i = 0; i < 4; ++i) + if (i != hub_.host_slot && !hub_.admitted[i] && !hub_.left[i]) result.preparing_requests.push_back(i); return result; } @@ -62,32 +64,33 @@ class Link : public SyncLink { std::lock_guard lock(hub_.mutex); error.clear(); const auto op = decode_message(data); - const auto to = slot_ ? 0 : static_cast(target); + const bool host = slot_ == hub_.host_slot; + const auto to = host ? static_cast(target) : hub_.host_slot; if (to >= 4 || hub_.packets[to].size() >= 32) return false; - if (slot_ && op.operation == Operation::Progress) + if (!host && op.operation == Operation::Progress) ++hub_.progress_reports[slot_]; - if (slot_ && op.operation == Operation::Consent && !hub_.consent_dropped[slot_]) { + if (!host && op.operation == Operation::Consent && !hub_.consent_dropped[slot_]) { hub_.consent_dropped[slot_] = true; return true; } - if (slot_ && op.operation == Operation::Preparing && !hub_.prepare_dropped[slot_]) { + if (!host && op.operation == Operation::Preparing && !hub_.prepare_dropped[slot_]) { hub_.prepare_dropped[slot_] = true; return true; } - if (!slot_ && op.operation == Operation::PayloadChunk) { + if (host && op.operation == Operation::PayloadChunk) { hub_.payload_bytes[to] += op.bytes.size(); if (op.offset == 826 && !hub_.chunk_dropped[to]) { hub_.chunk_dropped[to] = true; return true; } } - hub_.packets[to].push_back({slot_, slot_ ? slot_ : 0, Bytes(data.begin(), data.end())}); + hub_.packets[to].push_back({slot_, host ? 0 : slot_, Bytes(data.begin(), data.end())}); return true; } bool verify_local(std::string_view digest, std::string_view resources, std::string&) override { std::lock_guard lock(hub_.mutex); - if (!valid_digest(resources) || !slot_ || !hub_.offer || digest != hub_.offer->digest) + if (!valid_digest(resources) || slot_ == hub_.host_slot || !hub_.offer || digest != hub_.offer->digest) return false; hub_.verified[slot_] = true; return true; @@ -292,6 +295,45 @@ int main(int argc, char** argv) { std::lock_guard lock(hub.mutex); check(hub.admitted[2]); } + // Promote the exact verified client cache, then use it to serve a + // fresh download after the lobby's authority changes. + std::string promotion_error; + check(a.promote_cached_host(settings(1), promotion_error)); + const auto promoted = wait(a, SyncPhase::HostReady); + check(a.cached_host_active() && promoted.runtime == first.runtime && + promoted.profile->digest == ready.profile->digest); + { + std::lock_guard lock(hub.mutex); + hub.host_slot = 1; + hub.admitted[0] = true; + hub.admitted[2] = false; + hub.verified[2] = false; + hub.payload_bytes[2] = 0; + hub.packets[2].clear(); + } + auto transferred_settings = settings(2); + transferred_settings.online_root = root / "after-transfer-cache"; + check(b.watch_client(transferred_settings, proof)); + wait(b, SyncPhase::Review); + b.consent(true, false); + const auto after_transfer = wait(b, SyncPhase::Verified); + check(after_transfer.runtime && after_transfer.profile->digest == promoted.profile->digest); + { + std::lock_guard lock(hub.mutex); + check(hub.admitted[2] && hub.payload_bytes[2] > 0); + } + // Retained profile metadata is not sufficient if a cached payload + // changed after verification. The candidate must fail closed. + check(!third.manifest->payloads.empty()); + const auto corrupt = + private_storage_path(settings(3).online_root) / "payloads" / third.manifest->payloads.front().digest; + { + std::ofstream out(corrupt, std::ios::binary | std::ios::trunc); + out << "changed"; + } + check(c.promote_cached_host(settings(3), promotion_error)); + const auto rejected = wait(c, SyncPhase::Verified); + check(!rejected.error.empty() && !c.cached_host_active()); } if (argc == 4) { Hub stale; diff --git a/runtime-recomp/tests/online_picture_tests.cpp b/runtime-recomp/tests/online_picture_tests.cpp index bbf4613a..86cc4ffc 100644 --- a/runtime-recomp/tests/online_picture_tests.cpp +++ b/runtime-recomp/tests/online_picture_tests.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include using namespace dkr::runtime::netplay::experimental; int main() { @@ -62,6 +63,92 @@ int main() { assert(!present_gate::requires_gpu_picture(&slot, 10, 20)); ++checks; } + { + PresentationMailbox box; + assert(!box.retire_for_correction(91, 0) && box.begin_epoch(91)); + assert(box.retire_for_correction(91, 0)); + int older_slot = 0, newer_slot = 0; + descriptor.frame = 10; + assert(box.publish(91, descriptor, ram)); + auto older = box.take(); + assert(older); + { + present_gate::Scope scope(registration, older); + present_gate::tag(&state, &older_slot, 100, 200); + } + assert(box.finish_decode(older)); + descriptor.frame = 11; + assert(box.publish(91, descriptor, ram)); + auto newer = box.take(); + assert(newer); + { + present_gate::Scope scope(registration, newer); + present_gate::tag(&state, &newer_slot, 101, 201); + } + assert(box.finish_decode(newer)); + descriptor.frame = 12; + assert(box.publish(91, descriptor, ram)); + // Delay the actual queue consumer across a CPU rewind. Unchanged past + // frames survive; the changed frame and its pending future do not. + bool allowed = false; + { + auto hold = std::make_unique(registration, + present_gate::HoldPoint::BeforeAdmission); + std::thread worker([&] { + auto admission = present_gate::acquire(&older_slot, 100, 200); + allowed = admission.allowed; + }); + assert(hold->wait(std::chrono::seconds(2))); + assert(box.retire_for_correction(91, 11)); + hold.reset(); + worker.join(); + } + assert(allowed && !box.take()); + { + auto rejected = present_gate::acquire(&newer_slot, 101, 201); + assert(!rejected.allowed); + } + for (unsigned frame = 12; frame < 42; ++frame) { + descriptor.frame = frame; + assert(box.publish(91, descriptor, ram)); + auto image = box.take(); + assert(image); + assert(box.finish_decode(image) && box.retire_for_correction(91, frame)); + assert(!SubmissionPermit::acquire(image)); + auto unaffected = present_gate::acquire(&older_slot, 100, 200); + assert(unaffected.allowed); + auto wrong_slot = present_gate::acquire(&older_slot, 101, 200); + assert(!wrong_slot.allowed); + } + assert(box.buffer_statistics().image_allocations <= 4); + assert(box.retire_for_correction(91, 10)); + { + auto denied = present_gate::acquire(&older_slot, 100, 200); + assert(!denied.allowed); + } + assert(box.retire_for_correction(91, 50)); + { + auto denied = present_gate::acquire(&older_slot, 100, 200); + assert(!denied.allowed); + } // Never resurrect. + newer.reset(); + older.reset(); + assert(box.quiescent() && box.begin_epoch(92)); + descriptor.frame = 2; + assert(box.publish(92, descriptor, ram)); + assert(box.retire_for_correction(92, 3)); + auto pending = box.take(); + assert(pending && box.is_current(pending)); + auto admitted = SubmissionPermit::acquire(pending); + assert(admitted); + assert(box.retire_for_restore(92, 50) && !box.is_current(pending) && !box.submissions_drained()); + assert(!SubmissionPermit::acquire(pending)); // Resource retirement is unconditional. + admitted.reset(); + assert(box.submissions_drained() && box.finish_decode(pending)); + pending.reset(); + assert(box.quiescent() && box.begin_epoch(93)); + } + std::cout << checks << " immutable queue-picture checks passed; menus and shared scenes retain native fallback, stale admissions remain rejected.\n"; diff --git a/runtime-recomp/tests/online_stability_tests.cpp b/runtime-recomp/tests/online_stability_tests.cpp index 43f5f79b..a94ff368 100644 --- a/runtime-recomp/tests/online_stability_tests.cpp +++ b/runtime-recomp/tests/online_stability_tests.cpp @@ -877,8 +877,81 @@ void negotiated_trace(bool dynamic, unsigned window, bool impaired, bool loss = std::cout << "delay trace dynamic=" << dynamic << " window=" << window << " impairment=" << impaired << " low=" << low << " high=" << high << " changes=" << changes << '\n'; } +void replay_arrival_regressions() { + const auto start = Clock::time_point(std::chrono::seconds(100)); + auto bridge = std::make_shared(); + bridge->configure({44, 2, 1, true, false, true, {{1, 142, true, 0}}}); + LiveDelay delay(bridge, 1, 20); + delay.local_owner(1); + delay.pulse(91, 1, 100, false, false, start); + bridge->outgoing(); + delay.pulse(91, 1, 90, false, false, start + std::chrono::milliseconds(100)); + bridge->outgoing(); + for (unsigned n = 0; n < 12; ++n) + delay.arrival(0, 95); + delay.arrival(0, 1, true); + delay.arrival(1, 0); // Repair and local input are excluded. + delay.pulse(91, 1, 92, false, false, start + std::chrono::milliseconds(500)); + unsigned reports = 0; + for (const auto& packet : bridge->outgoing()) { + DelayMessage m; + assert(decode(packet.bytes, m)); + if (m.kind == DelayKind::Report) { + ++reports; + assert(m.frame == 100 && m.samples == 12 && m.late_frames == 5 && m.owner_late[0] == 5 && + m.owner_samples[0] == 12 && m.owner_samples[1] == 0); + } + } + assert(reports == 1); + for (unsigned n = 0; n < 12; ++n) + delay.arrival(0, 105); + delay.pulse(91, 1, 100, false, false, start + std::chrono::milliseconds(1000)); + for (const auto& packet : bridge->outgoing()) { + DelayMessage m; + assert(decode(packet.bytes, m)); + if (m.kind == DelayKind::Report) + assert(m.late_frames == 0 && m.owner_late[0] == 0); + } + delay.pulse(92, 1, 0, false, false, start + std::chrono::milliseconds(1500)); + bridge->outgoing(); + delay.arrival(0, 0); + delay.pulse(92, 1, 0, false, false, start + std::chrono::milliseconds(2000)); + for (const auto& packet : bridge->outgoing()) { + DelayMessage m; + assert(decode(packet.bytes, m)); + if (m.kind == DelayKind::Report) + assert(m.frame == 0 && m.late_frames == 0 && m.owner_late[0] == 0); + } +} + +void replay_burst_regressions() { + ReplayCost cost; + cost.observe(100, 0, 0, 500000); + cost.observe(115, 330000, 150000, 500000); + assert(cost.pressure(3, 150000) && !cost.pressure(2, 150000) && cost.busy(2, 150000)); + assert(!cost.pressure(12, 0) && !cost.pressure(3, 1000)); + const auto start = Clock::time_point(std::chrono::seconds(100)); + DelayPolicy policy; + policy.reset(0, start); + const auto growth = policy.evaluate(0, 20, 142, 3, 0, true, true, start + std::chrono::seconds(2), + cost.pressure(3, 150000), cost.busy(3, 150000), 0); + assert(growth && *growth == 1); // Costly bursts matter below 70% average work. + assert(!policy.evaluate(1, 20, 142, 2, 0, true, true, start + std::chrono::seconds(5), false, cost.busy(2, 150000), + 0)); + const auto reduced = + policy.evaluate(1, 20, 142, 0, 0, true, true, start + std::chrono::seconds(8), false, false, 0); + assert(reduced && *reduced == 0); + ReplayCost cheap; + cheap.observe(100, 0, 0, 500000); + cheap.observe(115, 16500, 15000, 500000); + assert(!cheap.pressure(12, 15000) && !cheap.busy(12, 15000)); + cost.observe(0, 100000, 50000, 500000); + assert(!cost.pressure(3, 150000)); +} } // namespace int main() { + replay_arrival_regressions(); + replay_burst_regressions(); background_budget_checks(); host_settings_checks(); delayed_ping_checks(); diff --git a/runtime-recomp/tests/peer_relay_glue_tests.cpp b/runtime-recomp/tests/peer_relay_glue_tests.cpp index a88da93f..cdb4b276 100644 --- a/runtime-recomp/tests/peer_relay_glue_tests.cpp +++ b/runtime-recomp/tests/peer_relay_glue_tests.cpp @@ -154,6 +154,12 @@ int main() { const auto client = route({{1, {1}}, {2, {2}}, {1, {3}}}, table); check(client.size() == 2 && client[0].bytes == Bytes({1}) && client[1].bytes == Bytes({3}), "client sends to the host only"); + table.introduced = {2}; + const Bytes ice{'D', 'K', 'R', 'X', 1, 6, 0}; + const Bytes grant{'D', 'K', 'R', 'X', 1, 3, 0}; + const auto introduced = route({{2, ice}, {2, grant}, {3, ice}, {1, grant}}, table); + check(introduced.size() == 2 && introduced[0].target == 2 && introduced[1].target == 1, + "introduced racers exchange ICE only; relay grants and unknown peers retain host routing"); } std::puts("peer relay glue passed"); return 0; diff --git a/runtime-recomp/tests/regression_harness_tests.py b/runtime-recomp/tests/regression_harness_tests.py index b526668a..c47ae990 100644 --- a/runtime-recomp/tests/regression_harness_tests.py +++ b/runtime-recomp/tests/regression_harness_tests.py @@ -40,7 +40,7 @@ def suite(self, *scenarios): self.suite_path.write_text(json.dumps(value), encoding="utf-8") return value - def run_cli(self, *options, output=None): + def run_cli(self, *options, output=None, cwd=None): self.next_output += 1 output = output or self.root / f"run with spaces {self.next_output}" command = [ @@ -58,7 +58,7 @@ def run_cli(self, *options, output=None): str(output), *map(str, options), ] - child = subprocess.run(command, cwd=self.root, capture_output=True, text=True, timeout=20) + child = subprocess.run(command, cwd=cwd or self.root, capture_output=True, text=True, timeout=20) report_path = output / "report.json" report = json.loads(report_path.read_text()) if report_path.is_file() else None return child, report, output @@ -351,12 +351,13 @@ def test_check_inputs_aggregates_independent_failures_and_honors_selection(self) def test_check_inputs_and_execution_resolve_relative_executable_from_invocation_directory(self): item = self.scenario(expect_stdout=["OK"]) - item["command"][0] = os.path.relpath(sys.executable, self.root.resolve()) + invocation = Path(sys.executable).resolve().parent + item["command"][0] = os.path.join(".", Path(sys.executable).name) self.suite(item) - child, _, output = self.run_cli("--check-inputs") + child, _, output = self.run_cli("--check-inputs", cwd=invocation) self.assert_exit(child, 0) self.assertFalse(output.exists()) - child, report, _ = self.run_cli() + child, report, _ = self.run_cli(cwd=invocation) self.assert_exit(child, 0) self.assertEqual(report["scenarios"][0]["command"][0], str(Path(sys.executable).resolve())) diff --git a/runtime-recomp/tests/release_tools_tests.py b/runtime-recomp/tests/release_tools_tests.py index c2221324..700a7867 100644 --- a/runtime-recomp/tests/release_tools_tests.py +++ b/runtime-recomp/tests/release_tools_tests.py @@ -130,12 +130,21 @@ def test_an_entry_needs_exactly_one_selector(self): class PackageCheckTests(unittest.TestCase): def test_prerelease_labels_are_found_in_narrow_and_wide_text(self): - for label in ("1.0.7+beta.10", "1.0.10-vehicle-playtest.3"): + for label in ("1.0.7+beta.10", "1.0.10-vehicle-playtest.3", "1.0.16-playtest.1", "1.0.16-beta.2"): for data in (b"\0x" + label.encode() + b"\0", b"\0" + label.encode("utf-16-le")): with self.subTest(label=label, wide=len(data) > 20): self.assertIsNotNone(package_release.prerelease_label(data)) self.assertIsNone(package_release.prerelease_label(b"DKR-R 1.0.11 Release Build\0")) + def test_current_playtest_does_not_hide_other_prerelease_labels(self): + current = "1.0.16-playtest.1" + for encoding in ("utf-8", "utf-16-le"): + self.assertIsNone(package_release.prerelease_label(current.encode(encoding), current)) + for stale in ("1.0.15-playtest.1", "1.0.16-playtest.10", "1.0.16-beta.2"): + self.assertEqual( + package_release.prerelease_label((current + "\0" + stale).encode(encoding), current), stale + ) + def test_the_runtime_must_carry_both_contracts(self): data = b"".join(package_release.FEATURES) with self.assertRaisesRegex(ValueError, "Rollback contract"): diff --git a/runtime-recomp/tests/replay_probe/probe_driver.cpp b/runtime-recomp/tests/replay_probe/probe_driver.cpp index 42915797..3977936e 100644 --- a/runtime-recomp/tests/replay_probe/probe_driver.cpp +++ b/runtime-recomp/tests/replay_probe/probe_driver.cpp @@ -9,6 +9,8 @@ namespace dkr::runtime::saves::records { void install(legacy::ModWorld&, std::uint8_t*); } +#include "netplay/session_links/menu_control.hpp" +#include "session_log.hpp" #include "probe_driver.hpp" #include "owned_game.hpp" #include "rom_revision.hpp" @@ -325,7 +327,9 @@ class Component final : public SceneSimulation { independent_restore_ = independent_restore; } bool before_restore(std::uint64_t epoch, std::uint32_t first_frame, std::string& error) override { - if (presentation_ && !presentation_->retire_for_restore(epoch, first_frame)) { + if (presentation_ && !(independent_restore_ && !native_.pending_scene_site + ? presentation_->retire_for_correction(epoch, first_frame) + : presentation_->retire_for_restore(epoch, first_frame))) { error = "Owned render generation refused retirement."; return false; } @@ -366,7 +370,7 @@ class Component final : public SceneSimulation { menu_tick_active() && host_control_ != unsigned(HostControlPolicy::EveryAssignedPort) && (!native_.assigned_ports_released || (host_control_ == unsigned(HostControlPolicy::HostSharedMenus) && menu_for_test() != 3)); - return std::uint8_t(host_only ? 1 : owner_mask_ ? owner_mask_ : 15); + return std::uint8_t(host_only ? (1U << menu_owner_port_) : owner_mask_ ? owner_mask_ : 15); } RestoreStep prepare_tick(std::uint64_t epoch, std::uint32_t frame, bool agreed, std::string& error) override { #if DKR_PROBE_HAS_MOD_SERVICES @@ -677,15 +681,15 @@ class Component final : public SceneSimulation { std::array pads; for (unsigned p = 0; p < 4; ++p) { const bool host_only = - menu_tick && p > 0 && host_control_ != unsigned(HostControlPolicy::EveryAssignedPort) && + menu_tick && host_control_ != unsigned(HostControlPolicy::EveryAssignedPort) && (!native_.assigned_ports_released || (host_control_ == unsigned(HostControlPolicy::HostSharedMenus) && menu_for_test() != 3)); // Filter at the logical simulation frame, never during hardware // sampling. Replay uses the SAME captured menu/release state and // immutable owner-final inputs; no local clock/input reinterpretation. - pads[p] = host_only || (owner_mask_ && !(owner_mask_ & (1U << p))) - ? dkr_probe_pad{} - : dkr_probe_pad{inputs[p].buttons, inputs[p].stick_x, inputs[p].stick_y}; + const auto routed = + dkr::runtime::netplay::links::menu_control::input(inputs, menu_owner_port_, p, host_only, owner_mask_); + pads[p] = {routed.buttons, routed.stick_x, routed.stick_y}; } dkr_probe_component_inputs(pads.data()); dkr_probe_native_restore(native_); @@ -1245,20 +1249,31 @@ class Component final : public SceneSimulation { return true; } bool publish_cpu_frame_for_test(PresentationMailbox& box, std::uint64_t epoch, std::uint32_t frame) { - if (!authored_cpu_ || native_.pending_scene_site) + if (!authored_cpu_ || native_.pending_scene_site) { + dkr::runtime::session_log::write( + "[online][picture-reject] epoch=%llu frame=%u authored=%u pending-scene=%u\n", + static_cast(epoch), frame, unsigned(authored_cpu_), + unsigned(native_.pending_scene_site)); return false; + } const auto word = [&](unsigned offset) { std::uint32_t v; std::memcpy(&v, ram_.data() + offset, 4); return v; }; const auto next_slot = word(DKR_PROBE_REVISION == 77 ? 0x1234E8 : 0x123A68); - if (next_slot > 1) + if (next_slot > 1) { + dkr::runtime::session_log::write("[online][picture-reject] epoch=%llu frame=%u next-slot=%u\n", + static_cast(epoch), frame, next_slot); return false; + } const auto slot = 1 - next_slot; const auto base = DKR_PROBE_REVISION == 77 ? 0x1211F0 : 0x121770; - if (published_preview_loads_ != native_.preview_loads && !box.retire_for_restore(epoch, frame)) + if (published_preview_loads_ != native_.preview_loads && !box.retire_for_restore(epoch, frame)) { + dkr::runtime::session_log::write("[online][picture-reject] epoch=%llu frame=%u retirement=0\n", + static_cast(epoch), frame); return false; + } // Outside tick/commit/checkpoint: presentation ownership never rewinds // with guest RAM and never publishes a historical correction tick. const auto local_scene = scenery_.freeze(native_.presentation.scene); @@ -1274,6 +1289,14 @@ class Component final : public SceneSimulation { ram_, draw_events_, local_scene); if (published) published_preview_loads_ = native_.preview_loads; + else { + const auto buffers = box.buffer_statistics(); + dkr::runtime::session_log::write( + "[online][picture-reject] epoch=%llu frame=%u images=%zu reuses=%zu display=%08x-%08x framebuffer=%08x depth=%08x black=%u events=%zu\n", + static_cast(epoch), frame, buffers.image_allocations, buffers.image_reuses, + word(base + slot * 4), word(base + 8), native_.video_framebuffer, native_.video_depthbuffer, + unsigned(native_.video_black), draw_events_.size()); + } return published; } unsigned pending_scene() const { @@ -1923,6 +1946,7 @@ class Component final : public SceneSimulation { dkr_probe_native_state native_{}; std::uint32_t owner_mask_ = 0; std::uint32_t host_control_ = 0; + unsigned menu_owner_port_ = dkr::runtime::netplay::links::menu_control::creating_port(); std::vector> commits_; std::vector draw_events_; // Derived anew by each completed tick, never a live registry. LocalSceneryCapture scenery_; // Immutable visuals; NEVER checkpoint/network state. diff --git a/runtime-recomp/tests/run_private_fixture.py b/runtime-recomp/tests/run_private_fixture.py index bf9dacc8..a8f377d8 100644 --- a/runtime-recomp/tests/run_private_fixture.py +++ b/runtime-recomp/tests/run_private_fixture.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """Run a fixture that requires a fresh private directory; remove its files afterward.""" +import os from pathlib import Path import subprocess import sys @@ -9,7 +10,12 @@ def main(): executable = Path(sys.argv[1]).resolve(strict=True) - with tempfile.TemporaryDirectory(prefix="dkr-private-fixture-") as parent: + directory = str(Path(tempfile.gettempdir()).resolve()) + if os.name == "nt" and not directory.startswith("\\\\?\\"): + # Content-addressed caches can exceed MAX_PATH even under a short TEMP. + # Use the same extended path for creation, the fixture and cleanup. + directory = "\\\\?\\" + directory + with tempfile.TemporaryDirectory(prefix="dkr-private-fixture-", dir=directory) as parent: return subprocess.run([str(executable), str(Path(parent).resolve() / "fixture")]).returncode diff --git a/runtime-recomp/tests/session_links_native_tests.cpp b/runtime-recomp/tests/session_links_native_tests.cpp new file mode 100644 index 00000000..878af1f0 --- /dev/null +++ b/runtime-recomp/tests/session_links_native_tests.cpp @@ -0,0 +1,455 @@ +#include "netplay/direct_session.hpp" +#include "netplay/session_links/registry.hpp" +#include "netplay/session_links/transport.hpp" +#include "online_stability/qualification_delivery.hpp" +#include "party_link.hpp" +#include "start_gate.hpp" +#include +#include +#include +#include +#include + +namespace net = dkr::runtime::netplay; +namespace watch = dkr::runtime::spectators; +using namespace std::chrono_literals; +namespace { +void check(bool value, const std::string& why) { + if (!value) + throw std::runtime_error(why); +} +} // namespace +namespace dkr::runtime::netplay { +struct DirectSessionTestAccess { + static void initialize(std::array& sessions) { + std::array addresses; + std::array keys; + for (unsigned i = 0; i < 12; ++i) { + auto& s = sessions[i]; + { + std::scoped_lock lock(s.mutex_); + s.worker_stop_.store(true); + } + s.state_changed_.notify_all(); + if (s.network_worker_.joinable()) + s.network_worker_.join(); + std::scoped_lock lock(s.mutex_); + std::string error; + check(s.transport_->open(0, error), error); + check(DatagramSocket::resolve("127.0.0.1", s.transport_->local_port(), addresses[i], error), error); + keys[i] = secure::generate_key(); + s.is_host_ = i == 0; + s.state_ = i == 0 ? ConnectionState::Hosting : ConnectionState::Lobby; + s.match_id_ = 71145; + s.sender_id_ = i + 1; + s.host_sender_id_ = 1; + s.local_slot_ = i < 4 ? std::uint8_t(i) : 255; + s.local_name_ = "Native member " + std::to_string(i + 1); + s.room_view_.name = "Full native session links"; + s.last_admission_response_ = s.last_client_request_ = std::chrono::steady_clock::now(); + s.manifest_.architecture = i % 2 ? "aarch64" : "x86_64"; + s.session_save_.assign(512, 42); + s.session_save_generation_ = 1; + s.local_online_save_ready_ = s.local_online_save_acknowledged_ = true; + s.manifest_.session_save_hash = + stable_hash(std::string_view(reinterpret_cast(s.session_save_.data()), 512)); + } + auto& host = sessions[0]; + std::string error; + Rules rules; + rules.maximum_players = 4; + host.host_key_pair_ = secure::generate_key_pair(); + host.invitation_capability_ = secure::generate_key(); + host.invite_ = host.make_invite("127.0.0.1"); + check(host.invite_.size() > 128, "The native fixture must cover a full direct-connect invitation."); + rules.synchronization = SynchronizationMode::ExperimentalRollback; + check(host.lobby_.create("71145", "ABCDEF", "Full native session links", Visibility::Private, "1", + host.local_name_, host.manifest_, rules, error), + error); + for (unsigned i = 1; i < 4; ++i) { + const auto slot = + host.lobby_.join(std::to_string(i + 1), sessions[i].local_name_, sessions[i].manifest_, error); + check(bool(slot), error); + auto& p = host.peers_[i - 1]; + p.active = true; + p.sender_id = i + 1; + p.address = addresses[i]; + p.slot = *slot; + p.key = keys[i]; + p.online_save_ready = true; + } + watch::Party roster; + check(roster.create(1, host.local_name_, error), error); + for (unsigned i = 1; i < 12; ++i) + check(roster.add(i + 1, sessions[i].local_name_, i < 4 ? std::optional(i) : std::nullopt, + error), + error); + host.room_view_ = host.lobby_.room(); + for (unsigned i = 0; i < 12; ++i) { + auto& s = sessions[i]; + s.room_view_ = host.room_view_; + s.key_ = keys[i]; + s.host_address_ = addresses[0]; + auto hub = watch::party_link(&s); + std::scoped_lock lock(hub->mutex); + hub->requested = hub->enabled = hub->admitted = true; + hub->host = i == 0; + hub->local = i + 1; + hub->authority = 1; + hub->room_id = s.match_id_; + hub->links.scope.room = s.match_id_; + hub->links.save_owner = 1; + if (!i) + for (unsigned peer = 0; peer < 12; ++peer) + hub->links.architectures[peer + 1] = sessions[peer].manifest_.architecture; + hub->seed = s.session_save_; + hub->save_hash = s.manifest_.session_save_hash; + hub->save_generation = 1; + check(hub->party.replace_verified(roster.snapshot(), error), error); + if (!i) + for (unsigned peer = 1; peer < 12; ++peer) { + watch::LinkPeer member; + member.id = peer + 1; + member.address = addresses[peer]; + member.key = keys[peer]; + member.heard = std::chrono::steady_clock::now(); + hub->peers.push_back(member); + } + } + } + static void platform_identity(DirectSession& session, unsigned index) { + std::scoped_lock lock(session.mutex_); + check(session.manifest_.architecture == (index % 2 ? "aarch64" : "x86_64"), + "Host handover replaced the local architecture."); + for (unsigned peer = 0; peer < 12; ++peer) + if (peer != index) + check(session.other_architecture_senders_.contains(peer + 1) == ((peer % 2) != (index % 2)), + "Host handover lost the cross-architecture roster."); + } + static void pump(DirectSession& session) { + std::scoped_lock lock(session.mutex_); + session.pump_locked(); + } + static void stale_start_receipt(DirectSession& client, DirectSession& host) { + std::scoped_lock lock(client.mutex_, host.mutex_); + const auto source = dkr::runtime::party_start::gate(&host); + check(bool(source->launch), "The successor did not stage a normal starting grid."); + auto target = dkr::runtime::party_start::gate(&client); + *target = *source; + --target->roster; + target->prepared.clear(); + target->committed.clear(); + } + static void diagnostic(DirectSession& s) { + std::scoped_lock lock(s.mutex_); + auto h = watch::party_link(&s); + std::scoped_lock party_lock(h->mutex); + std::fprintf(stderr, "native id=%llu generation=%llu scope=%llu authority=%llu queued=%zu\n", + (unsigned long long)s.sender_id_, (unsigned long long)h->party.snapshot().generation, + (unsigned long long)h->links.scope.generation, (unsigned long long)s.host_sender_id_, + h->outgoing_bytes); + for (const auto& p : h->peers) { + const auto found = s.received_sequences_.find(p.id); + std::fprintf(stderr, " peer=%llu outbound=%llu received-control=%llu heartbeats=%u\n", + (unsigned long long)p.id, (unsigned long long)p.sequence, + (unsigned long long)(found == s.received_sequences_.end() ? 0 : found->second[0].highest), + p.rtt_count); + } + } + static void send(DirectSession& session, unsigned target, watch::LinkKind kind, + std::span body) { + std::scoped_lock lock(session.mutex_); + auto hub = watch::party_link(&session); + std::scoped_lock party_lock(hub->mutex); + auto* peer = hub->peer(target); + check(peer, "Missing direct test peer"); + const auto payload = watch::link_encode(kind, body); + const auto traffic = + kind == watch::LinkKind::Runtime ? TransportTrafficClass::Realtime : TransportTrafficClass::Control; + protocol::Datagram packet{ + {protocol::MessageType(watch::PartyMessageType), session.match_id_, peer->sequence++, unsigned(traffic)}, + payload}; + const auto bytes = secure::seal(protocol::encode(packet, 14000), peer->key, session.sender_id_, + packet.header.sequence, session.match_id_); + std::string error; + check(session.transport_->send_status(peer->address, bytes, traffic, error) == DatagramSendStatus::Sent, error); + } +}; +} // namespace dkr::runtime::netplay +int main(int argc, char**) try { + { + int owner = 0; + auto hub = watch::party_link(&owner); + hub->enabled = true; + auto packet = [](unsigned kind, std::uint64_t game, std::uint64_t transfer) { + std::vector bytes{'D', 'P', 'R', 2, std::uint8_t(kind)}; + for (auto v : {game, std::uint64_t(1), transfer}) + for (unsigned i = 0; i < 8; ++i) + bytes.push_back(std::uint8_t(v >> (8 * i))); + return bytes; + }; + using Lane = net::TransportTrafficClass; + using Kind = watch::LinkKind; + for (const auto& row : std::array, 7>{ + {{5, 3, 77, 11, Lane::Checkpoint}, + {5, 7, 77, 11, Lane::Replica}, + {5, 3, 77, 12, Lane::Checkpoint}, + {6, 3, 77, 11, Lane::Checkpoint}, + {5, 3, 78, 11, Lane::Checkpoint}, + {5, 19, 77, 11, Lane::Replica}, + {5, 19, 77, 11, Lane::Realtime}}}) { + const auto [target, kind, game, transfer, lane] = row; + check(hub->enqueue({target, Kind::Runtime, lane, packet(kind, game, transfer)}), + "Could not stage checkpoint supersession fixture."); + } + const auto before = hub->outgoing_bytes; + check(watch::party_retire_checkpoint(&owner, 5, 77, 12) == 58, + "Supersession did not discard exactly the old observer chunk and history."); + check(hub->outgoing_bytes == before - 58 && hub->outgoing[4].size() == 3 && hub->outgoing[3].size() == 1 && + hub->outgoing[2].size() == 1, + "Checkpoint supersession touched another game, viewer, racing repair or live input."); + watch::forget_party_link(&owner); + } + { + std::string error; + auto transport = net::make_quick_join_session_transport(false, "ABCDE", error); + check(bool(transport), error); + net::PeerAddress reserved, renamed, other; + check(net::links::introduce_peer(*transport, "dkrr-test-before", false, reserved, error), error); + check(net::links::alias_peer(*transport, reserved, "dkrr-test-after", error), + "A reserved route cannot follow successor registration: " + error); + check(net::links::introduce_peer(*transport, "dkrr-test-after", false, renamed, error) && renamed == reserved, + "Quiet re-registration changed the authenticated logical address."); + check(net::links::introduce_peer(*transport, "dkrr-test-other", false, other, error), error); + check(!net::links::alias_peer(*transport, reserved, "dkrr-test-other", error), + "A reservation alias stole another member's route."); + transport->release_peer_route(reserved); + transport->release_peer_route(other); + for (unsigned i = 0; i < 24; ++i) { + net::PeerAddress temporary; + check(net::links::introduce_peer(*transport, "dkrr-retired-" + std::to_string(i), false, temporary, error), + "Retired reservations leaked admission capacity: " + error); + transport->release_peer_route(temporary); + } + transport->close(); + } + const bool turbulence = argc > 1; + if (turbulence) + check(dkr::online_stability::qualification_delivery::arm(375, 25, 200, 97), + "Native qualification settings are invalid."); + std::array sessions; + net::DirectSessionTestAccess::initialize(sessions); + auto pump = [&] { + for (auto& s : sessions) + net::DirectSessionTestAccess::pump(s); + std::this_thread::sleep_for(1ms); + }; + bool ready = false; + const auto deadline = std::chrono::steady_clock::now() + 10s; + while (std::chrono::steady_clock::now() < deadline) { + pump(); + ready = true; + for (unsigned i = 1; i < 4; ++i) { + auto hub = watch::party_link(&sessions[i]); + std::scoped_lock lock(hub->mutex); + ready = ready && hub->links.introduced.size() == 2; + for (unsigned peer = 2; peer <= 4; ++peer) + if (peer != i + 1) { + const auto at = hub->links.samples.find({i + 1, peer}); + ready = ready && at != hub->links.samples.end() && at->second.observations >= 3; + } + } + if (ready) + break; + } + if (!ready) + for (unsigned i = 0; i < 4; ++i) { + const auto status = sessions[i].view().status; + auto h = watch::party_link(&sessions[i]); + std::scoped_lock lock(h->mutex); + std::fprintf(stderr, "mesh member=%u capable=%zu introduced=%zu samples=%zu members=%zu status=%s\n", i + 1, + h->links.capable.size(), h->links.introduced.size(), h->links.samples.size(), + h->party.snapshot().members.size(), status.c_str()); + } + check(ready, "Four native racers did not establish and measure their authenticated direct input links."); + // Seed after normal room initialization, which deliberately clears stale + // session-link state before any UI can offer a handover. + if (turbulence) { + auto hub = watch::party_link(&sessions[0]); + std::scoped_lock lock(hub->mutex); + hub->links.save_paks.assign(131072, 0x52); + } + for (unsigned i = 4; i < 12; ++i) { + auto hub = watch::party_link(&sessions[i]); + std::scoped_lock lock(hub->mutex); + check(hub->links.introduced.empty() && hub->peers.empty(), "Spectators unexpectedly joined the racer mesh."); + } + std::vector input{'D', 'P', 'R', 2, 19}; + input.resize(29, 0x42); + net::DirectSessionTestAccess::send(sessions[1], 3, watch::LinkKind::Runtime, input); + bool delivered = false; + const auto delivery_deadline = std::chrono::steady_clock::now() + (turbulence ? 3s : 1s); + auto input_retry = std::chrono::steady_clock::now() + 100ms; + while (std::chrono::steady_clock::now() < delivery_deadline && !delivered) { + if (turbulence && std::chrono::steady_clock::now() >= input_retry) { + net::DirectSessionTestAccess::send(sessions[1], 3, watch::LinkKind::Runtime, input); + input_retry = std::chrono::steady_clock::now() + 100ms; + } + pump(); + watch::LinkIncoming incoming; + while (watch::party_receive(&sessions[2], incoming)) + if (incoming.source == 2 && incoming.bytes == input) + delivered = true; + } + check(delivered, "A direct client input did not pass real native AEAD and replay validation."); + // A previous racer may have left before this twelve-member roster formed. + // Its retired pair key must not poison the next successor's inventory. + { + auto hub = watch::party_link(&sessions[0]); + std::scoped_lock lock(hub->mutex); + hub->links.keys[{2, 99}] = net::secure::generate_key(); + } + pump(); + { + auto hub = watch::party_link(&sessions[0]); + std::scoped_lock lock(hub->mutex); + check(!hub->links.keys.contains({2, 99}), "A departed member remained in the host transfer key inventory."); + } + const std::vector stop{'b', 'a', 'd'}; + net::DirectSessionTestAccess::send(sessions[1], 3, watch::LinkKind::Stop, stop); + for (unsigned i = 0; i < 20; ++i) + pump(); + check(!watch::party_link_view(&sessions[2]).stopping, "A directly linked racer acquired host Stop privileges."); + const auto before = watch::party_link_view(&sessions[0]).party; + unsigned current_host = 1; + for (const auto target : {3U, 12U}) { + { + auto hub = watch::party_link(&sessions[current_host - 1]); + std::scoped_lock lock(hub->mutex); + hub->links.request = target; + } + std::optional offered; + const auto offer_deadline = std::chrono::steady_clock::now() + 10s; + while (!offered && std::chrono::steady_clock::now() < offer_deadline) { + pump(); + auto hub = watch::party_link(&sessions[target - 1]); + std::scoped_lock lock(hub->mutex); + if (hub->links.handover.phase() == net::links::Phase::Offered) + offered = hub->links.handover.proposal(); + } + check(bool(offered), "The candidate never received a host transfer offer."); + net::links::Write forged; + forged.number(offered->serial).number(1, 1); + net::DirectSessionTestAccess::send( + sessions[current_host - 1], target, watch::LinkKind::Extension, + net::links::encode({net::links::Kind::Accept, 71145, offered->before.generation, std::move(forged.bytes)})); + const auto consent_deadline = std::chrono::steady_clock::now() + (turbulence ? 1500ms : 50ms); + while (std::chrono::steady_clock::now() < consent_deadline) + pump(); + { + auto hub = watch::party_link(&sessions[target - 1]); + std::scoped_lock lock(hub->mutex); + check(hub->links.handover.phase() == net::links::Phase::Offered && !hub->links.registration_started, + "The old host bypassed the candidate's local consent."); + } + bool transferred = false; + const auto handover_deadline = std::chrono::steady_clock::now() + (turbulence ? 90s : 20s); + while (std::chrono::steady_clock::now() < handover_deadline) { + pump(); + transferred = true; + for (unsigned i = 0; i < sessions.size(); ++i) { + auto hub = watch::party_link(&sessions[i]); + std::scoped_lock lock(hub->mutex); + if (i + 1 == target && hub->links.handover.phase() == net::links::Phase::Offered) + hub->links.consent = true; + transferred = transferred && hub->links.finished && hub->party.snapshot().host == target; + } + if (transferred) + break; + } + if (!transferred) + for (unsigned i = 0; i < sessions.size(); ++i) { + net::DirectSessionTestAccess::diagnostic(sessions[i]); + auto hub = watch::party_link(&sessions[i]); + std::scoped_lock lock(hub->mutex); + std::fprintf( + stderr, + "member=%u host=%llu phase=%u ready=%u state=%u bytes=%zu expected=%zu released=%u final=%u status=%s policy=%s\n", + i + 1, static_cast(hub->party.snapshot().host), + unsigned(hub->links.handover.phase()), hub->links.handover.ready(i + 1), hub->links.prepared_state, + hub->links.assembly.bytes.size(), hub->links.expected_transfer, hub->links.released, + hub->links.finished, hub->links.status.c_str(), hub->links.handover.status().c_str()); + } + check(transferred, "The native twelve-member handover did not finish."); + bool healthy = true; + { + auto hub = watch::party_link(&sessions[target - 1]); + std::scoped_lock lock(hub->mutex); + for (const auto& m : hub->party.snapshot().members) + if (m.port && m.id != target) { + const auto* peer = hub->peer(m.id); + healthy = healthy && peer && peer->rtt_count && std::chrono::steady_clock::now() - peer->heard < 5s; + } + } + if (!healthy) + net::DirectSessionTestAccess::diagnostic(sessions[target - 1]); + check(healthy, "The successor could not pass the real lobby start connection gate."); + for (unsigned i = 0; i < sessions.size(); ++i) { + net::DirectSessionTestAccess::platform_identity(sessions[i], i); + const auto v = watch::party_link_view(&sessions[i]); + check(v.host == (i + 1 == target) && v.party.controls == before.controls, + "Handover changed native controller ownership or left two hosts."); + auto hub = watch::party_link(&sessions[i]); + std::scoped_lock lock(hub->mutex); + check(hub->links.save_owner == 1 && !net::links::busy(hub->links), + "Handover changed persistent save ownership or left start locked."); + if (turbulence) + check(hub->links.save_paks == std::vector(131072, 0x52), + "The chunked shared Pak fixture changed during handover."); + } + current_host = target; + } + // Reproduce a descriptor accepted before the new roster/Room arrives. + // This uses the production socket, countdown, receipt validation and + // release path after transfers to both a racer and a spectator host. + for (unsigned i = 0; i < 4; ++i) + watch::party_ready(&sessions[i], true); + const auto ready_deadline = std::chrono::steady_clock::now() + 5s; + bool all_ready = false; + while (std::chrono::steady_clock::now() < ready_deadline && !all_ready) { + pump(); + auto hub = watch::party_link(&sessions[current_host - 1]); + std::scoped_lock lock(hub->mutex); + all_ready = true; + for (const auto& m : hub->party.snapshot().members) + if (m.port) + all_ready = all_ready && hub->ready[m.id]; + } + check(all_ready, "Transferred racers did not ready for the actual synchronized-start test."); + watch::party_start(&sessions[current_host - 1]); + net::DirectSessionTestAccess::pump(sessions[current_host - 1]); + net::DirectSessionTestAccess::stale_start_receipt(sessions[0], sessions[current_host - 1]); + bool launched = false; + const auto launch_deadline = std::chrono::steady_clock::now() + 15s; + while (std::chrono::steady_clock::now() < launch_deadline && !launched) { + pump(); + launched = true; + for (unsigned i = 0; i < sessions.size(); ++i) { + auto hub = watch::party_link(&sessions[i]); + std::scoped_lock lock(hub->mutex); + launched = launched && bool(hub->launch); + } + } + check(launched, "A stale pre-roster starting-grid receipt prevented synchronized launch after handover."); + for (auto& s : sessions) { + const auto v = watch::party_link_view(&s); + check(v.party.members.size() == 12, "Native membership changed during mesh preparation."); + s.disconnect(); + } + std::puts( + "Actual DirectSession: four racers, eight spectators, authenticated direct input, host-only controls and sequential racer/spectator host handovers passed."); + return 0; +} catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; +} diff --git a/runtime-recomp/tests/session_links_policy_tests.cpp b/runtime-recomp/tests/session_links_policy_tests.cpp new file mode 100644 index 00000000..179a9457 --- /dev/null +++ b/runtime-recomp/tests/session_links_policy_tests.cpp @@ -0,0 +1,213 @@ +#include "netplay/session_links/policy.hpp" +#include "netplay/session_links/state.hpp" +#include "netplay/session_links/registry.hpp" +#include "netplay/session_links/menu_control.hpp" +#include "start_gate.hpp" +#include +#include +#include + +namespace links = dkr::runtime::netplay::links; +using namespace std::chrono_literals; +namespace { +void check(bool value, const char* reason) { + if (!value) { + std::fprintf(stderr, "Session links: %s\n", reason); + std::abort(); + } +} +links::Scope full() { + links::Scope result{77, 1, 9}; + for (unsigned i = 0; i < 12; ++i) + result.members.push_back({i + 1, i < 4 ? int(i) : -1, true}); + return result; +} +links::Proposal proposal() { + links::Proposal result{full(), 1, 3, 1}; + result.state.fill(42); + return result; +} +} // namespace +int main() { + { + namespace start = dkr::runtime::party_start; + start::Gate gate; + gate.launch.emplace(); + gate.hash = 17; + gate.roster = 3; + gate.save_generation = 2; + gate.save_hash = 11; + check(!start::needs_prepare(gate, 17, 3, 2, 11), "an unchanged verified start remains idempotent"); + check(start::needs_prepare(gate, 18, 3, 2, 11), "a changed launch descriptor re-arms the receipt"); + check(start::needs_prepare(gate, 17, 4, 2, 11), "a changed roster re-arms the receipt"); + check(start::needs_prepare(gate, 17, 3, 3, 11), "a new save generation re-arms the receipt"); + check(start::needs_prepare(gate, 17, 3, 2, 12), "a changed save hash re-arms the receipt"); + gate.launch.reset(); + check(start::needs_prepare(gate, 17, 3, 2, 11), "an absent launch is prepared"); + } + std::array pads{11, 22, 33, 44}; + for (unsigned host = 0; host < 4; ++host) + for (unsigned guest = 0; guest < 4; ++guest) { + check(links::menu_control::input(pads, host, guest, true, 15) == (guest ? 0 : pads[host]), + "shared menus follow the successor without moving racing seats"); + check(links::menu_control::input(pads, host, guest, false, 15) == pads[guest], + "assigned gameplay ports retain their own input"); + check(links::menu_control::input(pads, host, guest, false, 5) == + ((guest == 0 || guest == 2) ? pads[guest] : 0), + "unassigned racing ports remain neutral"); + } + { + links::menu_control::CreationPort outer(2); + check(links::menu_control::creating_port() == 2, "owned construction captures the host port"); + { + links::menu_control::CreationPort inner(3); + check(links::menu_control::creating_port() == 3, "nested construction is scoped"); + } + check(links::menu_control::creating_port() == 2, "nested construction restores its caller"); + } + check(links::menu_control::creating_port() == 0, "ordinary world construction retains its original menu owner"); + auto scope = full(); + const auto now = links::Clock::now(); + std::string error; + check(links::valid(scope), "four racers and eight spectators are supported"); + unsigned pairs = 0; + for (auto a : scope.members) + for (auto b : scope.members) + if (a.id < b.id && links::input_pair(scope, a.id, b.id)) + ++pairs; + check(pairs == 6, "the racer mesh has six pairs, not a twelve-player mesh"); + check(!links::input_owner(scope, 5, 0) && links::input_owner(scope, 4, 3), "spectators cannot supply racer input"); + auto wrong = scope; + wrong.members[3].port = 0; + check(!links::valid(wrong), "controller ownership cannot alias"); + wrong = scope; + wrong.members.push_back({13, -1, true}); + check(!links::valid(wrong), "lobby membership is bounded"); + wrong = scope; + wrong.members[0].port = -1; + check(!links::valid(wrong), "a ninth spectator is rejected"); + + std::map samples; + std::map capacity; + for (auto m : scope.members) { + capacity[m.id] = {10000, true, false, now}; + for (auto racer : scope.members) + if (racer.port >= 0 && racer.id != m.id) + samples[{m.id, racer.id}] = {m.id == 3 ? 40U : 150U, 0, 12, now}; + } + auto best = links::recommend(scope, samples, capacity, now); + check(best && best->member == 3 && best->worst_p95_ms == 40, "ranking uses the worst measured racer path"); + capacity[3].step_p95_us = 30000; + check(!links::recommend(scope, samples, capacity, now), "a faster ping cannot recommend an overloaded host"); + capacity[3].step_p95_us = 10000; + capacity[3].background_saturated = true; + check(!links::recommend(scope, samples, capacity, now), "saturated background capacity disqualifies a host"); + capacity[3].background_saturated = false; + samples[{3, 4}].observations = 0; + check(!links::recommend(scope, samples, capacity, now), + "missing racer evidence prevents a misleading recommendation"); + samples[{3, 4}] = {40, 0, 12, now - 6s}; + check(!links::recommend(scope, samples, capacity, now), "stale routes are not ranked"); + samples[{3, 4}] = {40, 0, 12, now}; + capacity.erase(3); + best = links::recommend(scope, samples, capacity, now); + check(best && best->member == 3 && !best->capacity_measured, "unmeasured CPU capacity is explicitly identified"); + + links::TransferBuffer buffer; + std::vector content(900, 42); + check(!buffer.accept(1, links::MaximumTransferBytes + 1, 0, {}), + "transfer allocation is bounded before allocating"); + check(!buffer.accept(1, 900, 1, std::span(content).first(640)), "misaligned offsets are rejected"); + check(buffer.accept(1, 900, 640, std::span(content).subspan(640)) && !buffer.complete(), + "out of order chunks cannot complete a partial transfer"); + check(buffer.accept(1, 900, 0, std::span(content).first(640)) && buffer.complete(), + "all bounded chunks reconstruct the exact session snapshot"); + auto altered = content; + altered[0] ^= 1; + check(!buffer.accept(1, 900, 0, std::span(altered).first(640)), "duplicate conflicting save chunks are rejected"); + check(buffer.bytes == content, "invalid duplicate retains the original prepared snapshot"); + auto wire = links::encode({links::Kind::Offer, 77, 9, {1, 2, 3}}); + links::Packet decoded; + check(links::decode(wire, decoded) && decoded.room == 77 && decoded.generation == 9, + "wire scope survives the bounded codec"); + for (std::size_t i = 0; i < 23; ++i) + check(!links::decode(std::span(wire).first(i), decoded), "truncated host control is rejected"); + wire[6] = 255; + check(!links::decode(wire, decoded), "unknown host control cannot enter the mailbox"); + int owner = 0; + dkr::runtime::netplay::PeerAddress address; + std::string address_error; + check(dkr::runtime::netplay::DatagramSocket::resolve("127.0.0.1", 22222, address, address_error), + "test native route resolves"); + dkr::runtime::netplay::secure::Key pair_key; + pair_key.fill(7); + check(links::install(&owner, 77, 2, address, pair_key), "authenticated owner can introduce a pair key"); + check(links::receive_key(&owner, 77, 2, address) == pair_key, "pair key is available only on its introduced route"); + check(!links::receive_key(&owner, 78, 2, address) && !links::receive_key(&owner, 77, 3, address), + "room and sender confusion cannot reveal a pair key"); + links::forget(&owner); + check(!links::receive_key(&owner, 77, 2, address), "disconnect revokes introduced keys"); + + links::Handover transfer; + auto p = proposal(); + check(!transfer.offer(2, p, true, now, error), "a client cannot offer a host transfer"); + check(!transfer.offer(1, p, false, now, error), "a running game cannot start a waiting-lobby transfer"); + auto old = p; + old.before.members.back().capable = false; + check(!transfer.offer(1, old, true, now, error), "an unsupported spectator prevents an unsafe authority change"); + check(transfer.offer(1, p, true, now, error), "the host can propose a full-lobby transfer"); + check(!transfer.consent(2, 1, true, now, error), "only the candidate can accept"); + check(transfer.consent(3, 1, true, now, error), "candidate accepts without leaving the lobby"); + check(!transfer.bind(3, 1, p.state, error), "only the original host can bind the successor registration"); + auto registered = p.state; + registered[0] ^= 1; + check(transfer.bind(1, 1, registered, error), "registration and shared save bind before readiness votes"); + p.state = registered; + for (unsigned id = 1; id < 12; ++id) + check(transfer.prepared(id, 1, p.state, true, now, error), "member prepares matching state and routes"); + check(!transfer.can_commit(), "the slow twelfth member does not allow a partial commit"); + check(!transfer.bind(1, 1, registered, error), "prepared state cannot change after the first readiness vote"); + auto bad = p.state; + bad[0] ^= 1; + check(!transfer.prepared(12, 1, bad, true, now, error), "a different save/session snapshot cannot be acknowledged"); + check(!transfer.prepared(12, 1, p.state, false, now, error), "unconnected candidates cannot prepare"); + check(!transfer.prepared(13, 1, p.state, true, now, error), "an outsider cannot vote"); + check(transfer.prepared(12, 1, p.state, true, now, error), "the final spectator prepares"); + check(!transfer.commit(3, 1, p.state, error), "the candidate cannot seize ownership"); + check(transfer.commit(1, 1, p.state, error), "the old host commits only after all twelve prepare"); + const auto result = transfer.result(); + check(result && result->host == 3 && result->generation == 10 && result->members == scope.members, + "transfer changes authority and preserves all members and controller ports"); + check(transfer.proposal()->save_owner == 1, "networking handover preserves persistent save ownership"); + for (unsigned id = 1; id < 12; ++id) + check(transfer.acknowledge(id, 1, p.state, error), "committed member acknowledges"); + transfer.service(scope, true, now + 90s); + check(transfer.frozen() && !transfer.complete(), "a lost commit ACK holds start and never restores old authority"); + check(!transfer.cancel(1, 1, "timeout", error), "post-commit timeout cannot produce two hosts"); + check(transfer.commit(1, 1, p.state, error), "commit retransmission is idempotent"); + check(transfer.acknowledge(12, 1, p.state, error) && transfer.complete(), + "delayed spectator ACK finishes transfer"); + check(transfer.acknowledge(12, 1, p.state, error), "duplicate ACK is harmless"); + check(!transfer.acknowledge(12, 2, p.state, error), "stale/mismatched transfer serial is rejected"); + p.serial = 2; + p.before = *result; + p.successor = 4; + check(transfer.offer(3, p, true, now, error), "the new host can offer another transfer"); + transfer.service(p.before, true, now + 21s); + check(transfer.phase() == links::Phase::Cancelled && !transfer.result(), + "pre-commit timeout retains old ownership"); + p.serial = 3; + check(transfer.offer(3, p, true, now, error), "a new proposal can follow cancellation"); + check(transfer.consent(4, 3, false, now, error) && transfer.phase() == links::Phase::Cancelled, + "candidate can decline without losing the existing lobby"); + p.serial = 4; + check(transfer.offer(3, p, true, now, error), "another proposal is allowed"); + auto changed = p.before; + ++changed.generation; + transfer.service(changed, true, now); + check(transfer.phase() == links::Phase::Cancelled, "membership changes invalidate preparation"); + transfer.reset(); + check(transfer.phase() == links::Phase::Idle && !transfer.proposal(), "disconnect clears transfer state"); + std::puts( + "Four-racer/eight-spectator ownership policy, ranking, authentication, rollback-before-commit and commit-ACK recovery passed."); +} diff --git a/runtime-recomp/tests/tidy_changed_tests.py b/runtime-recomp/tests/tidy_changed_tests.py index f2bf7f63..ff56f95e 100644 --- a/runtime-recomp/tests/tidy_changed_tests.py +++ b/runtime-recomp/tests/tidy_changed_tests.py @@ -22,6 +22,13 @@ class LineDiffTests(unittest.TestCase): def test_identical_is_empty(self): self.assertEqual(tidy.line_diff(b"a;\nb;\n", b"a;\nb;\n", "x.cpp"), "") + def test_line_endings_do_not_turn_unchanged_code_into_changed_lines(self): + self.assertEqual(tidy.line_diff(b"a;\nb;\n", b"a;\r\nb;\r\n", "x.cpp"), "") + diff = tidy.line_diff(b"a;\nb;\n", b"a;\r\nB;\r\n", "x.cpp") + self.assertIn("@@ -2 +2 @@", diff) + self.assertNotIn("+a;", diff) + self.assertNotIn("\r", diff) + def test_paths_survive_dash_p1_and_hunks_are_zero_context(self): diff = tidy.line_diff(b"a;\nb;\nc;\n", b"a;\nB;\nc;\n", "src/x.cpp") self.assertIn("+++ b/src/x.cpp\n", diff) diff --git a/scripts/package_ios.py b/scripts/package_ios.py index 7beb9d92..8c16626f 100755 --- a/scripts/package_ios.py +++ b/scripts/package_ios.py @@ -380,6 +380,11 @@ def write_ipa(app: Path, destination: Path) -> None: continue info = zipfile.ZipInfo(f"Payload/DKR-R.app/{path.relative_to(app).as_posix()}") mode = path.stat().st_mode & 0xFFFF + if path == app / "DKR-R": + # The bundle entry point must be executable in the archive, + # including when the staging filesystem has no POSIX modes. + mode = 0o100755 + info.create_system = 3 info.external_attr = mode << 16 info.compress_type = zipfile.ZIP_DEFLATED archive.writestr(info, path.read_bytes()) diff --git a/scripts/port_check.py b/scripts/port_check.py index 5393649e..65b8a03f 100644 --- a/scripts/port_check.py +++ b/scripts/port_check.py @@ -120,8 +120,8 @@ def probe_cmake_args(args, generated: Path, build: Path) -> list[str]: "-B", str(build), "-DCMAKE_BUILD_TYPE=Release", - f"-DDKR_DEPENDENCIES_DIR={args.deps}", - f"-DDKR_PROBE_GENERATED={generated}", + f"-DDKR_DEPENDENCIES_DIR={args.deps.as_posix()}", + f"-DDKR_PROBE_GENERATED={generated.as_posix()}", ] if args.toolchain_file: command.append(f"-DCMAKE_TOOLCHAIN_FILE={args.toolchain_file}") diff --git a/scripts/release/package_release.py b/scripts/release/package_release.py index a737253d..0d22b149 100644 --- a/scripts/release/package_release.py +++ b/scripts/release/package_release.py @@ -66,7 +66,9 @@ FIXTURES = (b"DKR_REPLAY_CAPTURE_FILE", b"DKR_UPDATE_TEST_VERIFIER", b"DKR_WATER_TEST_MAP") # A pre-release label linked into a release binary: 1.0.7+beta.10, # 1.0.10-vehicle-playtest.3 and the like. -PRERELEASE = re.compile(r"\d+\.\d+\.\d+(?:\+beta\.\d+|-[a-z]+-playtest\.)") +PRERELEASE = re.compile( + r"\d+\.\d+\.\d+(?:\+beta\.\d+|-(?:beta\.\d+(?:-playtest\.\d+(?:-fix\.\d+)?)?|(?:[a-z]+-)?playtest\.\d+))" +) class Package: @@ -90,13 +92,13 @@ def tree(source: Path, target: Path) -> None: shutil.copytree(source, target, symlinks=True) -def prerelease_label(data: bytes) -> str | None: +def prerelease_label(data: bytes, allowed: str | None = None) -> str | None: """A pre-release label in the binary, as narrow or UTF-16LE text.""" views = (data.decode("latin-1"), data.decode("utf-16-le", "ignore"), data[1:].decode("utf-16-le", "ignore")) for text in views: - label = PRERELEASE.search(text) - if label: - return label[0] + for label in PRERELEASE.finditer(text): + if label[0] != allowed: + return label[0] return None @@ -116,7 +118,7 @@ def image(path: Path, machine: str, release: bool = False) -> bytes: v = version() if v.encode() not in data and v.encode("utf-16le") not in data: raise ValueError("Release version missing: " + str(path)) - label = prerelease_label(data) + label = prerelease_label(data, v if re.fullmatch(r"\d+\.\d+\.\d+-playtest\.[1-9]\d*", v) else None) if label: raise ValueError(f"Pre-release label linked into {path.name}: {label}") return data @@ -379,7 +381,7 @@ def main(argv: list[str] | None = None) -> int: receipt = { "schema": 2, "version": version(), - "label": f"v{version()} Release Build", + "label": f"v{version()} {'Playtest Build' if '-playtest.' in version() else 'Release Build'}", "platform": a.platform, "arch": a.arch, "rollback_build_ids": package.ids, diff --git a/scripts/tests/test_package_ios.py b/scripts/tests/test_package_ios.py index 5a8b13b0..dc281fc3 100644 --- a/scripts/tests/test_package_ios.py +++ b/scripts/tests/test_package_ios.py @@ -157,6 +157,15 @@ def test_archive_layout_and_executable_mode(self): self.assertEqual(archive.getinfo("Payload/DKR-R.app/DKR-R").external_attr >> 16 & 0o777, 0o755) self.assertFalse(destination.with_suffix(".ipa.partial").exists()) + def test_entry_point_mode_does_not_depend_on_staging_filesystem(self): + self.binary.chmod(0o644) + destination = self.build / "staged.ipa" + package.write_ipa(self.app, destination) + with zipfile.ZipFile(destination) as archive: + binary = archive.getinfo("Payload/DKR-R.app/DKR-R") + self.assertEqual(binary.create_system, 3) + self.assertEqual(binary.external_attr >> 16 & 0o777, 0o755) + if __name__ == "__main__": unittest.main() diff --git a/scripts/tidy_changed.py b/scripts/tidy_changed.py index 26a74729..20c580f9 100644 --- a/scripts/tidy_changed.py +++ b/scripts/tidy_changed.py @@ -27,6 +27,7 @@ from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor import difflib +import io from pathlib import Path import re import shlex @@ -99,8 +100,10 @@ def changed_paths(merge_base: str) -> list[tuple[str | None, str]]: def line_diff(before: bytes, after: bytes, path: str) -> str: """Unified diff with no context, `a/` and `b/` prefixed so `-p1` finds the path.""" - old = before.decode(errors="surrogateescape").splitlines(keepends=True) - new = after.decode(errors="surrogateescape").splitlines(keepends=True) + # Compare in-memory text using universal newlines, as read_text does. This + # produces a review diff only; neither input file is rewritten. + old = io.StringIO(before.decode(errors="surrogateescape"), newline=None).readlines() + new = io.StringIO(after.decode(errors="surrogateescape"), newline=None).readlines() return "".join(difflib.unified_diff(old, new, f"a/{path}", f"b/{path}", n=0)) diff --git a/scripts/validate_release_metadata.py b/scripts/validate_release_metadata.py index 49c8cd32..bb528d76 100644 --- a/scripts/validate_release_metadata.py +++ b/scripts/validate_release_metadata.py @@ -25,7 +25,7 @@ def main(argv: list[str] | None = None) -> int: if args.tag is not None and args.tag != f"Version{version}": fail(f"Tag {args.tag!r} doesn't match VERSION {version!r} (expected Version{version})") if not re.fullmatch( - r"\d+\.\d+\.\d+(?:-beta\.[1-9]\d*(?:-playtest\.[1-9]\d*(?:-fix\.[1-9]\d*)?)?|\+beta\.[1-9]\d*)?", + r"\d+\.\d+\.\d+(?:-beta\.[1-9]\d*(?:-playtest\.[1-9]\d*(?:-fix\.[1-9]\d*)?)?|-playtest\.[1-9]\d*|\+beta\.[1-9]\d*)?", version, ): fail(f"VERSION is not a supported release/beta semantic version: {version!r}") diff --git a/services/online-directory/api/library_api.mjs b/services/online-directory/api/library_api.mjs index 6c169d61..716ace57 100644 --- a/services/online-directory/api/library_api.mjs +++ b/services/online-directory/api/library_api.mjs @@ -3629,7 +3629,7 @@ async function handleOnlineDirectory(request, env) { const headers = { 'Cache-Control': 'no-store', 'Access-Control-Allow-Origin': '*' }; if (url.pathname === '/v1/online/capabilities' && request.method === 'GET') { return Response.json({ protocol: 1, enabled: env.ONLINE_ENABLED === 'true' && !!env.ONLINE_DIRECTORY, - runningSpectators: env.RUNNING_SPECTATORS_ENABLED === 'true', heartbeatSeconds: 20, leaseSeconds: 60 }, { headers }); + runningSpectators: env.RUNNING_SPECTATORS_ENABLED === 'true', hostHandover: true, heartbeatSeconds: 20, leaseSeconds: 60 }, { headers }); } if (env.ONLINE_ENABLED !== 'true' || !env.ONLINE_DIRECTORY) return Response.json({ error: { code: 'disabled', message: 'Public lobbies are not enabled yet.' } }, { status: 503, headers }); diff --git a/services/online-directory/build.py b/services/online-directory/build.py index 1f56cfde..52625630 100644 --- a/services/online-directory/build.py +++ b/services/online-directory/build.py @@ -4,6 +4,7 @@ import hashlib import json from pathlib import Path +import platform import shutil import subprocess import sys @@ -124,7 +125,11 @@ def verify(output): def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) - parser.add_argument("--esbuild", type=Path, default=AUTH.parent / "test-tools/node_modules/.bin/esbuild") + bundler = AUTH.parent / "test-tools/node_modules/.bin/esbuild" + if sys.platform == "win32": + architecture = "arm64" if platform.machine().lower() in ("aarch64", "arm64") else "x64" + bundler = AUTH.parent / f"test-tools/node_modules/@esbuild/win32-{architecture}/esbuild.exe" + parser.add_argument("--esbuild", type=Path, default=bundler) parser.add_argument("--rollback-api", type=Path) parser.add_argument("--rollback-directory", type=Path) parser.add_argument("--archive", type=Path) diff --git a/services/online-directory/directory.mjs b/services/online-directory/directory.mjs index 5ddfe6fe..6ba0c4c2 100644 --- a/services/online-directory/directory.mjs +++ b/services/online-directory/directory.mjs @@ -84,6 +84,7 @@ export class WorldwideDirectory extends DurableObject { CREATE TABLE IF NOT EXISTS joins(id TEXT PRIMARY KEY, account TEXT NOT NULL, instance TEXT NOT NULL, room TEXT NOT NULL, expires INTEGER NOT NULL, data TEXT NOT NULL); CREATE INDEX IF NOT EXISTS join_room ON joins(room,expires); CREATE TABLE IF NOT EXISTS social_members(room TEXT NOT NULL,instance TEXT NOT NULL,account TEXT NOT NULL,sender TEXT NOT NULL,PRIMARY KEY(room,instance),UNIQUE(room,sender)); + CREATE TABLE IF NOT EXISTS host_transfers(room TEXT PRIMARY KEY,expires INTEGER NOT NULL,data TEXT NOT NULL); CREATE TABLE IF NOT EXISTS replies(key TEXT PRIMARY KEY, expires INTEGER NOT NULL, data TEXT NOT NULL); CREATE TABLE IF NOT EXISTS tickets(hash TEXT PRIMARY KEY, expires INTEGER NOT NULL, data TEXT NOT NULL); CREATE TABLE IF NOT EXISTS limits(key TEXT PRIMARY KEY, window INTEGER NOT NULL, count INTEGER NOT NULL); @@ -152,6 +153,7 @@ export class WorldwideDirectory extends DurableObject { for (const row of this.rows('SELECT data FROM joins WHERE expires<=?', now)) this.cancelJoin(JSON.parse(row.data), 'The join request expired.'); this.sql.exec('DELETE FROM replies WHERE expires<=?', now); this.sql.exec('DELETE FROM tickets WHERE expires<=?', now); + this.sql.exec('DELETE FROM host_transfers WHERE expires<=?', now); this.sql.exec('DELETE FROM limits WHERE windowJSON.parse(row.data)).find(t=> + t.epoch===epoch&&t.serial===serial&&t.digest===hash&&t.oldAccount===who.account&&t.oldInstance===who.instance&&t.completed); + if(input.type==='transfer_commit'&&prior)return prior.result; + const room=this.rows('SELECT data FROM rooms').map(row=>JSON.parse(row.data)).find(r=>r.code===code&&r.epoch===epoch); + need(room&&this.roomLive(room),409,'transfer_room','The original lobby is no longer available.'); + need(['waiting','testing'].includes(room.phase),409,'transfer_phase','Return to the lobby before transferring host.'); + if(input.type==='transfer_prepare') { + need(room.owner===who.account&&room.instance===who.instance,403,'owner','Only the current host can prepare this transfer.'); + const member=this.rows('SELECT account,instance FROM social_members WHERE room=? AND sender=?',room.id,sender)[0]; + need(member&&room.socialRoster.includes(sender)&&member.instance!==room.instance, + 403,'transfer_member','The proposed host is not an admitted lobby member.'); + const candidate=this.sessions.get(member.instance); + need(candidate&&this.live(candidate.data)&&candidate.data.account===member.account,409,'transfer_left','The proposed host disconnected.'); + const previous=this.rows('SELECT data FROM host_transfers WHERE room=?',room.id)[0]; + const pending=previous&&JSON.parse(previous.data); + if(pending&&!pending.completed&&pending.serial===serial&&pending.digest===hash&&pending.sender===sender)return {prepared:true,serial,digest:hash}; + const transfer={room:room.id,epoch,serial,digest:hash,code,nextCode,sender,account:member.account,instance:member.instance, + oldAccount:room.owner,oldInstance:room.instance,completed:false,accepted:false}; + this.sql.exec('INSERT OR REPLACE INTO host_transfers VALUES(?,?,?)',room.id,Date.now()+120000,JSON.stringify(transfer)); + return {prepared:true,serial,digest:hash}; + } + if(input.type==='transfer_accept') { + const row=this.rows('SELECT data FROM host_transfers WHERE room=?',room.id)[0],pending=row&&JSON.parse(row.data); + need(pending&&!pending.completed&&pending.instance===who.instance&&pending.account===who.account&&pending.serial===serial&& + pending.digest===hash&&pending.sender===sender&&pending.nextCode===nextCode, + 403,'transfer_member','Only the admitted successor can accept the host prepared session.'); + pending.accepted=true;this.sql.exec('UPDATE host_transfers SET data=?,expires=? WHERE room=?',JSON.stringify(pending),Date.now()+120000,room.id); + return {accepted:true,serial,digest:hash}; + } + need(room.owner===who.account&&room.instance===who.instance,403,'owner','Only the current host can commit this transfer.'); + const row=this.rows('SELECT data FROM host_transfers WHERE room=?',room.id)[0],transfer=row&&JSON.parse(row.data); + need(transfer&&!transfer.completed&&transfer.accepted&&transfer.serial===serial&&transfer.digest===hash&&transfer.nextCode===nextCode&&transfer.sender===sender, + 409,'transfer_consent','Waiting for the admitted successor to confirm the same session.'); + const candidate=this.sessions.get(transfer.instance),member=this.rows('SELECT account,sender FROM social_members WHERE room=? AND instance=?',room.id,transfer.instance)[0]; + need(candidate&&this.live(candidate.data)&&candidate.data.account===transfer.account&&member?.account===transfer.account&&member.sender===sender&& + room.socialRoster.includes(sender),409,'transfer_left','The proposed host disconnected.'); + need(!this.rows('SELECT id FROM rooms WHERE owner=? AND instance=?',transfer.account,transfer.instance).length, + 409,'transfer_busy','The proposed host already owns another lobby.'); + for(const join of this.rows('SELECT data FROM joins WHERE room=?',room.id))this.cancelJoin(JSON.parse(join.data),'The host transferred the lobby. Please request to join again.'); + const oldHost=room.socialHost,wasPublic=room.visibility==='public'; + const next={...room,owner:transfer.account,instance:transfer.instance,hostName:candidate.data.name,socialHost:sender, + code:nextCode,bootstrap:nextCode,revision:room.revision+1,generation:room.generation+1}; + const result={id:next.id,epoch:next.epoch,revision:next.revision,visibility:next.visibility,serial,digest:hash}; + transfer.completed=true;transfer.result=result; + this.ctx.storage.transactionSync(()=>{ + this.saveRoom(next); + this.sql.exec('DELETE FROM social_members WHERE room=? AND instance=?',room.id,transfer.instance); + if(socialSender(oldHost))this.sql.exec('INSERT OR REPLACE INTO social_members VALUES(?,?,?,?)',room.id,who.instance,who.account,oldHost); + this.sql.exec('UPDATE host_transfers SET expires=?,data=? WHERE room=?',Date.now()+120000,JSON.stringify(transfer),room.id); + }); + who.room='';current.socket.serializeAttachment(who);candidate.data.room=room.id;candidate.socket.serializeAttachment(candidate.data); + this.send(candidate,{type:'host_transferred',...result});this.publicChange(next,wasPublic);this.changed();this.record(who.account,'host_transferred',room.id); + return result; + } if (input.type === 'social') { const member=this.rows('SELECT room,sender FROM social_members WHERE instance=? AND account=?',who.instance,who.account) .map(row=>({row,room:this.room(row.room)})).find(entry=>entry.room?.code===input.code && entry.room.socialRoster?.includes(entry.row.sender)); diff --git a/services/online-directory/tests/runtime.cjs b/services/online-directory/tests/runtime.cjs index 3f34f80d..bbb9d562 100644 --- a/services/online-directory/tests/runtime.cjs +++ b/services/online-directory/tests/runtime.cjs @@ -242,6 +242,58 @@ async function main(){ console.log(JSON.stringify({loadSessions:1000,hostedRooms:100,simultaneousJoins:100,seconds:(Date.now()-loadStart)/1000,scope:'Local Cloudflare runtime; no geographical or gameplay claim.'})); }finally{clearInterval(heartbeatTimer);} } + if(process.argv.includes('--handover')){ + const members=[]; + for(let i=0;i<12;i++){ + const account='handover_'+i,token=randomBytes(32).toString('base64url');tokens[account]=token; + await db.prepare('INSERT INTO accounts VALUES(?,?,?,?,?,?,?)').bind(account,account,'Transfer '+i,'player','active',now,now).run(); + await db.prepare('INSERT INTO sessions VALUES(?,?,?,?,?,?,NULL)').bind(createHash('sha256').update(token).digest('base64url'),account,now,now,now+3600,now+86400).run(); + members.push(await open(account)); + } + const state={title:'Twelve member handover',epoch:'full-handover',compatibility:'test-network',visibility:'public',phase:'waiting', + racers:1,maxRacers:4,spectators:0,maxSpectators:8,roster:'1',code:'XFER1',bootstrap:'XFER1',socialHost:'100',socialRoster:['100']}; + let room=(await members[0].call({type:'room',revision:0,state})).data; + for(let i=1;i<12;i++){ + const role=i<4?'racer':'spectator'; + const join=await members[i].call({type:'join',room:room.id,role,key:key(),compatibility:'test-network'}); + check(join.ok,'handover member reserves an authenticated slot'); + await members[0].event('intent',event=>event.join.id===join.data.id); + check((await members[0].call({type:'grant',id:join.data.id,allowed:true,admission:key()})).ok,'handover native admission is authorized'); + await members[i].event('bootstrap',event=>event.id===join.data.id); + check((await members[0].call({type:'consume',id:join.data.id,sender:String(100+i)})).ok,'handover binds account and instance to native sender'); + state[role==='racer'?'racers':'spectators']++;state.socialRoster.push(String(100+i));state.roster=String(i+1); + room=(await members[0].call({type:'room',revision:room.revision,state})).data; + } + const original=room.id; + const transfer={epoch:state.epoch,serial:'1',digest:key(),code:state.code,nextCode:'XFER2',sender:'102'}; + check(!(await members[2].call({type:'transfer_prepare',...transfer})).ok,'candidate cannot prepare a transfer as host'); + check((await members[0].call({type:'transfer_prepare',...transfer})).ok,'current host prepares an admitted candidate'); + equal((await members[0].call({type:'transfer_commit',...transfer})).error.code,'transfer_consent','host cannot transfer without successor consent'); + const duplicate=await open('handover_2'); + check(!(await duplicate.call({type:'transfer_accept',...transfer})).ok,'same account on another instance cannot accept'); + check(!(await members[5].call({type:'transfer_accept',...transfer})).ok,'spectator cannot accept as another sender'); + check(!(await members[2].call({type:'transfer_accept',...transfer,digest:key()})).ok,'successor cannot accept a different native state'); + check((await members[2].call({type:'transfer_accept',...transfer})).ok,'exact admitted candidate accepts prepared digest'); + const committed=await members[0].call({type:'transfer_commit',...transfer});check(committed.ok,'old host commits the acknowledged ownership transfer'); + equal(committed.data.id,original,'host handover preserves directory room identity'); + equal((await members[2].event('host_transferred')).id,original,'successor receives private ownership confirmation'); + equal((await members[0].call({type:'transfer_commit',...transfer})).data.id,original,'lost commit acknowledgement is idempotent'); + await members[0].call({type:'close'}); + check((await members[1].call({type:'list'})).data.rooms.some(r=>r.id===original),'old host close cannot close the successor lobby'); + state.code=state.bootstrap=transfer.nextCode;state.socialHost=transfer.sender;state.roster='13'; + room=(await members[2].call({type:'room',revision:committed.data.revision,state})).data; + equal(room.id,original,'successor updates the existing room rather than duplicating it'); + const visible=(await members[1].call({type:'list'})).data.rooms.find(r=>r.id===original); + equal(visible.racers,4,'four racing slots survive handover');equal(visible.spectators,8,'eight spectators survive handover'); + members[0].socket.close(1000,'former host leaves');await pause(50); + check((await members[1].call({type:'list'})).data.rooms.some(r=>r.id===original),'former host disconnect cannot close the transferred lobby'); + const again={...transfer,serial:'2',digest:key(),code:state.code,nextCode:'XFER3',sender:'111'}; + check((await members[2].call({type:'transfer_prepare',...again})).ok,'successor can prepare a second handover'); + check((await members[11].call({type:'transfer_accept',...again})).ok,'admitted spectator can accept hosting without acquiring a racing slot'); + const second=await members[2].call({type:'transfer_commit',...again});check(second.ok,'second planned handover succeeds');equal(second.data.id,original,'second handover keeps the same full lobby'); + await members[11].call({type:'close'}); + for(const member of [...members,duplicate])try{member.socket.close(1000,'handover test finished');}catch{} + } options.workers[0].bindings.ONLINE_ENABLED='false';options.workers[1].bindings.ONLINE_ENABLED='false'; await mf.setOptions(options); equal((await (await http('/v1/online/capabilities')).json()).enabled,false,'feature disable is advertised'); From 2d95e47ebfbcb53e2d1a219e8a4eda2760a924bc Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Tue, 17 Nov 2026 04:28:43 +0000 Subject: [PATCH 02/31] Use the reviewed newline canonicalization for private audio inputs --- scripts/generate_replay_probe.py | 22 ++++++++-------------- scripts/tests/test_generator_pins.py | 10 ++++++++++ 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/scripts/generate_replay_probe.py b/scripts/generate_replay_probe.py index 637efe35..c3d69003 100644 --- a/scripts/generate_replay_probe.py +++ b/scripts/generate_replay_probe.py @@ -23,11 +23,12 @@ def reviewed_bytes(data: bytes, expected: str) -> bytes | None: """The pinned bytes when data is them, as checked out with LF or CRLF. - Pins are taken from LF checkouts. Git for Windows checks dependencies out - with CRLF by default, so a CRLF copy of the same content passes and comes - back with LF endings. Anything else returns None. + Most pins are LF; the generated audio RSP also has reviewed CRLF inputs. + Return only bytes whose digest equals the existing pin, regardless of the + checkout's newline convention. Anything else returns None. """ - for candidate in (data, data.replace(b"\r\n", b"\n")): + lf = data.replace(b"\r\n", b"\n") + for candidate in (data, lf, lf.replace(b"\n", b"\r\n")): if hashlib.sha256(candidate).hexdigest() == expected: return candidate return None @@ -783,16 +784,9 @@ def audio_rsp_payload(rsp_source=None, dependencies_dir=None): if rsp_source is not None and name.startswith("runtime-recomp/RecompiledRSP/") else audited_input_path(name, dependencies_dir) ) - raw = source_path.read_bytes() - if hashlib.sha256(raw).hexdigest() != expected: - # The reviewed Windows-generated input uses CRLF, whereas a Git - # checkout may contain LF. Admit only newline-equivalent bytes - # that reconstruct the SAME existing pinned input; never relax - # the source-content gate or rewrite a protected input file. - pinned_newlines = raw.replace(b"\r\n", b"\n").replace(b"\n", b"\r\n") - if hashlib.sha256(pinned_newlines).hexdigest() != expected: - raise ValueError(f"Unreviewed private audio RSP input: {name}") - raw = pinned_newlines + raw = reviewed_bytes(source_path.read_bytes(), expected) + if raw is None: + raise ValueError(f"Unreviewed private audio RSP input: {name}") sources[Path(name).name] = raw.decode() header = sources["rsp.hpp"] header = header.replace( diff --git a/scripts/tests/test_generator_pins.py b/scripts/tests/test_generator_pins.py index 5e0d0a63..d8d677d6 100644 --- a/scripts/tests/test_generator_pins.py +++ b/scripts/tests/test_generator_pins.py @@ -37,6 +37,16 @@ def matches(data, pin): class GeneratorPins(unittest.TestCase): + def test_newline_variants_reconstruct_only_the_exact_pinned_bytes(self): + lf = b"int reviewed = 1;\nint other = 2;\n" + crlf = lf.replace(b"\n", b"\r\n") + for pinned in (lf, crlf): + digest = hashlib.sha256(pinned).hexdigest() + for checkout in (lf, crlf): + self.assertEqual(probe.reviewed_bytes(checkout, digest), pinned) + self.assertIsNone(probe.reviewed_bytes(checkout + b"// changed\n", digest)) + self.assertIsNone(probe.reviewed_bytes(checkout.replace(b"= 1", b"= 3"), digest)) + def assert_pinned(self, path, *pins): data = (ROOT / path).read_bytes() self.assertTrue( From 14c3652a0b93346f371630920e1f8452248c1675 Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Tue, 17 Nov 2026 04:34:56 +0000 Subject: [PATCH 03/31] Record unchanged prepared inputs after the Windows newline repair --- architecture/online-identity-inputs.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/architecture/online-identity-inputs.json b/architecture/online-identity-inputs.json index fcec2e5a..994ade88 100644 --- a/architecture/online-identity-inputs.json +++ b/architecture/online-identity-inputs.json @@ -184,7 +184,7 @@ "scripts/compose_payloads.py": "c662355843564ccd40759cb245de158888abae80baf59c7f309834897626ba68", "scripts/gen_guest_symbols.py": "f9c74c5c8214fae6372595db4c5f2721e656dabed9c783aa0bb3c6d7dc3e8202", "scripts/generate_recomp_config.py": "444874a216c9011e6f196aa0a1269594517afcdea5fb3763196e092d99bfc473", - "scripts/generate_replay_probe.py": "119d112f92e587f55b3ad5e614a500596ff3735db4a03baa899234978b81e8d9", + "scripts/generate_replay_probe.py": "b1a61521343eeec9547e0b67df68864d7a9ba2c0c3ad9a9cfd1b8c803ccfced7", "scripts/generate_revision_policy.py": "bafbefad41542e00b6c5ec13b02acde69dda7f48e34025f46d92d028da6427b9", "scripts/guest_hooks.py": "4058af2139c1211c2db79c8748734c2c1f231ec6168e964166d90c83bb48c6cc", "scripts/host_task_policy.py": "aa28c9bcd8110d0ef16b2f6dfde7ec51b8767578f46d3bc5371f197efb016f78", @@ -207,6 +207,6 @@ }, "last_update": { "identity_changed": false, - "reason": "Retain v1.0.15 simulation and wire identities. Optional authenticated session-links v2 extensions add duplicate immutable racer delivery and consented waiting-lobby handover among capable peers; default menu ownership remains port zero and older peers retain host delivery. Correction eligibility and Auto delay accounting affect presentation and scheduling only. Upstream architecture-free launch hashes, state cross-checks, GuestCallContext and reliable checkpoint semantics are retained." + "reason": "Retain v1.0.15 simulation and wire identities. Optional authenticated session-links v2 extensions add duplicate immutable racer delivery and consented waiting-lobby handover among capable peers; default menu ownership remains port zero and older peers retain host delivery. Correction eligibility and Auto delay accounting affect presentation and scheduling only. Upstream architecture-free launch hashes, state cross-checks, GuestCallContext and reliable checkpoint semantics are retained. Audio input newline canonicalization reconstructs the same existing pins; all ten prepared Windows input digests still match the upstream lock." } } From 8e6060fcf08c3c40d26c4bcb9ade18fc719dbf42 Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Tue, 17 Nov 2026 04:39:53 +0000 Subject: [PATCH 04/31] Check private native fixtures using the same pinned newline rules --- runtime-recomp/tests/replay_probe/test_generator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime-recomp/tests/replay_probe/test_generator.py b/runtime-recomp/tests/replay_probe/test_generator.py index b12604dc..d1f0434c 100644 --- a/runtime-recomp/tests/replay_probe/test_generator.py +++ b/runtime-recomp/tests/replay_probe/test_generator.py @@ -622,7 +622,7 @@ def test_audited_native_source_contracts_do_not_drift(self): "extern/n64-modern-runtime/ultramodern/src/timer.cpp":"07bec0f6617c0d9965a263ae6f41d8785cd380f5d584df8a844bc83b2cc89211", } for path,expected in pins.items(): - self.assertEqual(hashlib.sha256(generator.audited_input_path(path, DEPENDENCIES_DIR).read_bytes()).hexdigest(),expected, + self.assertIsNotNone(generator.reviewed_bytes(generator.audited_input_path(path, DEPENDENCIES_DIR).read_bytes(),expected), f"Re-audit the private native contract after source changes: {path}") From 91ea43fb6b5436dbbcde798104d2fc1ed34d2cea Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Tue, 17 Nov 2026 04:48:32 +0000 Subject: [PATCH 05/31] Include handover checks and record validation in the runtime owners --- runtime-recomp/src/game/game_main.cpp | 2 +- runtime-recomp/src/game/runtime_ui.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime-recomp/src/game/game_main.cpp b/runtime-recomp/src/game/game_main.cpp index 9efb82c6..a408f53a 100644 --- a/runtime-recomp/src/game/game_main.cpp +++ b/runtime-recomp/src/game/game_main.cpp @@ -43,6 +43,7 @@ #include "netplay/session_chat/chat.hpp" #include "netplay/peer_relay/transport.hpp" #include "netplay/session_chat/settings.hpp" +#include "netplay/session_links/qualification.hpp" #include #endif #if defined(__ANDROID__) @@ -54,7 +55,6 @@ #include #endif #if DKR_LEGACY_QUALIFICATION -#include "netplay/session_links/qualification.hpp" #include "legacy_runtime_qualification.hpp" #endif #if DKR_RUNTIME_HAS_RT64 diff --git a/runtime-recomp/src/game/runtime_ui.cpp b/runtime-recomp/src/game/runtime_ui.cpp index d3d15af7..ce9f2bb5 100644 --- a/runtime-recomp/src/game/runtime_ui.cpp +++ b/runtime-recomp/src/game/runtime_ui.cpp @@ -52,6 +52,7 @@ #include "invite_handoff.hpp" #include #include "party_link.hpp" +#include "custom_records.hpp" #include "online_presentation/test_receive_delay.hpp" #include "online_stability/qualification_delivery.hpp" #include "runtime_ui.hpp" From 0454873b605f7442a8f51a823cf1d4806f187bd3 Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Tue, 17 Nov 2026 04:55:34 +0000 Subject: [PATCH 06/31] Generate revision symbols for the standalone mod regression tests --- runtime-recomp/tests/legacy_mods/CMakeLists.txt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/runtime-recomp/tests/legacy_mods/CMakeLists.txt b/runtime-recomp/tests/legacy_mods/CMakeLists.txt index 2f2222f1..d2bc0d95 100644 --- a/runtime-recomp/tests/legacy_mods/CMakeLists.txt +++ b/runtime-recomp/tests/legacy_mods/CMakeLists.txt @@ -4,6 +4,11 @@ set(BUILD_TESTING ON) set(CMAKE_C_STANDARD 17) set(CMAKE_CXX_STANDARD 20) get_filename_component(DKRPORT_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../.." ABSOLUTE) +if(NOT DEFINED DKR_DEPENDENCIES_DIR) + set(DKR_DEPENDENCIES_DIR "${DKRPORT_ROOT}/extern") +endif() +include("${DKRPORT_ROOT}/runtime-recomp/cmake/GuestSymbols.cmake") +dkr_guest_symbols_everywhere() include("${DKRPORT_ROOT}/runtime-recomp/cmake/LegacyMods.cmake") # These four link code that only the full runtime provides (achievements, saves, road wheels, # the launcher UI). The rest of this project builds without it. From 5a20f6027a35c5969228d9e6d415553be7b57944 Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Tue, 17 Nov 2026 05:02:22 +0000 Subject: [PATCH 07/31] Wait for asynchronous offline copies in the mod sync fixture --- .../tests/online_mod_sync_tests.cpp | 37 ++++++++++++++++--- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/runtime-recomp/tests/online_mod_sync_tests.cpp b/runtime-recomp/tests/online_mod_sync_tests.cpp index 4b17d76e..3f44cfbb 100644 --- a/runtime-recomp/tests/online_mod_sync_tests.cpp +++ b/runtime-recomp/tests/online_mod_sync_tests.cpp @@ -6,13 +6,14 @@ #include #include #include +#include using namespace dkr::mods; using namespace dkr::mods::online; namespace { unsigned checks = 0; -void check(bool value) { +void check(bool value, const std::source_location& site = std::source_location::current()) { if (!value) - throw Error("Online sync assertion " + std::to_string(checks)); + throw Error("Online sync assertion " + std::to_string(checks) + " at line " + std::to_string(site.line())); ++checks; } struct Hub { @@ -134,6 +135,31 @@ SyncView wait(ModSync& sync, SyncPhase wanted, std::chrono::seconds timeout = st } throw Error("Timed out waiting for the online mod sync phase."); } +SyncView wait_kept(ModSync& sync) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (std::chrono::steady_clock::now() < deadline) { + auto view = sync.snapshot(); + if (view.phase == SyncPhase::Failed) + throw Error(view.error); + // Admission finishes before the deliberately asynchronous offline copy. + if (view.phase == SyncPhase::Verified && (view.kept_offline || !view.keep_error.empty())) + return view; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + throw Error("The admitted client's offline copy did not finish."); +} +void promote(ModSync& sync, const SyncSettings& settings) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (std::chrono::steady_clock::now() < deadline) { + std::string error; + if (sync.promote_cached_host(settings, error)) + return; + if (!error.empty()) + throw Error(error); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + throw Error("The verified mod worker did not retire before promotion."); +} } // namespace int main(int argc, char** argv) { if (argc != 3 && argc != 4) { @@ -244,7 +270,7 @@ int main(int argc, char** argv) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } check(observed_progress); - const auto first = wait(a, SyncPhase::Verified), third = wait(c, SyncPhase::Verified); + const auto first = wait_kept(a), third = wait_kept(c); check(first.profile && first.runtime && third.profile && third.runtime); check(first.profile->digest == ready.profile->digest && third.profile->digest == ready.profile->digest); check(first.kept_offline && first.keep_error.empty()); @@ -297,8 +323,7 @@ int main(int argc, char** argv) { } // Promote the exact verified client cache, then use it to serve a // fresh download after the lobby's authority changes. - std::string promotion_error; - check(a.promote_cached_host(settings(1), promotion_error)); + promote(a, settings(1)); const auto promoted = wait(a, SyncPhase::HostReady); check(a.cached_host_active() && promoted.runtime == first.runtime && promoted.profile->digest == ready.profile->digest); @@ -331,7 +356,7 @@ int main(int argc, char** argv) { std::ofstream out(corrupt, std::ios::binary | std::ios::trunc); out << "changed"; } - check(c.promote_cached_host(settings(3), promotion_error)); + promote(c, settings(3)); const auto rejected = wait(c, SyncPhase::Verified); check(!rejected.error.empty() && !c.cached_host_active()); } From 6ffe644e915ccecc3ad16590931f7c0020c74f6c Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Tue, 17 Nov 2026 05:32:26 +0000 Subject: [PATCH 08/31] Report bounded spectator checkpoint progress across scene transitions --- architecture/online-identity-inputs.json | 4 ++-- runtime-recomp/src/game/party_runtime.cpp | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/architecture/online-identity-inputs.json b/architecture/online-identity-inputs.json index 994ade88..2ded3020 100644 --- a/architecture/online-identity-inputs.json +++ b/architecture/online-identity-inputs.json @@ -106,7 +106,7 @@ "runtime-recomp/src/game/netplay/runtime_state.hpp": "9d54de461b5220b246763d5f0b044cfc7ed845da4c8ad1ba521eb6f3cb905b07", "runtime-recomp/src/game/netplay/setup_policy.hpp": "c2630dbc6a3950e947d0ce380d1be42c71568a864bb7dbef42703df5f1cf31fc", "runtime-recomp/src/game/party_release.hpp": "0f364dfe23f991223547679858ca894056974d891040527a2c6e0ea6065e3676", - "runtime-recomp/src/game/party_runtime.cpp": "20e2818b9ebf10e3f828f702caaf54849688208dcdbcc933dfe565bad85bc15d", + "runtime-recomp/src/game/party_runtime.cpp": "bc72a11cf8e128929e60184a90f3e028600b28ec005f8501ccdadaf582b0ebeb", "runtime-recomp/src/game/party_runtime.hpp": "f71d5b873f71fd24000c43833171967fa40860468f2ee6f50367ac1c1c60b404", "runtime-recomp/src/game/runtime_save_routing.cpp": "837917b9ede8d0f9cadd86edaa325da50c7e88a6c34242758f18228112737890", "runtime-recomp/src/game/runtime_save_routing.hpp": "cb3ae802050f29e38def0d42c60c01345be2cc46a515a95e9c50d49a06cf6879", @@ -207,6 +207,6 @@ }, "last_update": { "identity_changed": false, - "reason": "Retain v1.0.15 simulation and wire identities. Optional authenticated session-links v2 extensions add duplicate immutable racer delivery and consented waiting-lobby handover among capable peers; default menu ownership remains port zero and older peers retain host delivery. Correction eligibility and Auto delay accounting affect presentation and scheduling only. Upstream architecture-free launch hashes, state cross-checks, GuestCallContext and reliable checkpoint semantics are retained. Audio input newline canonicalization reconstructs the same existing pins; all ten prepared Windows input digests still match the upstream lock." + "reason": "Add bounded checkpoint delivery diagnostics only; no message format, simulation, admission or queue policy changes." } } diff --git a/runtime-recomp/src/game/party_runtime.cpp b/runtime-recomp/src/game/party_runtime.cpp index bb835f2a..16f29aef 100644 --- a/runtime-recomp/src/game/party_runtime.cpp +++ b/runtime-recomp/src/game/party_runtime.cpp @@ -687,6 +687,9 @@ struct PartyRuntime::Impl { if (!d.sender.begin(++transfer_serial, std::make_shared(wire))) throw std::runtime_error("Could not stage spectator checkpoint delivery."); party_retire_checkpoint(key, id, match, d.sender.offer().transfer); + std::fprintf(stderr, "[party][checkpoint-send] peer=%llu transfer=%llu epoch=%llu frame=%u bytes=%zu\n", + static_cast(id), static_cast(transfer_serial), + static_cast(wire.next.epoch), wire.next.frame, wire.state->size()); } bool current_checkpoint() const { if (!encoded || !feed.covers(encoded->next)) @@ -964,6 +967,9 @@ struct PartyRuntime::Impl { last_offer = offer; receiving = offer; active_transfer = offer.transfer; + std::fprintf(stderr, "[party][checkpoint-receive] transfer=%llu epoch=%llu frame=%u bytes=%u\n", + static_cast(offer.transfer), + static_cast(offer.next.epoch), offer.next.frame, offer.bytes); admitted_at.reset(); buffered.clear(); if (phase == Phase::Admission) @@ -987,6 +993,8 @@ struct PartyRuntime::Impl { if (result == CheckpointReceiver::Result::Rejected) throw std::runtime_error(e); if (result == CheckpointReceiver::Result::Complete) { + std::fprintf(stderr, "[party][checkpoint-receive] complete transfer=%llu bytes=%zu\n", + static_cast(chunk.transfer), receiver.received_bytes()); auto wire_state = receiver.take_verified(e); if (!wire_state) throw std::runtime_error(e); @@ -1737,6 +1745,8 @@ struct PartyRuntime::Impl { // An observer cannot stop required racing peers with malformed // playback/seat requests. Required members still fail closed. if (server() && !required().contains(packet.source)) { + std::fprintf(stderr, "[party][observer-packet] rejected peer=%llu reason=%s\n", + static_cast(packet.source), e.what()); needing.erase(packet.source); deliveries.erase(packet.source); continue; @@ -1767,6 +1777,15 @@ struct PartyRuntime::Impl { if (!callback_error.empty()) throw std::runtime_error(callback_error); transfer(now); + if (phase != Phase::Admission && now >= admission_log && + ((!simulating() && playback.needs_baseline()) || (server() && !deliveries.empty()))) { + admission_log = now + std::chrono::seconds(5); + std::fprintf( + stderr, + "[party][checkpoint-progress] authority=%u receiving=%zu active=%u decoding=%u encoded=%u needing=%zu deliveries=%zu\n", + unsigned(server()), receiver.received_bytes(), unsigned(bool(receiving)), unsigned(decoding.valid()), + unsigned(bool(encoded)), needing.size(), deliveries.size()); + } std::erase_if(deliveries, [&](const auto& entry) { return !roster.find(entry.first); }); std::erase_if(requested_at, [&](const auto& entry) { return !roster.find(entry.first); }); if (server() && phase == Phase::Admission && all(prepared)) From 2a05ba30939a21134a87893eaf950b6a9be38deb Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Tue, 17 Nov 2026 05:39:16 +0000 Subject: [PATCH 09/31] Record integration acceptance and compare wrapped CMake warnings portably --- docs/notes/2026-11-17-upstream-integration.md | 44 +++++++++++++++++-- scripts/tests/test_prepared_inputs_cmake.py | 4 +- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/docs/notes/2026-11-17-upstream-integration.md b/docs/notes/2026-11-17-upstream-integration.md index 995db5f2..e3e1271f 100644 --- a/docs/notes/2026-11-17-upstream-integration.md +++ b/docs/notes/2026-11-17-upstream-integration.md @@ -59,9 +59,47 @@ same regression-harness timeout. Git status on the NTFS source checkout took 23.14 seconds; the test's outer timeout is 20 seconds. Linux verification moves to a normal Linux checkout instead of increasing or disabling that deadline. -Windows and Linux game builds, prepared-input verification, actual-game tests -and final package scans are still being completed. This note will be updated -with their results before the testing packages are handed over. +Both Release builds completed. Windows passed all 243 Release tests, and Linux +passed all 243 in a normal Linux checkout. The prepared-input lock check passed +all ten inputs on both systems against the unchanged upstream lock. The private +generator suite also passed all 53 tests. The cached-mod handover fixture passed +37 checks using the real mod worker, including a fresh download from the promoted +host and rejection of a damaged cache. + +The actual Windows game was tested with twelve separate processes: four racers +and eight spectators. All twelve completed host handover and reached the race. +The ordinary run recorded no racing input waits. The impaired run injected +375 ms of outgoing delivery delay, 25 ms jitter, 200 ms spikes and loss of every +97th disposable packet. The last spectator also had 1,000 ms delay and spikes. +All twelve completed this run too. Each racer recorded 2.38 to 2.66 seconds of +input waiting in the first two race pacing samples, then zero across the next +23 samples. This is injected application delivery delay on one Windows PC, +not twelve physical machines or a measured intercontinental connection. + +An earlier 90-second run ended while the spectators were still receiving the +new scene checkpoint. Diagnostics confirmed that delivery was progressing. +The complete 180-second run passed without changing the admission protocol or +increasing its background bandwidth allowance. That allowance protects racing +traffic, but eight spectators can still take a long time to receive a new scene. +This remains a known limit; passing this test does not mean instant spectator +scene loading or a guaranteed frame rate under every network condition. + +## Local checkout and recovery + +The combined branch in `C:/DKRPort` is `codex/upstream-integrated-v1016`. +The original branch is retained as `codex/network-host-handover`, with an extra +preservation ref and a named stash for its uncommitted files. The recovery +bundle and exact file archive remain outside the repository under +`D:/DiddykongWorkFolder/DKR-R-Upstream-Integration-20261117/recovery/`. +All 3,071 recorded file hashes and the original status were checked again +before switching branches; none had changed. + +Old dependency and build caches are preserved under +`C:/DKRPort-pre-integration-20261117/`. The current `extern` directory is a local +junction to the verified pinned checkouts in the integration workspace on D:. +The verified Release build trees are also on D:, rather than reusing the old +build caches. Neither path is a source or release-package dependency for other +users: fresh checkouts use the maintained bootstrap and prepare scripts. Nothing has been pushed, published, signed for the updater or deployed. Public directory ownership transfer remains capability-gated until its matching diff --git a/scripts/tests/test_prepared_inputs_cmake.py b/scripts/tests/test_prepared_inputs_cmake.py index 45121fef..193301cb 100644 --- a/scripts/tests/test_prepared_inputs_cmake.py +++ b/scripts/tests/test_prepared_inputs_cmake.py @@ -46,7 +46,9 @@ def configure(self, *definitions): name, separator, value = line.partition("=") if separator and not line.startswith(("#", "//")): cache[name.split(":")[0]] = value - return cache, done.stderr + # CMake wraps diagnostics according to the lengths of the checkout and + # temporary paths. Check the warning text independently of those wraps. + return cache, " ".join(done.stderr.split()) def test_defaults_come_from_the_prepared_directory(self): cache, _ = self.configure() From f1b958c70d7897e4d6b97c258782c28c92b424fc Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Tue, 17 Nov 2026 11:05:35 +0000 Subject: [PATCH 10/31] Record final host and packaged build verification --- docs/notes/2026-11-17-upstream-integration.md | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/docs/notes/2026-11-17-upstream-integration.md b/docs/notes/2026-11-17-upstream-integration.md index e3e1271f..0cc31841 100644 --- a/docs/notes/2026-11-17-upstream-integration.md +++ b/docs/notes/2026-11-17-upstream-integration.md @@ -38,7 +38,9 @@ capable members before a new owned world is constructed. ## Verification and build notes -The initial combined Windows host run passed all 214 tests. A separate native +The combined Windows host run passed all 214 tests. The final Linux host preset +also configured, built and passed all 214 tests after resuming the paused build. +The installed pre-commit checks passed for the integration changes. A separate native four-racer/eight-spectator test passed sequential handovers to a racer and a spectator, including mixed-architecture metadata, preserved seats/save owner, and a synchronized start. Its impaired run added 375 ms one-way delay, 25 ms @@ -52,7 +54,8 @@ Windows portability fixes retain the checks: use extended paths for deep cache fixtures, keep relative executable tests on the interpreter's drive, normalize schema paths, compare review text with universal newlines, encode the iOS bundle entry point's executable mode explicitly, and use native paths for the local -esbuild and CMake command construction. +esbuild and CMake command construction. CMake warning checks ignore line wraps +caused by different checkout and temporary-directory lengths. The clean Linux baseline and the first combined Linux run both exposed the same regression-harness timeout. Git status on the NTFS source checkout took @@ -84,6 +87,22 @@ traffic, but eight spectators can still take a long time to receive a new scene. This remains a known limit; passing this test does not mean instant spectator scene loading or a guaranteed frame rate under every network condition. +## Testing packages + +The Windows ZIP and x86_64 AppImage are built as `1.0.16-playtest.1`. Their +archive readback checks match every staged file, with no missing or changed +payloads. The package scans passed the version, feature, frozen identity and +private-data checks. Receipts, checksums and test logs stay outside the source +tree in the integration workspace. + +The packaged Windows runtime passed its install-layout check. The actual +AppImage extracted and ran its settings round-trip check successfully. The +Linux library audit inspected 100 ELF files and found no missing dependencies +outside the documented host-library policy. The AppDir closure check also +passed, including the file picker that deliberately uses host GTK libraries. +This AppImage requires glibc 2.38 or newer; its C++ runtime needs GLIBCXX 3.4.32. +These checks do not replace testing the package on a physical Steam Deck. + ## Local checkout and recovery The combined branch in `C:/DKRPort` is `codex/upstream-integrated-v1016`. From df9cd096042a48bd7c2c531bc621fa733020467a Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Sun, 22 Nov 2026 00:10:07 +0000 Subject: [PATCH 11/31] Stage public lobbies and a ranked replay review workflow --- docs/MOD_LIBRARY_WEBSITE.md | 30 +- docs/notes/2026-11-22-ranked-replay-review.md | 89 +++++ runtime-recomp/src/game/directory_ui.inl | 27 ++ .../game/mod_library/website/assets/app.js | 13 +- .../mod_library/website/assets/racing-ui.js | 354 ++++++++++++++++++ .../mod_library/website/assets/racing.css | 17 + .../website/assets/replay-format.js | 37 ++ .../src/game/mod_library/website/index.html | 4 +- .../src/game/mod_library/website/privacy.html | 4 +- .../tests/mod_library_community_tests.cjs | 10 +- services/library-workflow/build.py | 22 +- .../online-directory/api/speedrun_api.mjs | 177 +++++++++ .../online-directory/api/speedrun_replay.mjs | 23 ++ .../online-directory/api/speedrun_schema.sql | 46 +++ services/online-directory/api/worker.mjs | 28 ++ services/online-directory/build.py | 2 + services/online-directory/directory.mjs | 12 + .../online-directory/tests/build_tests.py | 10 +- services/online-directory/tests/runtime.cjs | 16 + .../online-directory/tests/speedrun_api.cjs | 122 ++++++ 20 files changed, 1028 insertions(+), 15 deletions(-) create mode 100644 docs/notes/2026-11-22-ranked-replay-review.md create mode 100644 runtime-recomp/src/game/mod_library/website/assets/racing-ui.js create mode 100644 runtime-recomp/src/game/mod_library/website/assets/racing.css create mode 100644 runtime-recomp/src/game/mod_library/website/assets/replay-format.js create mode 100644 services/online-directory/api/speedrun_api.mjs create mode 100644 services/online-directory/api/speedrun_replay.mjs create mode 100644 services/online-directory/api/speedrun_schema.sql create mode 100644 services/online-directory/tests/speedrun_api.cjs diff --git a/docs/MOD_LIBRARY_WEBSITE.md b/docs/MOD_LIBRARY_WEBSITE.md index 44db0e7b..778c2c19 100644 --- a/docs/MOD_LIBRARY_WEBSITE.md +++ b/docs/MOD_LIBRARY_WEBSITE.md @@ -15,7 +15,8 @@ Use Python 3.11+ and Node.js 24+ on Windows or Linux. On Windows substitute ```sh npm install --prefix build/library-community-tools --no-save --ignore-scripts --package-lock=false esbuild@0.28.2 jsdom@29.1.1 python3 services/library-workflow/build.py community --output build/library-community-release/stage --baseline build/mod-library-community-20261029/baseline --archive build/library-community-release/DKR-R-website-update.zip -node runtime-recomp/tests/mod_library_community_tests.cjs build/library-workflow-d1-runtime/node_modules/miniflare build/library-community-tools/node_modules/jsdom +npm ci --prefix services/test-tools --ignore-scripts +node runtime-recomp/tests/mod_library_community_tests.cjs services/test-tools/node_modules/miniflare build/library-community-tools/node_modules/jsdom python3 scripts/check.py --suite guard,tooling ``` @@ -87,3 +88,30 @@ and a 60 ms stagger capped after eight groups. Featured mods crossfade every Reduced-motion preferences disable entrances and automatic rotation by default. The companion picker keeps checked inputs mounted while filtering so existing draft/preview serialization includes selections outside the visible results. + +## Online and ranked replay review + +The Online page at `#online` reads `GET /v1/online/public`. The private +directory Worker creates the projection from the same live account leases and +room list as the launcher. This endpoint never forwards a browser credential +or a private room. The browser polls every 30 seconds while visible. A missing +count is shown as unavailable, and an available count of zero is shown as zero. + +Copy a public lobby link and choose **Find lobby from website** under **Public +lobbies** in the updated launcher. The link selects a room from the current +signed-in launcher list. The existing host, compatibility, mod and slot checks +still govern requests to join or spectate. + +Leaderboards at `#leaderboards` use the existing library account. The flow is +**Sign in → attach replay → check the detected event and recorded time → Post +run**. My runs tracks the upload, independent verification and review. Only +published verified PBs count on each board. The website is staged with no +qualified boards or upload access by default. + +Custom tracks are discovered automatically from the live catalogue, including +newly published releases. A board identifies an exact release and the server +checks the catalogue's verified SHA-256. Publish a new board after qualifying a +new release. Previous eligible versions stay available under their own boards. + +See [Ranked replay review](notes/2026-11-22-ranked-replay-review.md) for the +replay format, open qualification work and checks before opening submissions. diff --git a/docs/notes/2026-11-22-ranked-replay-review.md b/docs/notes/2026-11-22-ranked-replay-review.md new file mode 100644 index 00000000..c1524512 --- /dev/null +++ b/docs/notes/2026-11-22-ranked-replay-review.md @@ -0,0 +1,89 @@ +# Ranked replay review + +## What to review + +- **Online** shows the launcher's active-account count and public rooms. Test a + private and a public room and check whether copying a link identifies the + intended room in the launcher. Selecting the room asks for the normal host + approval. +- **Leaderboards** has Vanilla Tracks, Custom Tracks and Full Game. Tracks + appear from the library as soon as the listing has a published release. + Ranked results require a qualified board for that exact version. +- **Post a run** uses the existing library account and attachment flow. The file + fills in the board and recorded time. Submissions and their private replays go + into the same queue whether uploaded in the browser or by an authenticated + client. A queued time has no public rank. +- **My runs** shows submission state and staff feedback. **Review runs** gives + authorised staff the replay and verified time. A reviewer can publish or + reject an independently verified run. The route does not accept a claimed + verifier result from the reviewer or player. + +## Time Trial rules for qualification + +Start with solo offline US Time Trial. Board identity includes the game +engine, rules revision, track, exact release hash where applicable, category +and legal vehicle. Use separate boards for completed races and best laps when +the engine can derive both from a completed run. Start, split, finish and lap +durations come from the guest race clock. + +Use an isolated game profile with the normal retail racer and vehicle for the +board. Other Custom Magic Codes, retail Magic Codes, cheats, dev tools, +save or state injection, macros, scripted inputs and timing adjustments are +disallowed. Reject a run that changes a gameplay setting or pauses the clock +during the attempt. The verifier checks the resulting simulation and allowed +settings. Replaying an input stream cannot establish whether it came from a +person, so human moderation remains part of the workflow. + +The ranked Magic Code must only expose approved timer and run actions. The +runtime owns the locked profile, inputs and eligibility. Graphics choices are +separate from gameplay settings. Qualify each revision, OS and architecture +combination for tick and state parity before combining scores. Pixel comparison +requires a separately fixed renderer, assets, camera, viewport and output +format. + +## Replay and trust boundary + +The preview format starts with ASCII `DKRREPL1` and a little-endian 32-bit +manifest byte length. It then holds a UTF-8 JSON manifest and four bytes per +applied controller tick, with the 16-bit button bitset in little-endian order +and signed X and Y axes. The manifest names the board, engine digest, ruleset, +release digest, ROM revision, platform, architecture, tick count, recorded +race clock, initial RNG seed, ordered splits and state digests at 600-tick +intervals and on the last tick. The browser and API share format validation. +The manifest is untrusted. The one MiB limit applies to the Time Trial preview +format. Full-game runs need a separately qualified larger format. + +Only the independent verifier may set `verified_ticks`, `verifier_digest` +and `verified` after reproducing the run from a trusted clean start and +checking every required event, RNG transition and state digest. The public +Worker has no verifier-writes endpoint. D1 stores the queue and decisions. +R2 objects are private and served by the authorised download route. Neither +the replay format nor the published object includes a ROM or a guest snapshot. + +## Before opening ranked submissions + +The runtime recorder, ranked Magic Code, split overlay, playback controls and +independent verifier are still required. The existing owned-engine probe is +for private snapshots and rollback testing. First prove a completed legal +vanilla Time Trial from inputs alone on Windows and Linux, then qualify one +native custom track release. Compare applied input, engine checkpoints, splits +and completion. Verify renderer parity separately. Add Adventure categories +such as Any%, 100% and All Trophy Races after equivalent coverage. + +Keep `SPEEDRUN_UPLOADS_ENABLED` unset until that qualification is complete. +Configure a private `SPEEDRUN_REPLAYS` R2 binding during the ranked pilot. +Run the additive speedrun D1 migration and check the acceptance, privacy and +review cases in staging. The Online page and read-only track catalogue can +be reviewed independently of ranked uploads. + +## Staging review + +The review package contains website and Worker sources plus screenshots from +a local test. The screenshot times and lobbies are fixtures. The package's +rollback sources are the base checkout used to build the review. Collect the +actual deployed website files, Worker revisions and a D1 backup before rollout. +Keep the current Cloudflare settings and bindings. The directory Worker must +understand the public projection before the public API and website use it. + +Use the existing documented deployment commands only after review. No +production changes are required to run the local tests. diff --git a/runtime-recomp/src/game/directory_ui.inl b/runtime-recomp/src/game/directory_ui.inl index 769771b8..13eb0e78 100644 --- a/runtime-recomp/src/game/directory_ui.inl +++ b/runtime-recomp/src/game/directory_ui.inl @@ -1,5 +1,6 @@ // Uses the retained launcher's native controls, cards, fonts and focus handling. bool g_directory_friends_view = false; +std::string g_directory_website_lobby; const char* DirectoryPhase(const std::string& phase) { if (phase == "starting") return "Starting"; @@ -103,12 +104,38 @@ void DrawOlPublicLobbies(float width, const OnlineFrame& frame) { OlParagraph(snapshot->status, 15.F, kOlSoft, inner); return; } + if (OlButton("Find lobby from website")) { + constexpr std::string_view prefix = "https://positron-portal.com/dkr-r/#lobby="; + const char* clipboard = ImGui::GetClipboardText(); + const std::string_view link = clipboard != nullptr ? clipboard : ""; + const auto id = link.starts_with(prefix) ? link.substr(prefix.size()) : std::string_view{}; + const bool valid = id.size() == 32 && std::all_of(id.begin(), id.end(), [](char ch) { + return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f'); + }); + if (valid) + g_directory_website_lobby = id; + else + OlNotify("Copy a public lobby link from the DKR-R website first."); + } + if (!g_directory_website_lobby.empty()) { + if (OlButton("Show all public lobbies")) + g_directory_website_lobby.clear(); + const bool found = std::any_of(snapshot->rooms.begin(), snapshot->rooms.end(), + [](const auto& room) { return room.id == g_directory_website_lobby; }); + if (!g_directory_website_lobby.empty() && !found) { + PaddockGap(8.F); + OlParagraph("This lobby is no longer public or available.", 15.F, kOlSoft, inner); + return; + } + } if (snapshot->rooms.empty()) { OlParagraph("No public lobbies are available. Create a lobby and choose Public to host one.", 15.F, kOlSoft, inner); return; } for (const auto& lobby : snapshot->rooms) { + if (!g_directory_website_lobby.empty() && lobby.id != g_directory_website_lobby) + continue; const bool compatible = lobby.compatibility == dkr::online::compatibility(); const bool can_join = frame.launcher && frame.rom_ready && !frame.active && !snapshot->joining && compatible; diff --git a/runtime-recomp/src/game/mod_library/website/assets/app.js b/runtime-recomp/src/game/mod_library/website/assets/app.js index 704b4657..6a3ee404 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/app.js +++ b/runtime-recomp/src/game/mod_library/website/assets/app.js @@ -295,7 +295,7 @@ function listingOptions(value) { return options([['','Choose an existing listing']].concat(managedItems().filter(m=>!m.archived).map(m=>[m.id,m.title+' · '+category(m.category).short])),value); } function pagehead(title,subtitle,backAction,id) { const back=backAction||'store'; - const label={moderation:'Back to moderation',account:'Back to my account',admin:'Back to admin','review-request':'Back to request'}[back]||'Back to library'; + const label={moderation:'Back to moderation',account:'Back to my account',speedruns:'Back to leaderboards',admin:'Back to admin','review-request':'Back to request'}[back]||'Back to library'; const refresh=['account','request-status','moderation','review-request','admin','detail','editor','metadata-editor','publication-preview'].includes(s.view)?button('refresh-page',icon('refresh-cw')+'Refresh','quiet small'):''; return '
'+button(back,icon('arrow-left')+label,'quiet small',id,'data-page-focus')+refresh+'

'+esc(title)+'

'+(subtitle?'

'+subtitle+'

':'')+'
'; } @@ -354,7 +354,7 @@ function header() { const u=user(); - return ''; + return ''; } function footer() { return 'DKR-R Mod Library · Community creations, one starting grid.
DKR-R project'+textButton('help','Install help')+textButton('staff-login','Moderator login')+'Privacy
'; } function modcard(item) { @@ -472,6 +472,8 @@ return banner('Reports stay visible until a moderator acts. Negative feedback alone is not a reason to hide a review.')+'
'+(list(D.reports).length?D.reports.map(report=>{const review=report.review||list(D.reviews).find(v=>v.id===report.reviewId);if(!review)return '

Reported review unavailable

Refresh the moderation queue to load this report’s content.

';const m=D.item(review.itemId);return '

'+esc(m?m.title:report.itemTitle||'Mod review')+'

'+(report.status==='open'?'Open report':'Resolved')+'
'+stars(review.score)+'by '+esc(authorName(review))+' · '+esc(review.version||'Version not specified')+'

'+esc(review.text||'Rating only')+'

Report reason: '+esc(report.reason)+'

'+(report.status==='open'?'
'+area('Moderation reason','reason','','maxlength="1000" placeholder="Required if hiding the review."')+'
'+submit('Dismiss report','keep','quiet')+submit('Hide review','hide','red')+'
':'

Decision: '+esc(report.action||'Resolved')+' · '+esc(report.resolution||'')+'

'+(review.hidden?button('restore-review','Restore review','quiet small',report.id,'data-revision="'+esc(report.revision)+'" data-review-revision="'+esc(review.revision)+'"'):'Review is visible.'))+(m?button('reviews','View mod reviews','quiet small',review.itemId):'')+'
';}).join(''):empty('No reported reviews','Reported content will appear here for staff to assess.'))+'
'; } + const Racing = window.DKRRacingUI.create({root, config, Auth, view:()=>s.view, user, isStaff, esc, icon, button, pagehead, requireSignedIn, go, renderIcons}); + const Community = window.DKRCommunityUI.create({root,state:()=>s,store:()=>D,esc,icon,button,banner,empty,categories:C.categories,category,image,dateText,user,isStaff,render,go,flash,perform}); function prepareEditor(mode,id,saved) { @@ -751,12 +753,12 @@ main.innerHTML=D&&D.loading?progress('Loading your account'):pagehead('Your account could not be loaded','')+banner(esc(D&&D.error||'The connection was interrupted. Refresh this page to reconnect to your account.')+'
'+button('refresh-page','Reconnect','quiet')+'
','error'); } else { if(needsUser&&!user()){s.returnTo={view:s.view,requestId:s.requestId};s.loginMode=['moderation','review-request','editor','metadata-editor','publication-preview','admin','batch'].includes(s.view)?'staff':'player';s.view='login';} - const pages={batch:batchPage,store:storePage,detail:detailPage,login:loginPage,denied:()=>deniedPage(false),request:requestPage,account:accountPage,'request-status':requestStatusPage,moderation:moderationPage,'review-request':reviewRequestPage,editor:editorPage,'metadata-editor':metadataPage,'publication-preview':publicationPreviewPage,admin:adminPage,help:helpPage}; + const pages={online:Racing.onlinePage,speedruns:Racing.speedrunsPage,'post-run':Racing.postPage,batch:batchPage,store:storePage,detail:detailPage,login:loginPage,denied:()=>deniedPage(false),request:requestPage,account:accountPage,'request-status':requestStatusPage,moderation:moderationPage,'review-request':reviewRequestPage,editor:editorPage,'metadata-editor':metadataPage,'publication-preview':publicationPreviewPage,admin:adminPage,help:helpPage}; main.innerHTML=(pages[s.view]||storePage)(); } } if(Auth&&Auth.signoutPending&&!Auth.completionWindow){main.insertAdjacentHTML('afterbegin',banner(esc(Auth.signoutWarning||'Sign-out could not be confirmed. Reconnect and finish signing out to remove remembered access from this device.')+'
'+button('retry-signout','Finish signing out','quiet')+'
','error'));} - renderIcons();applyBusy();if(focus)focusPage();Community.mounted(); + renderIcons();applyBusy();if(focus)focusPage();Community.mounted();Racing.mounted(); } async function go(view,data,refresh) { if(view!==s.view){captureListingForm();if(Uploads&&Uploads.state.running&&uploadMatchesContext(uploadTarget,false))Uploads.pause();s.uploadOpenKind='';s.uploadJobsShown=false;s.uploadError='';s.uploadConnection='';} @@ -808,6 +810,7 @@ if(pendingWrite)return; try { if(await workflowAction(action,id,target))return; + if(await Racing.action(action,id,target))return; if(action==='store'){await go('store');return;} if(action==='category'){s.category=id;s.tag='all';s.limit=6;s.view='store';clearFlash();render();restoreFocus(action,id);return;} if(action==='tag'){s.tag=id;s.limit=6;clearFlash();render();restoreFocus(action,id);return;} @@ -1015,5 +1018,7 @@ } catch(error){bootError=errorMessage(error);} finally {started=true;bootLoading=false;render();} } + const publicPage = {'#online':'online','#leaderboards':'speedruns'}[location.hash]; + if(publicPage||/^#lobby=[a-f0-9]{32}$/.test(location.hash))s.view=publicPage||'online'; initialise(); }()); diff --git a/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js b/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js new file mode 100644 index 00000000..3930e395 --- /dev/null +++ b/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js @@ -0,0 +1,354 @@ +(function () { + 'use strict'; + const replayModule = new URL('replay-format.js?v=1', document.currentScript?.src || new URL('assets/racing-ui.js', document.baseURI).href); + const sections = [['vanilla','Vanilla Tracks'],['custom','Custom Tracks'],['full-game','Full Game']]; + const phases = {waiting:'In lobby',testing:'Testing connection',starting:'Starting',loading:'Loading',racing:'Racing',returning:'Returning to lobby'}; + const states = {uploading:'Upload incomplete',queued:'Waiting for verification',verified:'Waiting for moderator review',published:'Published',rejected:'Rejected'}; + const clock = ticks => { + if (!Number.isSafeInteger(ticks)) return '—'; + const ms = Math.floor(ticks * 1000 / 60); + return Math.floor(ms / 60000) + ':' + String(Math.floor(ms / 1000) % 60).padStart(2, '0') + + '.' + String(ms % 1000).padStart(3, '0'); + }; + + window.DKRRacingUI = {create({ root, config, Auth, view, user, isStaff, esc, icon, button, pagehead, requireSignedIn, go, renderIcons }) { + const linkedRoom = /^#lobby=([a-f0-9]{32})$/.exec(location.hash)?.[1]; + let online, directoryError, directoryBusy = false, directoryTimer; + let catalogue, board, selectedBoard = '', section = 'vanilla', listingTab = 'boards'; + let privateRows = []; + let leaderboardBusy = false, leaderboardError = '', leaderSequence = 0; + let file, manifest, postMessage = '', posting = false, fileSequence = 0, postError = false; + let currentPage = '', onlineNotice = '', privateIdentity = ''; + + async function request(path, { fresh = false, method = 'GET', body, privateAccess = false, type = 'application/json', download = false } = {}) { + const endpoint = new URL(config.apiBase); + if (endpoint.protocol !== 'https:' || endpoint.username || endpoint.password || endpoint.hash || endpoint.search) + throw new Error('The library address is invalid.'); + const headers = { Accept: download ? 'application/octet-stream' : 'application/json' }; + if (privateAccess) { + await Auth.ensureSession(); + const token = Auth.getToken(); + if (!token) throw new Error('Sign in again to continue.'); + headers.Authorization = 'Bearer ' + token; + } + if (body !== undefined) headers['Content-Type'] = type; + const reply = await fetch(new URL('/v1/' + path, endpoint), { method, body, headers, redirect:'error', + credentials:'omit', cache:fresh ? 'reload' : 'default', signal:AbortSignal.timeout(20000) }); + if (download && reply.ok) return reply.blob(); + const data = await reply.json().catch(() => ({})); + if (reply.ok) return data; + const error = new Error(data.error?.message || 'The service is temporarily unavailable.'); + error.code = data.error?.code; + throw error; + } + + function refreshRegion(selector, template, focusAction) { + const region = root.querySelector(selector); + if (!region) return; + const focused = region.contains(document.activeElement) ? document.activeElement : null; + const action = focusAction || focused?.dataset.action; + const id = focusAction ? null : focused?.dataset.id; + region.innerHTML = template(); + renderIcons(); + if (action) [...region.querySelectorAll('[data-action]')] + .find(node => node.dataset.action === action && (id == null || node.dataset.id === id))?.focus(); + } + + function onlinePage() { + return pagehead('DKR-R Online', 'See who’s online and find a public lobby.') + + '
' + onlineContent() + '
'; + } + function onlineContent() { + const age = online && Date.now() - online.serverTime; + const live = online && age < 90000 && !directoryError; + const count = live ? online.online : '—'; + const status = directoryError === 'disabled' ? 'The public lobby browser is currently disabled.' : + online && !live ? 'Last known rooms. Open DKR-R Online to check availability.' : + directoryError ? 'The lobby list could not be loaded.' : + online ? 'Updates every 30 seconds.' : 'Loading the public lobby list…'; + const rooms = online ? [...online.rooms] : []; + if (linkedRoom) rooms.sort((a, b) => Number(b.id === linkedRoom) - Number(a.id === linkedRoom)); + return '
' + count + + ' players online

' + esc(status) + '

' + + button('online-refresh',icon('refresh-cw') + 'Refresh','quiet small') + '
' + + '

Copy a link and use Find lobby from website in the launcher’s Public lobbies panel. The host approves requests to race or spectate.

' + + (onlineNotice ? '

' + esc(onlineNotice) + '

' : '') + + (rooms.length ? '
' + rooms.map(room => + '

' + esc(room.title) + + '

' + esc(phases[room.phase] || 'Updating') + '
' + + esc(room.racers) + ' / ' + esc(room.maxRacers) + ' racers · ' + esc(room.spectators) + ' / ' + + esc(room.maxSpectators) + ' spectators

' + + (live ? (room.canJoin && room.canSpectate ? 'Racing and spectator spots available' : + room.canJoin ? 'Racing spots available' : room.canSpectate ? 'Spectator spots available' : 'No places available right now') : + 'Check in the launcher for open spots') + '

' + + (live ? '
' + button('online-copy','Copy lobby link','quiet small',room.id) + '
' : '') + '
').join('') + '
' : + live ? '

No public lobbies are open right now.

' : '') + + (live && online.nextCursor ? button('online-more','More lobbies','quiet') : ''); + } + async function loadOnline({ more = false, fresh = false } = {}) { + if (directoryBusy) return; + directoryBusy = true; + try { + const suffix = more && online?.nextCursor ? '?cursor=' + encodeURIComponent(online.nextCursor) : ''; + const data = await request('online/public' + suffix, { fresh }); + if (!Array.isArray(data.rooms) || !Number.isSafeInteger(data.online) || !Number.isSafeInteger(data.serverTime)) + throw new Error('Invalid lobby list.'); + if (more && online) { + const rooms = new Map(online.rooms.map(room => [room.id, room])); + data.rooms.forEach(room => rooms.set(room.id, room)); + online = {...data, rooms:[...rooms.values()]}; + } else online = data; + directoryError = ''; + } catch (error) { + directoryError = error.code || 'unavailable'; + if (directoryError === 'disabled') online = null; + } finally { + directoryBusy = false; + if (view() === 'online') refreshRegion('[data-online-region]', onlineContent, more ? 'online-refresh' : undefined); + } + } + + const postButton = () => button('post-run','Post a run','gold'); + function clearPrivateIfChanged() { + const account = user(); + const identity = account ? account.id + ':' + account.role : ''; + if (identity === privateIdentity) return; + privateIdentity = identity; + if (listingTab !== 'boards') { + ++leaderSequence; + listingTab = 'boards'; + leaderboardError = ''; + leaderboardBusy = false; + privateRows = []; + } + ++fileSequence; + file = manifest = undefined; + postMessage = ''; + postError = false; + } + function speedrunsPage() { + clearPrivateIfChanged(); + return pagehead('Leaderboards','Race for a personal best and watch how other players set theirs.') + + '
' + speedrunContent() + '
'; + } + function speedrunContent() { + if (leaderboardError) return '
' + esc(leaderboardError) + + '
' + button('run-refresh','Try again','quiet') + '
'; + if (listingTab !== 'boards') return runListContent(); + const nav = ''; + const tools = '
' + postButton() + + (user() ? button('run-list','My runs','quiet','mine') : '') + + (isStaff() ? button('run-list','Review runs','quiet','review') : '') + '
'; + if (!catalogue) return nav + '
Loading leaderboards…
'; + const matching = catalogue.boards.filter(value => value.kind === section); + return nav + tools + (board ? rankingContent() : matching.length ? '
' + + matching.map(track => '

' + esc(track.title) + + '

' + esc(track.category) + ' · ' + esc(track.vehicle) + + '

' + button('run-board','View times','quiet',track.id) + '
').join('') + '
' : + '

' + (section === 'full-game' ? 'Full-game categories planned for replay qualification include Any%, 100% and All Trophy Races.' : + 'Times will appear here once the first tracks pass replay qualification.') + '

') + + (section === 'custom' && !board ? customContent() : ''); + } + + function customContent() { + return '

Tracks in the Mod Library

' + + catalogue.customTracks.map(track => '
' + + esc(track.title) + '

Version ' + esc(track.version) + '

' + + (track.qualified ? 'Ranked' : 'Awaiting qualification') + '
').join('') + + (catalogue.customTracks.length ? '' : '

No custom tracks are listed yet.

') + + '
' + (catalogue.nextCursor ? button('run-more','More tracks','quiet') : '') + '
'; + } + function rankingContent() { + return '

' + + esc(board.board.title) + '

' + button('run-back','All tracks','quiet small') + '

' + + esc(board.board.category) + ' · ' + esc(board.board.vehicle) + '

' + + (board.entries.length ? '' + + board.entries.map(entry => '').join('') + '
RankRacerTimeReplay
' + esc(entry.place) + '' + esc(entry.name) + '' + + clock(entry.ticks) + '' + button('run-download','Download','quiet small',entry.id) + + '
' : '

No verified runs have been published yet.

') + '
'; + } + function runListContent() { + return '

' + (listingTab === 'review' ? 'Review runs' : 'My runs') + + '

' + button('run-back','Back to leaderboards','quiet') + '
' + + (leaderboardBusy ? '

Loading runs…

' : privateRows.length ? + '
' + privateRows.map(run => '

' + + esc(run.title) + '

' + esc(states[run.state] || run.state) + + '

' + esc(run.category) + ' · ' + esc(run.vehicle) + ' · ' + clock(run.ticks ?? run.claimedTicks) + + (run.ticks == null ? ' (recorded)' : '') + '

' + esc(run.name) + ' · ' + + esc(run.platform) + ' ' + esc(run.arch) + ' · US ROM ' + esc(run.rom) + '

' + + (run.notes ? '

' + esc(run.notes) + '

' : '') + (run.reason ? '

' + esc(run.reason) + '

' : '') + + '
' + (run.state === 'uploading' ? '' : button('run-download','Download replay','quiet',run.id)) + '
' + + (listingTab === 'review' ? '
' + + button('run-publish','Publish','gold', run.id) + button('run-reject','Reject','red', run.id) + '
' : '') + + '
').join('') + '
' : '

No runs to show yet.

'); + } + + async function loadLeaderboards({ more = false, focus } = {}) { + const seq = ++leaderSequence; + leaderboardBusy = true; + leaderboardError = ''; + try { + if (listingTab !== 'boards') { + const data = await request('speedruns/' + listingTab, { privateAccess:true }); + if (seq === leaderSequence) privateRows = data.runs; + } else if (selectedBoard) { + const data = await request('speedruns/boards/' + encodeURIComponent(selectedBoard)); + if (seq === leaderSequence) board = data; + } else { + const data = await request('speedruns' + (more && catalogue?.nextCursor ? '?cursor=' + encodeURIComponent(catalogue.nextCursor) : '')); + if (seq === leaderSequence) catalogue = more && catalogue ? {...catalogue, nextCursor:data.nextCursor, + customTracks:[...catalogue.customTracks, ...data.customTracks]} : data; + } + } catch (error) { + if (seq === leaderSequence) leaderboardError = error.message; + } finally { + if (seq === leaderSequence) { + leaderboardBusy = false; + if (view() === 'speedruns') refreshRegion('[data-leaderboard-region]',speedrunContent,focus); + if (view() === 'post-run') refreshRegion('[data-post-region]',postContent); + } + } + } + + function postPage() { + clearPrivateIfChanged(); + return pagehead('Post a run','Attach a replay from DKR-R to send it for verification and review.','speedruns') + + '
' + postContent() + '
'; + } + function postContent() { + const qualified = catalogue?.boards?.find(entry => entry.id === manifest?.board); + return '
' + + (!user() ? '

Sign in with the same library account you use to post mods and comments.

' + + button('run-sign-in',icon('user-round') + 'Sign in','gold') : + '' + + (manifest ? '

' + esc(qualified?.title || manifest.board) + '

' + + esc(file.name) + '

' + + esc(qualified?.category || 'Unknown category') + ' · ' + clock(manifest.clockTicks) + + ' recorded · US ROM ' + esc(manifest.rom) + ' · ' + esc(manifest.platform) + '

' : '') + + (!catalogue?.canSubmit ? '

Posting opens once replay verification is ready.

' : '') + + '
' + (catalogue?.canSubmit && qualified && !posting && file ? button('run-upload','Post run','gold') : '') + '
') + + '

' + esc(postMessage) + '

'; + } + root.addEventListener('change', async event => { + if (!event.target.matches('[data-run-file]')) return; + const sequence = ++fileSequence; + const next = event.target.files[0]; + file = manifest = undefined; + postMessage = ''; + postError = false; + if (next) { + try { + const { MAX_REPLAY_BYTES, parseReplay } = await import(replayModule.href); + if (next.size > MAX_REPLAY_BYTES) throw new Error(); + const parsed = parseReplay(new Uint8Array(await next.arrayBuffer())); + if (sequence !== fileSequence || view() !== 'post-run') return; + file = next; + manifest = parsed; + } catch { + if (sequence !== fileSequence || view() !== 'post-run') return; + postMessage = 'Choose a valid .dkrreplay file under 1 MiB.'; + postError = true; + } + } + refreshRegion('[data-post-region]',postContent, file && catalogue?.canSubmit ? 'run-upload' : undefined); + }); + + async function action(action, id, target) { + if (action === 'online' || action === 'speedruns' || action === 'post-run') { await go(action); return true; } + if (action === 'online-refresh' || action === 'online-more') { + await loadOnline({ fresh:action === 'online-refresh', more:action === 'online-more' }); return true; + } + if (action === 'online-copy') { + if (!/^[a-f0-9]{32}$/.test(id)) return true; + const url = 'https://positron-portal.com/dkr-r/#lobby=' + id; + try { + await navigator.clipboard.writeText(url); + onlineNotice = 'Link copied. In DKR-R Online, choose Find lobby from website.'; + } catch { + onlineNotice = 'Copy this link into the clipboard to find the lobby in DKR-R Online. ' + url; + } + refreshRegion('[data-online-region]',onlineContent); + return true; + } + if (action === 'run-category' || action === 'run-back') { + if (action === 'run-category') section = id; + ++leaderSequence; + selectedBoard = ''; board = undefined; listingTab = 'boards'; privateRows = []; leaderboardError = ''; + refreshRegion('[data-leaderboard-region]',speedrunContent); + if (!catalogue) await loadLeaderboards(); + return true; + } + if (action === 'run-board' || action === 'run-list' || action === 'run-more' || action === 'run-refresh') { + if (action === 'run-board') selectedBoard = id; + if (action === 'run-list') { + if (!requireSignedIn({view:'speedruns'},id === 'review')) return true; + listingTab = id; privateRows = []; + } + await loadLeaderboards({more:action === 'run-more', focus:action === 'run-board' ? 'run-back' : undefined}); + return true; + } + if (action === 'run-sign-in') { requireSignedIn({view:'post-run'}); return true; } + if (action === 'run-upload') { + if (posting || !file || !user()) return true; + const owner = user().id; + posting = true; + postError = false; + postMessage = 'Posting your run…'; + refreshRegion('[data-post-region]',postContent); + try { + const data = await request('speedruns/runs', { method:'POST', privateAccess:true, type:'application/octet-stream',body:file }); + if (view() === 'post-run' && user()?.id === owner) { + file = manifest = undefined; + postMessage = 'Run saved. ' + (states[data.run.state] || 'Check My runs for its status') + '.'; + } + } catch (error) { + if (view() === 'post-run' && user()?.id === owner) { postError = true; postMessage = error.message; } + } finally { + posting = false; + refreshRegion('[data-post-region]',postContent); + } + return true; + } + if (action === 'run-download') { + const blob = await request('speedruns/runs/' + encodeURIComponent(id) + '/replay', + { download:true, privateAccess:listingTab !== 'boards' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; link.download = 'DKR-R-' + id + '.dkrreplay'; + link.click(); + setTimeout(() => URL.revokeObjectURL(url),1000); + return true; + } + if (action === 'run-publish' || action === 'run-reject') { + const reason = target.closest('article').querySelector('[data-review-note]').value; + target.disabled = true; + try { + await request('speedruns/runs/' + encodeURIComponent(id) + '/review', { method:'POST', privateAccess:true, + body:JSON.stringify({decision:action === 'run-publish' ? 'published' : 'rejected',reason}) }); + await loadLeaderboards(); + } finally { target.disabled = false; } + return true; + } + return false; + } + + function mounted() { + const next = view(); + if (!root.querySelector('[data-online-region],[data-leaderboard-region],[data-post-region]') && + ['online','speedruns','post-run'].includes(next)) return; + if (next === currentPage) return; + currentPage = next; + clearInterval(directoryTimer); + if (next !== 'post-run') { ++fileSequence; file = manifest = undefined; postMessage = ''; postError = false; } + if (next !== 'speedruns') { ++leaderSequence; listingTab = 'boards'; selectedBoard = ''; board = undefined; privateRows = []; leaderboardError = ''; } + if (next === 'online' && root.querySelector('[data-online-region]')) { + loadOnline(); + directoryTimer = setInterval(() => { if (!document.hidden) loadOnline(); },30000); + } + if ((next === 'speedruns' || next === 'post-run') && !catalogue) loadLeaderboards(); + } + return { onlinePage, speedrunsPage, postPage, action, mounted }; + }}; +}()); diff --git a/runtime-recomp/src/game/mod_library/website/assets/racing.css b/runtime-recomp/src/game/mod_library/website/assets/racing.css new file mode 100644 index 00000000..44fcc94c --- /dev/null +++ b/runtime-recomp/src/game/mod_library/website/assets/racing.css @@ -0,0 +1,17 @@ +#dkr-mod-library .dkr-racing-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr)); + gap: 1rem; +} +#dkr-mod-library .dkr-racing-grid .dkr-panel { min-width: 0; overflow-wrap: anywhere; } +#dkr-mod-library .dkr-racing-count { color: var(--dkr-gold, #ffc15a); font-size: 1.5rem; } +#dkr-mod-library .dkr-racing-list { display: grid; grid-template-columns: minmax(0, 1fr); gap: .65rem; } +#dkr-mod-library .dkr-run-table { width: 100%; border-collapse: collapse; } +#dkr-mod-library .dkr-run-table th, #dkr-mod-library .dkr-run-table td { + text-align: left; + padding: .55rem; + border-bottom: 1px solid #31515d; + overflow-wrap: anywhere; +} +#dkr-mod-library .dkr-run-table th:last-child, #dkr-mod-library .dkr-run-table td:last-child { text-align: right; } +#dkr-mod-library .dkr-racing-file { width: 100%; max-width: 100%; } diff --git a/runtime-recomp/src/game/mod_library/website/assets/replay-format.js b/runtime-recomp/src/game/mod_library/website/assets/replay-format.js new file mode 100644 index 00000000..335e152f --- /dev/null +++ b/runtime-recomp/src/game/mod_library/website/assets/replay-format.js @@ -0,0 +1,37 @@ +// DKRREPL1 stores an UTF-8 manifest and one applied controller sample per 60 Hz tick. +// The file is untrusted evidence. Only native re-simulation can verify its claims. +export const MAX_REPLAY_BYTES = 1024 * 1024; +export const replayHash = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value); +export const replayId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,96}$/.test(value); +const decoder = new TextDecoder('utf-8', { fatal: true }); +const manifestKeys = new Set(['board', 'engine', 'ruleset', 'releaseHash', 'rom', 'platform', 'arch', + 'ticks', 'clockTicks', 'startSeed', 'checkpoints', 'splits', 'notes']); +const tick = (value, maximum) => Number.isInteger(value) && value > 0 && value <= maximum; + +export function parseReplay(bytes) { + const invalid = () => { throw new Error('Choose a valid DKR-R replay made with a supported build.'); }; + if (bytes.byteLength < 16 || bytes.byteLength > MAX_REPLAY_BYTES || + decoder.decode(bytes.subarray(0, 8)) !== 'DKRREPL1') invalid(); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const size = view.getUint32(8, true); + if (size < 2 || size > 16384 || size > bytes.byteLength - 16) invalid(); + const manifest = JSON.parse(decoder.decode(bytes.subarray(12, 12 + size))); + if (!manifest || Array.isArray(manifest) || typeof manifest !== 'object' || + Object.keys(manifest).some(key => !manifestKeys.has(key)) || + !replayId(manifest.board) || !replayHash(manifest.engine) || !replayId(manifest.ruleset) || + (manifest.releaseHash !== null && !replayHash(manifest.releaseHash)) || + ![77, 80].includes(manifest.rom) || !['windows', 'linux'].includes(manifest.platform) || + !['x86_64', 'aarch64'].includes(manifest.arch) || + !tick(manifest.ticks, 216000) || !tick(manifest.clockTicks, manifest.ticks) || + !Number.isInteger(manifest.startSeed) || manifest.startSeed < 0 || manifest.startSeed > 0xffffffff || + bytes.byteLength !== 12 + size + 4 * manifest.ticks || + (manifest.notes !== undefined && (typeof manifest.notes !== 'string' || manifest.notes.length > 600))) invalid(); + const { ticks, clockTicks, checkpoints, splits } = manifest; + if (!Array.isArray(checkpoints) || checkpoints.length !== Math.ceil(ticks / 600)) invalid(); + if (checkpoints.some((entry, index) => !Array.isArray(entry) || entry.length !== 2 || + entry[0] !== Math.min((index + 1) * 600, ticks) || !replayHash(entry[1]))) invalid(); + if (!Array.isArray(splits) || splits.length < 1 || splits.length > 32 || + splits.at(-1) !== clockTicks || + splits.some((value, index) => !tick(value, clockTicks) || (index && value <= splits[index - 1]))) invalid(); + return manifest; +} diff --git a/runtime-recomp/src/game/mod_library/website/index.html b/runtime-recomp/src/game/mod_library/website/index.html index ebe67d65..6c9dc258 100644 --- a/runtime-recomp/src/game/mod_library/website/index.html +++ b/runtime-recomp/src/game/mod_library/website/index.html @@ -22,7 +22,9 @@ - + + +
diff --git a/runtime-recomp/src/game/mod_library/website/privacy.html b/runtime-recomp/src/game/mod_library/website/privacy.html index a238e3bc..7bd47bbe 100644 --- a/runtime-recomp/src/game/mod_library/website/privacy.html +++ b/runtime-recomp/src/game/mod_library/website/privacy.html @@ -14,6 +14,8 @@

What we keep

Download countersDisplay tracked website download requests for each mod.Visitors see aggregate totals. Temporary retry and rate-limit records stay in the private service. Ratings, reviews and datesHelp players choose mods and keep one rating per account for each mod.Visitors when the review is visible. Hidden reviews remain available to their author and staff. Mod requests and repliesCheck a suggested mod and tell you the outcome.The requester and staff. Private staff notes are visible only to staff. +Online player count and public lobby detailsShow how many signed-in players are connected and which lobbies are open to the public.Visitors see the total, public lobby title and available places. Private lobbies and join credentials stay in the launcher. +Speedrun replays, game inputs and run detailsCheck the time, ruleset, ROM revision, track version, platform and recorded inputs before a run is published.You and authorised reviewers see pending runs. Visitors can download published replays and see the display name on the leaderboard. Temporary sign-in records, session hashes and optional remembered-device hashesComplete sign-in and protect account actions.The private account service. Staff upload records, filenames, file sizes, transfer checksums and statusResume interrupted transfers and connect completed files to the library.The private library service and authorised staff. Completed mod packages and cover images are served publicly by the web host. @@ -38,7 +40,7 @@

Requests, retention and deletion

The browser uses a fingerprint of a selected file's size and sample bytes to help match it when resuming an upload. It also checks the previously accepted file chunks against their stored checksums before resuming. These checks identify file contents, not your device. The website does not save the selected file's bytes in browser storage. Deleting a staff account removes the account link from retained upload records; it does not remove files used by published mods.

Published and rejected requests, published draft history and staff activity logs are removed after 180 days by scheduled cleanup. Unfinished requests and unpublished drafts stay available while work is pending. Expired sign-in, session and remembered-device records are removed by scheduled cleanup; expired credentials stop working immediately even before that cleanup runs.

You can delete your website account from account settings. This removes its Discord identity mapping, sessions, remembered devices, ratings, reviews, comments, comment reports and review reports you submitted and your mod requests. In retained staff history, your account name is replaced with “Deleted account”. Published mods and their creator credits stay in the catalogue unless staff remove or update them separately. An administrator must leave another active administrator before deleting their own account.

-

Account deletion removes the live application records. Private provider backups and infrastructure records can have their own retention periods. If you sign in again after deletion, a new website account is created.

+

Deleting your account removes your runs from the leaderboard and makes their replay files unavailable through the website. Scheduled cleanup then removes those files and clears rejected submissions after 30 days. Private provider backups and infrastructure records can have their own retention periods. If you sign in again after deletion, a new website account is created.

Please keep personal information out of public reviews and comments. Mod requests are shared with the team that reviews them; include only the release information and links they need.

Questions or corrections

Contact the DKR-R Mod Library team through the community Discord for help with your account, a review or a request. Use account settings for deletion, and include the relevant mod or request title when asking about a correction.

diff --git a/runtime-recomp/tests/mod_library_community_tests.cjs b/runtime-recomp/tests/mod_library_community_tests.cjs index 4913b214..0d7e1d2b 100644 --- a/runtime-recomp/tests/mod_library_community_tests.cjs +++ b/runtime-recomp/tests/mod_library_community_tests.cjs @@ -4,12 +4,12 @@ const fs = require('node:fs'); const path = require('node:path'); const { randomBytes, createHash } = require('node:crypto'); const root = path.resolve(__dirname, '../..'); -const { Miniflare } = require(path.resolve(process.argv[2] || 'build/library-workflow-d1-runtime/node_modules/miniflare')); +const { Miniflare } = require(path.resolve(process.argv[2] || 'services/test-tools/node_modules/miniflare')); const { JSDOM } = require(path.resolve(process.argv[3] || 'build/library-community-tools/node_modules/jsdom')); -const esbuild = require(path.join(root, 'build/library-community-tools/node_modules/esbuild')); -const { schema } = require('../../patches/library-workflow/tests/support.cjs'); +const esbuild = require(path.join(root, 'services/test-tools/node_modules/esbuild')); +const { schema } = require('../../services/library-workflow/tests/support.cjs'); const source = path.join(root, 'runtime-recomp/src/game/mod_library/website'); -const backend = path.join(root, 'runtime-recomp/src/game/online_profile/backend'); +const backend = path.join(root, 'services/online-directory/api'); const output = path.join(root, 'build/mod-library-community-20261029/tests'); let checks = 0; const equal = (a, b, label) => { assert.equal(a, b, label); checks++; }; @@ -165,7 +165,7 @@ async function websiteTests(mf, db) { ensureSession: async () => {}, onChange: fn => { listeners.add(fn); return () => listeners.delete(fn); } }; w.fetch = (url, options = {}) => mf.dispatchFetch(url, { method: options.method || 'GET', body: options.body, redirect: 'manual', headers: { ...options.headers, Origin: origin } }); w.lucide = { createIcons() {} }; - for (const name of ['api-store.js', 'community-store.js', 'community-ui.js']) w.eval(fs.readFileSync(path.join(source, 'assets', name), 'utf8')); + for (const name of ['api-store.js', 'community-store.js', 'community-ui.js', 'racing-ui.js']) w.eval(fs.readFileSync(path.join(source, 'assets', name), 'utf8')); const originalCreate = w.createLibraryAPI; w.createLibraryAPI = function (...args) { D = originalCreate(...args); return D; }; w.eval(fs.readFileSync(path.join(source, 'assets/app.js'), 'utf8')); diff --git a/services/library-workflow/build.py b/services/library-workflow/build.py index 691f0e08..5e08b205 100644 --- a/services/library-workflow/build.py +++ b/services/library-workflow/build.py @@ -40,7 +40,15 @@ ROOT = HERE.parents[1] COMMUNITY_SITE = ROOT / "runtime-recomp/src/game/mod_library/website" COMMUNITY_API = ROOT / "services/online-directory/api" -COMMUNITY_API_FILES = ("worker.mjs", "library_api.mjs", "community_api.mjs", "community_schema.sql") +COMMUNITY_API_FILES = ( + "worker.mjs", + "library_api.mjs", + "community_api.mjs", + "community_schema.sql", + "speedrun_api.mjs", + "speedrun_replay.mjs", + "speedrun_schema.sql", +) sys.path.insert(0, str(HERE)) import transforms # noqa: E402 @@ -228,7 +236,17 @@ def community(output: Path, archive: Path | None, baseline: Path | None, esbuild ], check=True, ) - shutil.copyfile(COMMUNITY_API / "community_schema.sql", private / "community_schema.sql") + for schema in ("community_schema.sql", "speedrun_schema.sql"): + shutil.copyfile(COMMUNITY_API / schema, private / schema) + directory = ROOT / "services/online-directory" + online = output / "ONLINE-WORKER" + online.mkdir() + for name in ("directory.mjs", "wrangler-online.jsonc"): + shutil.copyfile(directory / name, online / name) + previous_directory = baseline / "ONLINE-WORKER/directory.mjs" + if previous_directory.is_file(): + (rollback / "ONLINE-WORKER").mkdir() + shutil.copyfile(previous_directory, rollback / "ONLINE-WORKER/directory.mjs") for name in COMMUNITY_API_FILES: review.extend( difflib.unified_diff( diff --git a/services/online-directory/api/speedrun_api.mjs b/services/online-directory/api/speedrun_api.mjs new file mode 100644 index 00000000..1bd1ad4e --- /dev/null +++ b/services/online-directory/api/speedrun_api.mjs @@ -0,0 +1,177 @@ +import { __dkrAuth, __dkrCommon, HttpError, finish } from './library_api.mjs'; +import { readReplayBody } from './speedrun_replay.mjs'; +import { parseReplay, replayId } from '../../../runtime-recomp/src/game/mod_library/website/assets/replay-format.js'; + +const { json, requireOrigin, requireRole, safeText, readJSON, randomToken, now } = __dkrCommon; +const fail = (status, code, message) => { throw new HttpError(status, message, code); }; +const all = async (db, sql, ...args) => (await db.prepare(sql).bind(...args).all()).results; +const one = (db, sql, ...args) => db.prepare(sql).bind(...args).first(); +const submitEnabled = env => env.SPEEDRUN_UPLOADS_ENABLED === 'true' && !!env.SPEEDRUN_REPLAYS; +const key = id => 'runs/' + id + '.dkrreplay'; +const verified = "r.verified_ticks > 0 AND length(r.verifier_digest)=64"; +const visible = "r.state='published' AND a.status='active' AND " + verified; +const validRelease = "(b.kind<>'custom' OR EXISTS (SELECT 1 FROM launcher_release_integrity i WHERE i.release_id=b.release_id AND i.sha256=b.release_sha256))"; + +function board(row) { + return { id: row.id, kind: row.kind, title: row.title, category: row.category, vehicle: row.vehicle, + ruleset: row.ruleset, releaseId: row.release_id, releaseHash: row.release_sha256 }; +} + +async function catalogue(db, env, url) { + const cursor = url.searchParams.get('cursor') || ''; + if (cursor && !replayId(cursor)) fail(400, 'cursor', 'Invalid track page.'); + const rows = await all(db, `SELECT i.id,i.title,r.id AS release_id,r.version,h.sha256 + FROM library_items i JOIN library_releases r ON r.id=i.current_release_id + LEFT JOIN launcher_release_integrity h ON h.release_id=r.id + WHERE i.category='tracks' AND i.archived=0 AND i.id>? ORDER BY i.id LIMIT 41`, cursor); + const boards = await all(db, `SELECT b.* FROM speedrun_boards b WHERE ${validRelease} ORDER BY b.title,b.category,b.vehicle LIMIT 2000`); + return json({ canSubmit: submitEnabled(env) && boards.length > 0, + boards: cursor ? [] : boards.map(board), + customTracks: rows.slice(0,40).map(row => ({ id: row.id, title: row.title, releaseId: row.release_id, + version: row.version, qualified: !!row.sha256 && boards.some(b => b.release_id === row.release_id && b.release_sha256 === row.sha256) })), + nextCursor: rows.length > 40 ? rows[39].id : '' }); +} + +async function ranking(db, id) { + const info = await one(db, `SELECT b.* FROM speedrun_boards b WHERE b.id=? AND ${validRelease}`, id); + if (!info) fail(404, 'board_missing', 'That leaderboard is unavailable.'); + const rows = await all(db, `WITH eligible AS ( + SELECT r.id,r.account_id,r.verified_ticks,r.created_at,a.display_name, + ROW_NUMBER() OVER (PARTITION BY r.account_id ORDER BY r.verified_ticks,r.created_at,r.id) AS personal_order + FROM speedrun_runs r JOIN accounts a ON a.id=r.account_id + WHERE r.board_id=? AND ${visible} + ) SELECT id,display_name,verified_ticks, + RANK() OVER (ORDER BY verified_ticks) AS place + FROM eligible WHERE personal_order=1 ORDER BY verified_ticks,created_at,id LIMIT 100`, id); + return json({ board: board(info), entries: rows.map(row => ({ id: row.id, name: row.display_name, ticks: row.verified_ticks, place: row.place })) }); +} + +async function enqueue(request, env, db) { + if (!submitEnabled(env)) fail(503, 'pilot_closed', 'Run submissions are closed while replay verification is being tested.'); + const user = await __dkrAuth.requireUser(request, env); + const bytes = await readReplayBody(request); + let manifest; + try { if (bytes) manifest = parseReplay(bytes); } catch { /* Invalid replay evidence. */ } + if (!manifest) fail(400, 'invalid_replay', 'Choose a valid DKR-R replay under 1 MiB.'); + const match = await one(db, `SELECT b.* FROM speedrun_boards b WHERE b.id=? AND ${validRelease}`, manifest.board); + if (!match || match.engine !== manifest.engine || match.ruleset !== manifest.ruleset || + match.release_sha256 !== manifest.releaseHash) fail(409, 'board_mismatch', 'This build or track version is not qualified for that board.'); + + const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), value => value.toString(16).padStart(2,'0')).join(''); + const stamp = now(); + const existing = () => one(db, 'SELECT id,state FROM speedrun_runs WHERE account_id=? AND sha256=?', user.id, hash); + let run = await existing(); + if (!run) { + await db.prepare(`INSERT OR IGNORE INTO speedrun_runs(id,account_id,board_id,sha256,manifest,notes,state,created_at,updated_at) + SELECT ?,?,?,?,?,?,'uploading',?,? + WHERE (SELECT COUNT(*) FROM speedrun_runs WHERE account_id=? AND created_at>?)<10 + AND (SELECT COUNT(*) FROM speedrun_runs WHERE state IN ('uploading','queued','verified'))<1000`) + .bind(randomToken(18), user.id, match.id, hash, JSON.stringify(manifest), + safeText(manifest.notes, 600, 'Notes'), stamp, stamp, user.id, stamp - 86400).run(); + run = await existing(); + } + if (!run) fail(429, 'queue_limit', 'The submission limit was reached. Try again later.'); + if (run.state === 'uploading') { + await env.SPEEDRUN_REPLAYS.put(key(run.id), bytes, { httpMetadata: { contentType: 'application/octet-stream' } }); + await db.prepare("UPDATE speedrun_runs SET state='queued',updated_at=? WHERE id=? AND state='uploading'").bind(now(), run.id).run(); + run = await existing(); + } + return json({ run }, 202); +} + +async function download(request, env, db, id) { + const row = await one(db, `SELECT r.*,a.status AS account_status,(${visible}) AS downloadable + FROM speedrun_runs r JOIN accounts a ON a.id=r.account_id WHERE r.id=?`, id); + if (!row || row.account_status !== 'active' || row.state === 'uploading') + fail(404, 'replay_missing', 'This replay is unavailable.'); + if (!row.downloadable) { + const user = request.headers.has('Authorization') ? await __dkrAuth.requireUser(request, env) : null; + if (!user || user.id !== row.account_id && !['admin','moderator'].includes(user.role)) + fail(404, 'replay_missing', 'This replay is unavailable.'); + } + const object = await env.SPEEDRUN_REPLAYS?.get(key(id)); + if (!object) fail(404, 'replay_missing', 'This replay is unavailable.'); + return new Response(object.body, { headers: { 'Content-Type':'application/octet-stream', + 'Content-Disposition': 'attachment; filename="DKR-R-' + id + '.dkrreplay"' } }); +} + +async function myRuns(request, env, db, review) { + const user = await __dkrAuth.requireUser(request, env); + if (review) requireRole(user, 'moderator'); + const rows = await all(db, `SELECT r.id,r.state,r.verified_ticks,r.notes,r.created_at,r.manifest, + b.title,b.category,b.vehicle,a.display_name,m.reason + FROM speedrun_runs r JOIN speedrun_boards b ON b.id=r.board_id JOIN accounts a ON a.id=r.account_id + LEFT JOIN speedrun_moderation m ON m.run_id=r.id + WHERE ${review ? "r.state='verified' AND a.status='active' AND " + verified : "r.account_id=?"} + ORDER BY r.created_at DESC,r.id DESC LIMIT 50`, ...(review ? [] : [user.id])); + return json({ runs: rows.map(row => { + const { rom, platform, arch, clockTicks } = JSON.parse(row.manifest); + return { id: row.id, state: row.state, ticks: row.verified_ticks, claimedTicks: clockTicks, + title: row.title, category: row.category, vehicle: row.vehicle, notes: row.notes, + name: row.display_name, createdAt: row.created_at, rom, platform, arch, reason: row.reason }; + }) }); +} + +async function moderate(request, env, db, id) { + const user = await __dkrAuth.requireUser(request, env); + requireRole(user, 'moderator'); + const body = await readJSON(request, 4096); + const decision = body.decision; + if (!['published','rejected'].includes(decision)) fail(400, 'decision', 'Choose Publish or Reject.'); + const reason = safeText(body.reason, 600, 'Review note', decision === 'rejected'); + const result = await db.prepare(`INSERT OR IGNORE INTO speedrun_moderation(run_id,moderator_id,decision,reason,decided_at) + SELECT r.id,?,?,?,? FROM speedrun_runs r JOIN speedrun_boards b ON b.id=r.board_id + JOIN accounts a ON a.id=r.account_id WHERE r.id=? AND r.state='verified' + AND a.status='active' AND ${verified} AND ${validRelease}`).bind(user.id, decision, reason, now(), id).run(); + if (!result.meta.changes) fail(409, 'review_unavailable', 'This run is not independently verified or was already reviewed.'); + return json({ saved: true }); +} + +// The signed-in routes hide deleted accounts immediately. Scheduled cleanup +// removes their private replay bytes and old rejected submissions in batches. +export async function cleanupSpeedruns(env) { + if (!env.DB || !env.SPEEDRUN_REPLAYS) return; + const db = env.DB.withSession ? env.DB.withSession('first-primary') : env.DB; + const expired = await all(db, `SELECT r.id FROM speedrun_runs r JOIN accounts a ON a.id=r.account_id + WHERE a.status='deleted' OR (r.state='rejected' AND r.updated_at key(row.id))); + const ids = expired.map(row => row.id); + await db.prepare(`DELETE FROM speedrun_runs WHERE id IN (${ids.map(() => '?').join(',')})`).bind(...ids).run(); +} + +export async function handleSpeedrun(request, env) { + const url = new URL(request.url); + const path = url.pathname; + if (path !== '/v1/speedruns' && !path.startsWith('/v1/speedruns/')) return null; + let response; + try { + if (url.protocol !== 'https:') fail(400, 'https', 'Use HTTPS.'); + const db = env.DB?.withSession ? env.DB.withSession('first-primary') : env.DB; + if (!db) fail(503, 'unavailable', 'The leaderboards are temporarily unavailable.'); + const { method } = request; + const run = path.match(/^\/v1\/speedruns\/runs\/([A-Za-z0-9_-]{1,96})\/(replay|review)$/); + const boardPath = path.match(/^\/v1\/speedruns\/boards\/([A-Za-z0-9_-]{1,96})$/); + if (method === 'OPTIONS') { + requireOrigin(request, env); + response = new Response(null, { status: 204 }); + } else if (method === 'GET' && path === '/v1/speedruns') response = await catalogue(db, env, url); + else if (method === 'GET' && boardPath) response = await ranking(db, boardPath[1]); + else if (method === 'GET' && path === '/v1/speedruns/mine') response = await myRuns(request, env, db, false); + else if (method === 'GET' && path === '/v1/speedruns/review') response = await myRuns(request, env, db, true); + else if (method === 'GET' && run?.[2] === 'replay') response = await download(request, env, db, run[1]); + else if (method === 'POST') { + // Native clients use the same bearer-token session without an Origin. + if (request.headers.has('Origin')) requireOrigin(request, env); + if (path === '/v1/speedruns/runs') response = await enqueue(request, env, db); + else if (run?.[2] === 'review') response = await moderate(request, env, db, run[1]); + } + if (!response) fail(404, 'not_found', 'This speedrun page does not exist.'); + } catch (error) { + const known = error instanceof HttpError; + response = json({ error: { code: known ? error.code : 'unavailable', + message: known ? error.message : 'The leaderboards are temporarily unavailable.' } }, known ? error.status : 503); + } + return finish(response, request, env); +} diff --git a/services/online-directory/api/speedrun_replay.mjs b/services/online-directory/api/speedrun_replay.mjs new file mode 100644 index 00000000..d009aae8 --- /dev/null +++ b/services/online-directory/api/speedrun_replay.mjs @@ -0,0 +1,23 @@ +import { MAX_REPLAY_BYTES } from '../../../runtime-recomp/src/game/mod_library/website/assets/replay-format.js'; + +export async function readReplayBody(request) { + if (!request.body || request.headers.get('Content-Type') !== 'application/octet-stream' || + Number(request.headers.get('Content-Length')) > MAX_REPLAY_BYTES) return null; + const reader = request.body.getReader(); + const bytes = new Uint8Array(MAX_REPLAY_BYTES); + let length = 0; + try { + while (true) { + const { value, done } = await reader.read(); + if (done) return bytes.subarray(0, length); + if (value.byteLength > bytes.length - length) { + await reader.cancel(); + return null; + } + bytes.set(value, length); + length += value.byteLength; + } + } finally { + reader.releaseLock(); + } +} diff --git a/services/online-directory/api/speedrun_schema.sql b/services/online-directory/api/speedrun_schema.sql new file mode 100644 index 00000000..acb651a2 --- /dev/null +++ b/services/online-directory/api/speedrun_schema.sql @@ -0,0 +1,46 @@ +-- Only the independent verifier may attest a replay. The public API can queue +-- submissions and moderate attested runs; it has no verification HTTP route. +CREATE TABLE IF NOT EXISTS speedrun_boards ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ('vanilla','custom','full-game')), + title TEXT NOT NULL, + category TEXT NOT NULL, + vehicle TEXT NOT NULL CHECK (vehicle IN ('car','hovercraft','plane','mixed')), + ruleset TEXT NOT NULL, + engine TEXT NOT NULL, + release_id TEXT REFERENCES library_releases(id), + release_sha256 TEXT, + CHECK ((kind='custom' AND release_id IS NOT NULL AND length(release_sha256)=64) + OR (kind<>'custom' AND release_id IS NULL AND release_sha256 IS NULL)) +); +CREATE TABLE IF NOT EXISTS speedrun_runs ( + id TEXT PRIMARY KEY, + account_id TEXT NOT NULL REFERENCES accounts(id), + board_id TEXT NOT NULL REFERENCES speedrun_boards(id), + sha256 TEXT NOT NULL, + manifest TEXT NOT NULL, + notes TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('uploading','queued','verified','published','rejected')), + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + verified_ticks INTEGER CHECK (verified_ticks IS NULL OR verified_ticks > 0), + verifier_digest TEXT, + UNIQUE (account_id,sha256) +); +CREATE INDEX IF NOT EXISTS speedrun_runs_by_account ON speedrun_runs(account_id,created_at DESC,id DESC); +CREATE INDEX IF NOT EXISTS speedrun_runs_by_board ON speedrun_runs(board_id,state,verified_ticks); +CREATE INDEX IF NOT EXISTS speedrun_runs_by_state ON speedrun_runs(state,created_at,id); +CREATE TABLE IF NOT EXISTS speedrun_moderation ( + run_id TEXT PRIMARY KEY REFERENCES speedrun_runs(id) ON DELETE CASCADE, + moderator_id TEXT NOT NULL REFERENCES accounts(id), + decision TEXT NOT NULL CHECK (decision IN ('published','rejected')), + reason TEXT NOT NULL, + decided_at INTEGER NOT NULL +); + +CREATE TRIGGER IF NOT EXISTS speedrun_apply_moderation +AFTER INSERT ON speedrun_moderation +BEGIN + UPDATE speedrun_runs SET state=NEW.decision,updated_at=NEW.decided_at + WHERE id=NEW.run_id AND state='verified'; +END; diff --git a/services/online-directory/api/worker.mjs b/services/online-directory/api/worker.mjs index 9a197545..6a764a4f 100644 --- a/services/online-directory/api/worker.mjs +++ b/services/online-directory/api/worker.mjs @@ -1,19 +1,47 @@ +import { handleSpeedrun, cleanupSpeedruns } from './speedrun_api.mjs'; import library, { HttpError } from './library_api.mjs'; import { handleLauncherProfile, launcherVerifiedSocial } from './profile_api.mjs'; import { handleCommunity, communityCatalogue, cleanupCommunity } from './community_api.mjs'; +// The website uses a read-only projection. Never forward browser credentials +// or actor headers to the directory. +async function publicOnline(request, env, url) { + const headers = { 'Cache-Control': 'no-store', 'Access-Control-Allow-Origin': '*' }; + const error = (status, code) => Response.json({ error: { code } }, { status, headers }); + if (request.method !== 'GET') return error(405, 'method'); + if (url.protocol !== 'https:') return error(400, 'https'); + if (env.ONLINE_ENABLED !== 'true' || !env.ONLINE_DIRECTORY) return error(503, 'disabled'); + + const cursor = url.searchParams.get('cursor') || ''; + if (cursor && !/^[a-f0-9]{32}$/.test(cursor)) return error(400, 'cursor'); + const forwarded = new URL('/v1/online/public', url.origin); + if (cursor) forwarded.searchParams.set('cursor', cursor); + try { + const response = await env.ONLINE_DIRECTORY.fetch(new Request(forwarded)); + if (!response.ok) return error(503, 'unavailable'); + headers['Cache-Control'] = 'public, max-age=15, s-maxage=15'; + return Response.json(await response.json(), { headers }); + } catch { + return error(503, 'unavailable'); + } +} + export default { scheduled(event,env,ctx) { ctx.waitUntil(cleanupCommunity(env).catch(() => {})); + ctx.waitUntil(cleanupSpeedruns(env).catch(() => { console.error('Speedrun cleanup failed.'); })); return library.scheduled(event,env,ctx); }, async fetch(request, env, ctx) { try { const community = await handleCommunity(request, env, ctx); if (community) return community; + const speedrun = await handleSpeedrun(request, env); + if (speedrun) return speedrun; const profile = await handleLauncherProfile(request, env); if(profile)return profile; const url=new URL(request.url); + if (url.pathname === '/v1/online/public') return publicOnline(request, env, url); if(url.pathname==='/v1/online/capabilities' && request.method==='GET') { const response=await library.fetch(request,env,ctx); if(!response.ok)return response; diff --git a/services/online-directory/build.py b/services/online-directory/build.py index 52625630..0f9a3add 100644 --- a/services/online-directory/build.py +++ b/services/online-directory/build.py @@ -51,6 +51,7 @@ def compose(output, esbuild, rollback_api=None, rollback_directory=None): ) shutil.copy2(API / "discord_schema.sql", output / "PRIVATE-API/001-launcher-discord-profiles.sql") shutil.copy2(API / "profile_schema.sql", output / "PRIVATE-API/002-launcher-profiles.sql") + shutil.copy2(API / "speedrun_schema.sql", output / "PRIVATE-API/003-speedruns.sql") for name in ("directory.mjs", "wrangler-online.jsonc"): shutil.copy2(AUTH / name, output / "ONLINE-WORKER" / name) for source, name in ((rollback_api, "worker-single-file.mjs"), (rollback_directory, "directory.mjs")): @@ -93,6 +94,7 @@ def compose(output, esbuild, rollback_api=None, rollback_directory=None): shutil.copy2(path, output / path.name) sources = [ *sorted(API.glob("*")), + ROOT / "runtime-recomp/src/game/mod_library/website/assets/replay-format.js", AUTH / "directory.mjs", AUTH / "wrangler-online.jsonc", *docs, diff --git a/services/online-directory/directory.mjs b/services/online-directory/directory.mjs index 6ba0c4c2..1795b26e 100644 --- a/services/online-directory/directory.mjs +++ b/services/online-directory/directory.mjs @@ -141,6 +141,15 @@ export class WorldwideDirectory extends DurableObject { return { rooms: active.slice(0, 50).map(room => publicRoom(room, this.env.RUNNING_SPECTATORS_ENABLED === 'true')), nextCursor: active.length > 50 ? active[49].id : '', online: this.count(), revision: this.revision(), serverTime: Date.now() }; } + publicSnapshot(cursor) { + const { rooms, online, nextCursor, serverTime } = this.list(cursor); + return { + online, nextCursor, serverTime, + rooms: rooms.map(({ id, title, phase, racers, maxRacers, spectators, maxSpectators, canJoin, canSpectate }) => ({ + id, title, phase, racers, maxRacers, spectators, maxSpectators, canJoin, canSpectate + })) + }; + } cleanup() { const now = Date.now(); let changed = false; for (const [id, session] of this.sessions) if (!this.live(session.data, now)) { @@ -190,6 +199,9 @@ export class WorldwideDirectory extends DurableObject { async fetch(request) { try { const url = new URL(request.url); + // This route is only reachable through the private service binding. + if (url.pathname === '/v1/online/public' && request.method === 'GET') + return json(this.publicSnapshot(url.searchParams.get('cursor') || '')); let who; if (url.pathname === '/v1/online/connect') { const protocols = (request.headers.get('Sec-WebSocket-Protocol') || '').split(',').map(s => s.trim()); diff --git a/services/online-directory/tests/build_tests.py b/services/online-directory/tests/build_tests.py index 54bceb1d..63ffc9a1 100644 --- a/services/online-directory/tests/build_tests.py +++ b/services/online-directory/tests/build_tests.py @@ -40,7 +40,15 @@ def test_native_modules_bundle_with_exact_rollback_inputs(self): inputs = json.loads((out / "API-BUILD-INPUTS.json").read_text())["inputs"] self.assertEqual( {Path(name).name for name in inputs}, - {"worker.mjs", "library_api.mjs", "profile_api.mjs", "community_api.mjs"}, + { + "worker.mjs", + "library_api.mjs", + "profile_api.mjs", + "community_api.mjs", + "speedrun_api.mjs", + "speedrun_replay.mjs", + "replay-format.js", + }, ) self.assertEqual((out / "ROLLBACK/worker-single-file.mjs").read_bytes(), previous.read_bytes()) self.assertTrue((out / "PRIVATE-API/002-launcher-profiles.sql").is_file()) diff --git a/services/online-directory/tests/runtime.cjs b/services/online-directory/tests/runtime.cjs index bbb9d562..e679a901 100644 --- a/services/online-directory/tests/runtime.cjs +++ b/services/online-directory/tests/runtime.cjs @@ -85,6 +85,12 @@ async function main(){ const state={title:'Private test',epoch:'epoch-one',compatibility:'test-network',visibility:'private',phase:'waiting',racers:1,maxRacers:2,spectators:0,maxSpectators:8,reservedRacers:0,reservedSpectators:0,roster:'1',code:'ABCD1',bootstrap:'ABCD1',canSpectateRunning:true}; let room=(await host.call({type:'room',revision:0,state})).data; check(room.id,'private room created'); + const webPrivate=await (await http('/v1/online/public')).json(); + equal(webPrivate.online,3,'website sees the same deduplicated active player count'); + equal(webPrivate.rooms.length,0,'website excludes live private rooms'); + equal((await http('/v1/online/public',null,null,'POST')).status,405,'website projection is read-only'); + equal((await http('/v1/online/public?cursor=invalid')).status,400,'invalid public cursor is refused'); + equal((await http('/v1/online/lobbies')).status,401,'launcher list remains authenticated'); equal((await guest.call({type:'list'})).data.rooms.length,0,'private room omitted from public payload'); equal((await guest.call({type:'join',room:room.id,role:'racer',key:key(),compatibility:'test-network'})).error.code,'unavailable','private room identifier grants no public access'); equal((await guest.call({type:'resolve',code:'WRONG',role:'racer',key:key(),compatibility:'test-network'})).error.code,'unavailable','unknown private code is not searchable'); @@ -99,6 +105,16 @@ async function main(){ const wire=JSON.stringify(list); check(!wire.includes('ABCD1')&&!wire.includes('admission')&&!wire.includes('owner')&&!wire.includes('account'),'public payload excludes connection secrets and account identifiers'); equal(list.rooms[0].host,'Player host','verified display name preserved'); + const webResponse=await http('/v1/online/public'); + equal(webResponse.headers.get('Cache-Control'),'public, max-age=15, s-maxage=15','website projection is briefly cacheable'); + const web=await webResponse.json(); + equal(web.rooms.length,1,'public lobby visible on the website'); + const projection=web.rooms[0]; + assert.deepEqual(Object.keys(projection).sort(), + ['canJoin','canSpectate','id','maxRacers','maxSpectators','phase','racers','spectators','title']); + equal(projection.id,room.id,'public reference matches the launcher room'); + equal(projection.title,'Public test','public title matches the launcher room'); + equal((await (await http('/v1/online/public?cursor='+room.id)).json()).rooms.length,0,'public cursor advances the list'); equal((await other.call({type:'room',revision:room.revision,state:{...state,epoch:'bad',visibility:'invalid'}})).error.code,'invalid','invalid host state rejected'); const firstKey=key(); const intent=await guest.call({type:'join',room:room.id,role:'racer',key:firstKey,compatibility:'test-network'},'idempotent'); diff --git a/services/online-directory/tests/speedrun_api.cjs b/services/online-directory/tests/speedrun_api.cjs new file mode 100644 index 00000000..f47f67a9 --- /dev/null +++ b/services/online-directory/tests/speedrun_api.cjs @@ -0,0 +1,122 @@ +// Local Workers, SQLite-backed D1, and private R2 integration test. +const assert = require('node:assert/strict'); +const { createHash, randomBytes } = require('node:crypto'); +const fs = require('node:fs'); +const path = require('node:path'); +const { Miniflare } = require('../../test-tools/node_modules/miniflare'); +const { schema } = require('../../library-workflow/tests/support.cjs'); + +const origin = 'https://positron-portal.com'; +const engine = 'a'.repeat(64); +const releaseHash = 'b'.repeat(64); +const verifierDigest = 'c'.repeat(64); + +function replay(overrides = {}, samples = Buffer.alloc(240)) { + const manifest = Buffer.from(JSON.stringify({ + board:'ancient-lake-car', engine, ruleset:'tt-1', releaseHash:null, rom:80, + platform:'linux', arch:'x86_64', ticks:60, clockTicks:60, startSeed:7, + checkpoints:[[60,'0'.repeat(64)]], splits:[60], ...overrides, + })); + const prefix = Buffer.alloc(12); + prefix.write('DKRREPL1'); + prefix.writeUInt32LE(manifest.length, 8); + return Buffer.concat([prefix, manifest, samples]); +} + +async function main() { + const root = path.resolve(process.argv[2]); + const mf = new Miniflare({ + modules:true, modulesRoot:root, scriptPath:path.join(root,'PRIVATE-API/worker-single-file.mjs'), + d1Databases:['DB'], r2Buckets:['SPEEDRUN_REPLAYS'], + bindings:{FRONTEND_URL:origin + '/dkr-r/index.html', SPEEDRUN_UPLOADS_ENABLED:'true'} + }); + try { + const db = await mf.getD1Database('DB'); + await db.exec(schema); + const migration = fs.readFileSync(path.join(root,'PRIVATE-API/003-speedruns.sql'),'utf8'); + const delimiter = migration.indexOf('CREATE TRIGGER'); + await db.exec(migration.slice(0, delimiter).replace(/^--.*$/gm, '').replace(/\s+/g, ' ').trim()); + await db.prepare(migration.slice(delimiter)).run(); + const tokens = {}; + const stamp = Math.floor(Date.now() / 1000); + for (const [id, role] of [['alice','player'],['bob','player'],['reviewer','moderator']]) { + tokens[id] = randomBytes(32).toString('base64url'); + await db.prepare('INSERT INTO accounts VALUES(?,?,?,?,?,?,?)').bind(id,id,id,role,'active',stamp,stamp).run(); + await db.prepare('INSERT INTO sessions VALUES(?,?,?,?,?,?,NULL)').bind( + createHash('sha256').update(tokens[id]).digest('base64url'), id, stamp, stamp, stamp + 3600, stamp + 86400).run(); + } + const fetch = (route, options = {}) => mf.dispatchFetch('https://review.invalid/v1/speedruns' + route, { + ...options, headers:{Origin:origin,...(options.user ? {Authorization:'Bearer ' + tokens[options.user]} : {}),...options.headers} + }); + const post = (id, body, from = origin) => fetch('/runs',{method:'POST',user:id,body, + headers:{Origin:from,'Content-Type':'application/octet-stream'}}); + const review = (id, user, decision, reason = '') => fetch('/runs/' + id + '/review',{method:'POST',user, + headers:{'Content-Type':'application/json'},body:JSON.stringify({decision,reason})}); + const submit = async (id, body) => { + const response = await post(id,body); + assert.equal(response.status,202,await response.clone().text()); + return (await response.json()).run; + }; + const catalogue = async () => (await fetch('')).json(); + assert.equal((await catalogue()).canSubmit,false); + await db.prepare("INSERT INTO library_items(id,title,category,archived,current_release_id) VALUES('custom','Custom course','tracks',0,'release1')").run(); + await db.prepare("INSERT INTO library_releases(id,item_id,version) VALUES('release1','custom','1.0')").run(); + await db.prepare("INSERT INTO library_releases(id,item_id,version) VALUES('release2','custom','1.1')").run(); + const addBoard = (id, kind, title, release = null, sha = null) => db.prepare('INSERT INTO speedrun_boards VALUES(?,?,?,?,?,?,?,?,?)') + .bind(id,kind,title,'Time Trial','car','tt-1',engine,release,sha).run(); + await addBoard('ancient-lake-car','vanilla','Ancient Lake'); + await addBoard('custom-car','custom','Custom course','release1',releaseHash); + let state = await catalogue(); + assert.equal(state.canSubmit,true); + assert.equal(state.boards.length,1); + assert.equal(state.customTracks[0].qualified,false); + await db.prepare("INSERT INTO launcher_release_integrity VALUES('release1',?,?,?)").bind(releaseHash,128,stamp).run(); + state = await catalogue(); + assert.equal(state.boards.length,2); + assert.equal(state.customTracks[0].qualified,true); + await db.prepare("UPDATE library_items SET current_release_id='release2' WHERE id='custom'").run(); + assert.equal((await catalogue()).customTracks[0].qualified,false,'new version has separate qualification'); + + assert.equal((await post(null,replay())).status,401); + assert.equal((await post('alice',replay(),'https://foreign.invalid')).status,403); + for (const bad of [Buffer.alloc(4), Buffer.alloc(1024*1024+1), replay({ticks:61}), replay({rom:1}), + replay({checkpoints:[[59,'0'.repeat(64)]]}), replay({verified:true}), replay({splits:[60,60]})]) + assert.equal((await post('alice',bad)).status,400); + assert.equal((await post('alice',replay({engine:'f'.repeat(64)}))).status,409); + assert.equal((await post('alice',replay({board:'custom-car'}))).status,409); + const proof = replay(); + const alice = await submit('alice',proof); + assert.equal(alice.state,'queued'); + assert.equal((await submit('alice',proof)).id,alice.id,'resubmission is idempotent'); + const alice2 = await submit('alice',replay({ clockTicks:59, splits:[59] })); + const bob = await submit('bob',proof); + assert.notEqual(alice.id,bob.id,'private replay identity is account scoped'); + assert.equal((await fetch('/runs/'+alice.id+'/replay')).status,404); + assert.equal((await fetch('/runs/'+alice.id+'/replay',{user:'bob'})).status,404); + assert.deepEqual(Buffer.from(await (await fetch('/runs/'+alice.id+'/replay',{user:'alice'})).arrayBuffer()),proof); + assert.equal((await review(alice.id,'alice','published')).status,403); + assert.equal((await review(alice.id,'reviewer','published')).status,409,'a moderator cannot bypass verification'); + assert.equal((await fetch('/review',{user:'alice'})).status,403); + assert.equal((await (await fetch('/mine',{user:'alice'})).json()).runs.length,2); + assert.equal((await (await fetch('/review',{user:'reviewer'})).json()).runs.length,0); + const entries = async () => (await (await fetch('/boards/ancient-lake-car')).json()).entries; + assert.deepEqual(await entries(),[]); + // Seed only the trust boundary result. This fixture does not attest engine determinism. + for (const [id,ticks] of [[alice.id,65],[alice2.id,64],[bob.id,64]]) { + await db.prepare("UPDATE speedrun_runs SET state='verified',verified_ticks=?,verifier_digest=? WHERE id=?") + .bind(ticks,verifierDigest,id).run(); + assert.equal((await review(id,'reviewer','published')).status,200); + } + const leaderboard = await entries(); + assert.equal(leaderboard.length,2,'one PB per account'); + assert.equal(leaderboard[0].ticks,64,'time comes from verifier result, not upload'); + assert.equal(leaderboard[1].place,1,'equal times share rank'); + assert.deepEqual(Buffer.from(await (await fetch('/runs/'+alice2.id+'/replay')).arrayBuffer()),replay({clockTicks:59,splits:[59]})); + assert.equal((await review(alice2.id,'reviewer','published')).status,409); + await db.prepare("UPDATE accounts SET status='deleted' WHERE id='alice'").run(); + assert.equal((await entries()).length,1); + assert.equal((await fetch('/runs/'+alice2.id+'/replay')).status,404); + console.log('Ranked API passed: catalogue, version gate, bounded replay upload, retry, privacy, verification gate, moderation and PB ranking.'); + } finally { await mf.dispose(); } +} +main().catch(error => { console.error(error); process.exitCode=1; }); From 65406682f8111f71f5177102d4eaeed343e9c1a9 Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Sun, 22 Nov 2026 00:48:42 +0000 Subject: [PATCH 12/31] Add compact launcher leaderboards and online activity history --- docs/MOD_LIBRARY_WEBSITE.md | 16 ++ .../src/game/library_ui/leaderboards_page.inl | 206 ++++++++++++++++++ .../src/game/library_ui/navigation_check.inl | 15 +- .../src/game/library_ui/play_tools.inl | 49 +++-- runtime-recomp/src/game/library_ui/policy.hpp | 4 +- .../src/game/library_ui/shared_page_ui.inl | 5 + .../game/mod_library/website/assets/app.js | 2 +- .../mod_library/website/assets/racing-ui.js | 74 ++++++- .../mod_library/website/assets/racing.css | 42 ++++ .../src/game/mod_library/website/index.html | 6 +- .../src/game/mod_library/website/privacy.html | 2 +- runtime-recomp/src/game/mod_store.cpp | 53 +++++ runtime-recomp/src/game/mod_store.hpp | 4 + .../src/game/runtime_mod_library_ui.inl | 87 ++++---- runtime-recomp/src/game/runtime_play_ui.inl | 12 +- runtime-recomp/tests/library_ui_tests.cpp | 3 +- .../tests/play_launch_layout_tests.py | 18 +- services/online-directory/api/worker.mjs | 24 +- services/online-directory/directory.mjs | 116 +++++++++- services/online-directory/tests/runtime.cjs | 41 +++- 20 files changed, 685 insertions(+), 94 deletions(-) create mode 100644 runtime-recomp/src/game/library_ui/leaderboards_page.inl diff --git a/docs/MOD_LIBRARY_WEBSITE.md b/docs/MOD_LIBRARY_WEBSITE.md index 778c2c19..a70896d1 100644 --- a/docs/MOD_LIBRARY_WEBSITE.md +++ b/docs/MOD_LIBRARY_WEBSITE.md @@ -97,6 +97,17 @@ room list as the launcher. This endpoint never forwards a browser credential or a private room. The browser polls every 30 seconds while visible. A missing count is shown as unavailable, and an available count of zero is shown as zero. +The Online card shows currently connected unique accounts against the number +of active accounts that have signed in through the shared library sign-in. +People with several launcher instances count once. Live public lobby, racer +and spectator totals only include publicly listed lobbies. + +Player activity has 7-day, 30-day and All-time views. Each view shows the +peak and days with activity. The recent views also show the busiest hour, new +sign-ups and daily peaks. All time keeps the first timestamp of the lifetime +peak, the total active days and a lifetime history chart. The chart groups peaks by month at first and by year once activity spans more than 12 months. Activity history starts when the directory Worker starts collecting +it. Date buckets are UTC and peak times display in the visitor's time zone. + Copy a public lobby link and choose **Find lobby from website** under **Public lobbies** in the updated launcher. The link selects a room from the current signed-in launcher list. The existing host, compatibility, mod and slot checks @@ -108,6 +119,11 @@ run**. My runs tracks the upload, independent verification and review. Only published verified PBs count on each board. The website is staged with no qualified boards or upload access by default. +The launcher and in-game overlay use the same Leaderboards page. Open it +next to Achievements on Play. Its category tabs, track cards and rankings +read the public website API. Post a run opens the signed-in website flow. +The launcher keeps the last successful catalogue in memory for the session. + Custom tracks are discovered automatically from the live catalogue, including newly published releases. A board identifies an exact release and the server checks the catalogue's verified SHA-256. Publish a new board after qualifying a diff --git a/runtime-recomp/src/game/library_ui/leaderboards_page.inl b/runtime-recomp/src/game/library_ui/leaderboards_page.inl new file mode 100644 index 00000000..ab0cdf51 --- /dev/null +++ b/runtime-recomp/src/game/library_ui/leaderboards_page.inl @@ -0,0 +1,206 @@ +constexpr const char* kLeaderboardWebsite = "https://positron-portal.com/dkr-r/#leaderboards"; +constexpr const char* kLeaderboardPost = "https://positron-portal.com/dkr-r/#post-run"; + +std::int64_t LeaderboardNumber(const dkr::store::Json& data, const char* key) { + const auto value = data.find(key); + if (value == data.end() || !value->is_number_integer()) + return 0; + return std::clamp(value->get(), std::int64_t(0), std::int64_t(216000)); +} + +std::string LeaderboardTime(std::int64_t ticks) { + const auto millis = ticks * 1000 / 60; + char clock[16]{}; + std::snprintf(clock, sizeof(clock), "%d:%02d.%03d", int(millis / 60000), int(millis / 1000 % 60), + int(millis % 1000)); + return clock; +} + +void DrawLeaderboardRanking(float width, const dkr::store::Json& board) { + const auto& event = board["board"]; + DrawOlFeature(width, StoreText(event, "title", 120).c_str(), nullptr, [&](float inner) { + PaddockGap(6.F); + OlParagraph(StoreText(event, "category", 80) + " · " + StoreText(event, "vehicle", 24), 15.F, kOlSoft, inner); + PaddockGap(12.F); + const auto& entries = board["entries"]; + if (entries.empty()) { + OlParagraph("No verified runs have been published yet.", 15.F, kOlSoft, inner); + return; + } + if (!ImGui::BeginTable("ranked-runs", 4, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH, {inner, 0.F})) + return; + ImGui::TableSetupColumn("Rank", ImGuiTableColumnFlags_WidthFixed, 70.F); + ImGui::TableSetupColumn("Racer", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_WidthFixed, 82.F); + ImGui::TableSetupColumn("Replay", ImGuiTableColumnFlags_WidthFixed, 86.F); + ImGui::TableHeadersRow(); + for (const auto& entry : entries) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(std::to_string(LeaderboardNumber(entry, "place")).c_str()); + ImGui::TableNextColumn(); + OlParagraph(StoreText(entry, "name", 60), 15.F, kOlInk, ImGui::GetContentRegionAvail().x); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(LeaderboardTime(LeaderboardNumber(entry, "ticks")).c_str()); + ImGui::TableNextColumn(); + const auto id = StoreText(entry, "id", 96); + if (!id.empty() && + id.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == + std::string::npos) { + ImGui::PushID(id.c_str()); + if (OlButton("Download", OlTone::Plain, ImGui::GetContentRegionAvail().x, nullptr, 32.F)) + SDL_OpenURL((std::string(dkr::online::Api) + "/v1/speedruns/runs/" + id + "/replay").c_str()); + ImGui::PopID(); + } + } + ImGui::EndTable(); + }); +} + +const dkr::store::Snapshot& LeaderboardLayoutFixture() { + using Json = dkr::store::Json; + static const auto fixture = [] { + dkr::store::Snapshot value; + value.speedrun_catalogue = std::make_shared(Json::parse(R"json({ + "boards": [ + {"id":"ancient-lake-car","kind":"vanilla","title":"Ancient Lake","category":"Time Trial","vehicle":"car"}, + {"id":"crescent-island-car","kind":"vanilla","title":"Crescent Island","category":"Time Trial","vehicle":"car"}, + {"id":"frosty-village-car","kind":"vanilla","title":"Frosty Village","category":"Time Trial","vehicle":"car"} + ], + "customTracks": [ + {"id":"splashdown","title":"Splashdown Pass","version":"1.0","qualified":false}, + {"id":"sherbet-land","title":"Sherbet Land","version":"1.0","qualified":false} + ], "nextCursor":"" + })json")); + value.speedrun_board = std::make_shared(Json::parse(R"json({ + "board":{"id":"ancient-lake-car","title":"Ancient Lake","category":"Time Trial","vehicle":"car"}, + "entries":[{"place":1,"name":"Example Racer","ticks":5300,"id":"fixture-one"}, + {"place":2,"name":"Deck Racer","ticks":5350,"id":"fixture-two"}] + })json")); + return value; + }(); + return fixture; +} + +void DrawLeaderboardsPage(float width, bool entered) { + static const std::vector labels{"Vanilla Tracks", "Custom Tracks", "Full Game"}; + constexpr std::array kinds{"vanilla", "custom", "full-game"}; + static int category = 0; + static std::string selected_board; + auto& service = dkr::store::service(); + const auto published = service.view(); + const auto* snapshot = published.get(); + if (g_leaderboard_layout_check) { + snapshot = &LeaderboardLayoutFixture(); + category = g_launcher_layout_step == 3 ? 1 : 0; + selected_board = g_launcher_layout_step == 2 ? "ancient-lake-car" : ""; + } else if (entered && !snapshot->speedrun_catalogue) { + service.load_leaderboards(); + } + DrawPageHeading("LEADERBOARDS"); + PaddockGap(8.F); + OlParagraph("Race for a personal best and see how other players set theirs.", 16.F, kOlSoft, width); + PaddockGap(12.F); + if (OlButton("Post a run", OlTone::Go)) + SDL_OpenURL(kLeaderboardPost); + ImGui::SameLine(); + if (OlButton("Website")) + SDL_OpenURL(kLeaderboardWebsite); + ImGui::SameLine(); + { + const OlDisabled busy(snapshot->speedrun_loading); + if (OlButton("Refresh")) + service.load_leaderboards(selected_board); + } + ImGui::SameLine(); + if (OlButton("Back to Play")) + g_page_navigation_request = kPagePlay; + PaddockGap(12.F); + const int next = StoreTabLine(labels, category, width, "speedrun-category"); + if (next != category) { + category = next; + selected_board.clear(); + } + PaddockGap(12.F); + if (!snapshot->speedrun_error.empty()) + OlParagraph(snapshot->speedrun_error, 15.F, kOlError, width); + if (!selected_board.empty()) { + if (OlButton("All tracks") || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) + selected_board.clear(); + else if (snapshot->speedrun_board && + StoreText((*snapshot->speedrun_board)["board"], "id", 96) == selected_board) { + DrawLeaderboardRanking(width, *snapshot->speedrun_board); + return; + } else { + if (snapshot->speedrun_loading) + OlParagraph("Loading times…", 15.F, kOlSoft, width); + return; + } + } + if (!snapshot->speedrun_catalogue) { + if (snapshot->speedrun_loading) + OlParagraph("Loading leaderboards…", 15.F, kOlSoft, width); + return; + } + + const auto& catalogue = *snapshot->speedrun_catalogue; + std::vector events; + for (const auto& event : catalogue["boards"]) + if (StoreText(event, "kind", 16) == kinds[category]) + events.push_back(&event); + if (events.empty()) { + DrawOlCard(width, OlPanelLook{}, [&](float inner) { + OlParagraph(category == 2 ? "Planned categories include Any%, 100% and All Trophy Races." + : "Times will appear here once the first tracks pass replay qualification.", + 15.F, kOlSoft, inner); + }); + PaddockGap(12.F); + } else { + const int columns = std::clamp(int(width / 320.F), 1, 4); + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, {5.F, 5.F}); + if (ImGui::BeginTable("leaderboard-events", columns, ImGuiTableFlags_SizingStretchSame, {width, 0.F})) { + for (const auto* event : events) { + ImGui::TableNextColumn(); + const auto id = StoreText(*event, "id", 96); + ImGui::PushID(id.c_str()); + DrawOlFeature(ImGui::GetContentRegionAvail().x, StoreText(*event, "title", 120).c_str(), nullptr, + [&](float inner) { + PaddockGap(6.F); + OlParagraph(StoreText(*event, "category", 80) + " · " + + StoreText(*event, "vehicle", 24), + 15.F, kOlSoft, inner); + PaddockGap(8.F); + const OlDisabled busy(snapshot->speedrun_loading); + if (OlButton("View times")) { + service.load_leaderboards(id); + selected_board = id; + } + }); + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::PopStyleVar(); + PaddockGap(12.F); + } + if (category != 1) + return; + + DrawOlFeature(width, "Tracks in the Mod Library", nullptr, [&](float inner) { + for (const auto& track : catalogue["customTracks"]) { + PaddockGap(8.F); + OlParagraph(StoreText(track, "title", 120), 16.F, kOlInk, inner, true); + const bool qualified = track.contains("qualified") && track["qualified"] == true; + OlParagraph(StoreText(track, "version", 80) + (qualified ? " · Ranked" : " · Awaiting qualification"), 14.F, + kOlSoft, inner); + } + if (catalogue["customTracks"].empty()) + OlParagraph("No custom tracks are listed yet.", 15.F, kOlSoft, inner); + if (const auto cursor = StoreText(catalogue, "nextCursor", 96); !cursor.empty()) { + PaddockGap(8.F); + const OlDisabled busy(snapshot->speedrun_loading); + if (OlButton("More tracks")) + service.load_leaderboards({}, cursor); + } + }); +} diff --git a/runtime-recomp/src/game/library_ui/navigation_check.inl b/runtime-recomp/src/game/library_ui/navigation_check.inl index be1b59fe..80f59341 100644 --- a/runtime-recomp/src/game/library_ui/navigation_check.inl +++ b/runtime-recomp/src/game/library_ui/navigation_check.inl @@ -9,6 +9,7 @@ std::filesystem::path g_launcher_layout_root; int g_launcher_layout_step = 0; bool g_launcher_layout_sized = false; bool g_localisation_cycle_check = false; +bool g_leaderboard_layout_check = false; double g_launcher_layout_at = 0; constexpr std::array kLauncherLayoutPages{0, 6, 6, 6, 6, 6, 10, 1, 2, 3, 4, 5, 8, 9, 7, 10, 10, 10, 10, 10, 10, 10, 10, 3, 3, 3, 3, 6, 6, 6, @@ -23,6 +24,10 @@ void PlayLaunchCaptureCheck(); void SaveDraftCaptureCheck(); void LibrarySelectCheckView(int step, int& page) { + if (g_leaderboard_layout_check) { + page = step == 0 ? kPagePlay : dkr::library_ui::LeaderboardsPage; + return; + } if (SaveDraftLayoutCheck()) { page = kPageSaveManager; g_saves_page.scope = 0; @@ -134,8 +139,11 @@ void LauncherLayoutCheckCapture(SDL_Renderer* renderer) { SDL_FreeSurface(surface); if (!saved) return; + const int page = g_leaderboard_layout_check && g_launcher_layout_step > 0 + ? dkr::library_ui::LeaderboardsPage + : kLauncherLayoutPages[std::size_t(g_launcher_layout_step)]; std::fprintf(stderr, "[launcher-layout][isolated-check] step=%d page=%d width=%d height=%d captured\n", - g_launcher_layout_step, kLauncherLayoutPages[std::size_t(g_launcher_layout_step)], width, height); + g_launcher_layout_step, page, width, height); std::fprintf(stderr, "[localisation][isolated-check] step=%d language=%s atlas=%dx%d texture=%p\n", g_launcher_layout_step, dkr::localisation::active().data(), ImGui::GetIO().Fonts->TexWidth, ImGui::GetIO().Fonts->TexHeight, ImGui::GetIO().Fonts->TexID); @@ -147,7 +155,8 @@ void LauncherLayoutCheckCapture(SDL_Renderer* renderer) { PlayLaunchCaptureCheck(); ++g_launcher_layout_step; g_launcher_layout_at = PaddockClock(); - if (PlayLaunchLayoutCheck() && g_launcher_layout_step == 6) { + if ((PlayLaunchLayoutCheck() && g_launcher_layout_step == 6) || + (g_leaderboard_layout_check && g_launcher_layout_step == 4)) { SDL_Event quit{}; quit.type = SDL_QUIT; SDL_PushEvent(&quit); @@ -221,6 +230,8 @@ void LibraryNavigationCheckLauncherInit(const std::filesystem::path& root) { std::string_view(layout) == "wide" || std::string_view(layout) == "small" || std::string_view(layout) == "short")) g_launcher_layout_root = root; + const char* racing = std::getenv("DKR_OWNED_CHECK_LEADERBOARD_LAYOUT"); + g_leaderboard_layout_check = !g_launcher_layout_root.empty() && racing && std::string_view(racing) == "1"; const char* controls = std::getenv("DKR_LIBRARY_CONTROLS_CHECK"); g_library_controls_check = !g_launcher_layout_root.empty() && controls && std::string_view(controls) == "1"; } diff --git a/runtime-recomp/src/game/library_ui/play_tools.inl b/runtime-recomp/src/game/library_ui/play_tools.inl index dc91e19b..c893f0ef 100644 --- a/runtime-recomp/src/game/library_ui/play_tools.inl +++ b/runtime-recomp/src/game/library_ui/play_tools.inl @@ -1,38 +1,43 @@ const char* SessionModsCaption(bool enabled) { return enabled ? "Session mods: ON" : "Session mods: OFF"; } -float SessionModsWidth() { - return std::max(PaddockImportButtonWidth(SessionModsCaption(true)), - PaddockImportButtonWidth(SessionModsCaption(false))); -} -float PlayToolsHeight(float width) { - return PaddockImportButtonWidth("Achievements") + SessionModsWidth() + PaddockImportButtonWidth("Save Manager") + - 32.F <= - width - ? 56.F - : 192.F; -} +constexpr float kPlayToolHeight = 40.F, kPlayToolGap = 8.F; void DrawPlayTools(float width) { - const float achievements = PaddockImportButtonWidth("Achievements"); - const float saves = PaddockImportButtonWidth("Save Manager"); - const bool row = PlayToolsHeight(width) == 56.F; + const std::array widths{PaddockImportButtonWidth("Achievements", true), + PaddockImportButtonWidth("Leaderboards", true), + std::max(PaddockImportButtonWidth(SessionModsCaption(true), true), + PaddockImportButtonWidth(SessionModsCaption(false), true)), + PaddockImportButtonWidth("Save Manager", true)}; + const float widest = *std::max_element(widths.begin(), widths.end()); + const float full = widths[0] + widths[1] + widths[2] + widths[3] + 3.F * kPlayToolGap; + const int columns = width >= full ? 4 : width >= 2.F * widest + kPlayToolGap ? 2 : 1; + const int rows = 4 / columns; + const float fallback_width = std::min(widest, width); + const float row_width = columns == 4 ? full : float(columns) * fallback_width + float(columns - 1) * kPlayToolGap; const auto at = ImGui::GetCursorScreenPos(); - if (PaddockImportButton("Achievements###play-achievements", row ? achievements : width, false, false, 1)) + const float left = at.x + (width - row_width) * .5F; + float next = left; + const auto draw = [&](int i, const char* label, int icon) { + const float button_width = columns == 4 ? widths[std::size_t(i)] : fallback_width; + const float x = columns == 4 ? next : left + float(i % columns) * (fallback_width + kPlayToolGap); + next += button_width + kPlayToolGap; + ImGui::SetCursorScreenPos({x, at.y + float(i / columns) * (kPlayToolHeight + kPlayToolGap)}); + return PaddockImportButton(label, button_width, false, false, icon, true); + }; + if (draw(0, "Achievements###play-achievements", 1)) g_page_navigation_request = kPageAchievements; - ImGui::SetCursorScreenPos( - row ? ImVec2{at.x + achievements + (width - achievements - saves - SessionModsWidth()) * .5F, at.y} - : ImVec2{at.x, at.y + 68.F}); + if (draw(1, "Leaderboards###play-leaderboards", 4)) + g_page_navigation_request = dkr::library_ui::LeaderboardsPage; const bool enabled = dkr::session_content::next_enabled.load(); const auto caption = std::string(SessionModsCaption(enabled)) + "###play-session-mods"; - if (PaddockImportButton(caption.c_str(), row ? SessionModsWidth() : width, false, false, 3)) { + if (draw(2, caption.c_str(), 3)) { dkr::session_content::next_enabled = !enabled; SaveSettings(); } - ImGui::SetCursorScreenPos(row ? ImVec2{at.x + width - saves, at.y} : ImVec2{at.x, at.y + 136.F}); - if (PaddockImportButton("Save Manager###play-saves", row ? saves : width, false, false, 2)) + if (draw(3, "Save Manager###play-saves", 2)) g_page_navigation_request = kPageSaveManager; ImGui::SetCursorScreenPos(at); - ImGui::Dummy({width, PlayToolsHeight(width)}); + ImGui::Dummy({width, float(rows) * kPlayToolHeight + float(rows - 1) * kPlayToolGap}); } void DrawPlayToolBack(float) { if (PaddockTextLink("Back to Play")) diff --git a/runtime-recomp/src/game/library_ui/policy.hpp b/runtime-recomp/src/game/library_ui/policy.hpp index faafe439..46d652cc 100644 --- a/runtime-recomp/src/game/library_ui/policy.hpp +++ b/runtime-recomp/src/game/library_ui/policy.hpp @@ -9,10 +9,10 @@ namespace dkr::library_ui { // Existing page identities stay stable. Only visual order changes. -inline constexpr int LibraryPage = 10, PageCount = 11; +inline constexpr int LibraryPage = 10, PageCount = 11, LeaderboardsPage = 14; inline constexpr std::array SidebarOrder{0, 5, LibraryPage, 6, 1, 2, 3, 7, 13, 11, 12}; inline constexpr int sidebar_parent(int page) { - return page == 4 || page == 9 ? 0 : page; + return page == 4 || page == 9 || page == LeaderboardsPage ? 0 : page; } inline constexpr int TexturesSection = 4; // Preserve existing section identities used by links and import callbacks. diff --git a/runtime-recomp/src/game/library_ui/shared_page_ui.inl b/runtime-recomp/src/game/library_ui/shared_page_ui.inl index 56e62261..9761da71 100644 --- a/runtime-recomp/src/game/library_ui/shared_page_ui.inl +++ b/runtime-recomp/src/game/library_ui/shared_page_ui.inl @@ -1,3 +1,4 @@ +#include "leaderboards_page.inl" // One page router owns both surfaces. Live capability checks stay in each // service; presentation does not grant save/import/update permissions. struct SharedPlaySnapshot { @@ -18,12 +19,14 @@ bool LibraryContentInputCaptured() { void DrawSharedUiPage(float width, int page, bool live, const PlayPageContext* launcher = nullptr) { LibraryNavigationContentWindow(); const float top = ImGui::GetCursorPosY(); + static std::array previous_page{-1, -1}; // Paired SDL readbacks use the real live page branch inside the existing // authenticated, disposable layout harness. Normal startup cannot arm it. if (!live && !g_launcher_layout_root.empty()) { const char* surface = std::getenv("DKR_OWNED_CHECK_LAYOUT_SURFACE"); live = surface && std::string_view(surface) == "overlay"; } + const bool entered = std::exchange(previous_page[live ? 1 : 0], page) != page; g_store_in_game = live; if (DrawLibraryControlsFieldCheck(width)) { LibrarySurfaceProbe(live, page, width, ImGui::GetCursorPosY() - top); @@ -62,6 +65,8 @@ void DrawSharedUiPage(float width, int page, bool live, const PlayPageContext* l } else if (page == kPageAchievements) { DrawPlayToolBack(width); DrawAchievementsPage(width); + } else if (page == dkr::library_ui::LeaderboardsPage) { + DrawLeaderboardsPage(width, entered); } else if (page == kPageOnlineMp) DrawOnlinePage(width, !live, live || play->rom_ready); else if (page == kPageModLibrary) diff --git a/runtime-recomp/src/game/mod_library/website/assets/app.js b/runtime-recomp/src/game/mod_library/website/assets/app.js index 6a3ee404..82c8f315 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/app.js +++ b/runtime-recomp/src/game/mod_library/website/assets/app.js @@ -1018,7 +1018,7 @@ } catch(error){bootError=errorMessage(error);} finally {started=true;bootLoading=false;render();} } - const publicPage = {'#online':'online','#leaderboards':'speedruns'}[location.hash]; + const publicPage = {'#online':'online','#leaderboards':'speedruns','#post-run':'post-run'}[location.hash]; if(publicPage||/^#lobby=[a-f0-9]{32}$/.test(location.hash))s.view=publicPage||'online'; initialise(); }()); diff --git a/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js b/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js index 3930e395..10309bc7 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js +++ b/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js @@ -1,6 +1,7 @@ (function () { 'use strict'; const replayModule = new URL('replay-format.js?v=1', document.currentScript?.src || new URL('assets/racing-ui.js', document.baseURI).href); + const activityPeriods = [['7','7 days'],['30','30 days'],['all','All time']]; const sections = [['vanilla','Vanilla Tracks'],['custom','Custom Tracks'],['full-game','Full Game']]; const phases = {waiting:'In lobby',testing:'Testing connection',starting:'Starting',loading:'Loading',racing:'Racing',returning:'Returning to lobby'}; const states = {uploading:'Upload incomplete',queued:'Waiting for verification',verified:'Waiting for moderator review',published:'Published',rejected:'Rejected'}; @@ -13,6 +14,7 @@ window.DKRRacingUI = {create({ root, config, Auth, view, user, isStaff, esc, icon, button, pagehead, requireSignedIn, go, renderIcons }) { const linkedRoom = /^#lobby=([a-f0-9]{32})$/.exec(location.hash)?.[1]; + let activityPeriod = 'all'; let online, directoryError, directoryBusy = false, directoryTimer; let catalogue, board, selectedBoard = '', section = 'vanilla', listingTab = 'boards'; let privateRows = []; @@ -58,19 +60,74 @@ return pagehead('DKR-R Online', 'See who’s online and find a public lobby.') + '
' + onlineContent() + '
'; } + const players = value => Number.isSafeInteger(value) && value >= 0 ? value.toLocaleString() : '—'; + function activityTime(value) { + return Number.isSafeInteger(value) && value > 0 ? new Intl.DateTimeFormat(undefined, { + weekday:'short', month:'short', day:'numeric', hour:'numeric', minute:'2-digit', timeZoneName:'short' + }).format(value) : ''; + } + function stat(label, count, detail = '') { + return '
' + label + '
' + players(count) + + '
' + (detail ? '
' + esc(detail) + '
' : '') + '
'; + } + function activityHistory(history, interval) { + if (!Array.isArray(history) || !history.length) return ''; + const valid = history.filter(point => Number.isSafeInteger(point.startsAt) && + Number.isSafeInteger(point.players) && point.players >= 0); + if (!valid.length) return ''; + const maximum = Math.max(1, ...valid.map(point => point.players)); + const date = new Intl.DateTimeFormat(undefined, interval === 'year' ? {year:'numeric',timeZone:'UTC'} : + interval === 'month' ? {month:'short',year:'numeric',timeZone:'UTC'} : {month:'short',day:'numeric',timeZone:'UTC'}); + const label = interval === 'year' ? 'Yearly peaks' : + interval === 'month' ? 'Monthly peaks' : 'Daily peaks · days with recorded activity (UTC)'; + return '

' + label + '

' + + '
    ' + valid.map(point => { + const tip = date.format(point.startsAt) + ' · ' + players(point.players) + ' online'; + return '
  1. '; + }).join('') + '

' + + esc(date.format(valid[0].startsAt)) + '' + + (valid.length > 1 ? '' + esc(date.format(valid.at(-1).startsAt)) + '' : '') + '

'; + } + function onlineStats(live) { + const stats = online?.stats; + const period = stats?.periods?.[activityPeriod]; + const lifetime = activityPeriod === 'all'; + const peakTime = activityTime(stats?.peak?.observedAt); + const busiest = period?.busiestHour; + const busiestTime = activityTime(busiest?.startsAt); + return '
' + stat('Public lobbies',live ? stats?.publicLobbies : undefined) + + stat('Racers in public lobbies',live ? stats?.publicRacers : undefined) + + stat('Spectators in public lobbies',live ? stats?.publicSpectators : undefined) + '
' + + '

Player activity

' + + '
' + + activityPeriods.map(([id,label]) => '').join('') + '
' + + '
' + + stat(lifetime ? 'All-time concurrent peak' : 'Peak concurrent players', period?.peak, + lifetime ? peakTime : '') + + stat('Days with activity',period?.activeDays) + + (lifetime ? '
Activity recorded since
' + + esc(stats?.trackedSince ? new Intl.DateTimeFormat(undefined,{dateStyle:'medium'}).format(stats.trackedSince) : 'Collecting activity') + '
' : + '
Busiest hour
' + esc(busiestTime || 'Collecting activity') + '
' + + (busiestTime ? '
' + players(busiest.players) + ' at peak
' : '') + '
' + + stat('New sign-ups',online?.newSignups?.[activityPeriod])) + '
' + activityHistory(period?.history,lifetime ? period?.interval || 'month' : 'day'); + } function onlineContent() { const age = online && Date.now() - online.serverTime; const live = online && age < 90000 && !directoryError; - const count = live ? online.online : '—'; + const count = players(live ? online.online : undefined); + const registered = players(online?.totalSignedUp); const status = directoryError === 'disabled' ? 'The public lobby browser is currently disabled.' : online && !live ? 'Last known rooms. Open DKR-R Online to check availability.' : directoryError ? 'The lobby list could not be loaded.' : online ? 'Updates every 30 seconds.' : 'Loading the public lobby list…'; const rooms = online ? [...online.rooms] : []; if (linkedRoom) rooms.sort((a, b) => Number(b.id === linkedRoom) - Number(a.id === linkedRoom)); - return '
' + count + - ' players online

' + esc(status) + '

' + - button('online-refresh',icon('refresh-cw') + 'Refresh','quiet small') + '
' + + return '
' + + count + ' / ' + registered + '

Total online / Total signed up

' + + '

' + esc(status) + '

' + + button('online-refresh',icon('refresh-cw') + 'Refresh','quiet small') + '
' + onlineStats(live) + '
' + '

Copy a link and use Find lobby from website in the launcher’s Public lobbies panel. The host approves requests to race or spectate.

' + (onlineNotice ? '

' + esc(onlineNotice) + '

' : '') + (rooms.length ? '
' + rooms.map(room => @@ -96,7 +153,7 @@ if (more && online) { const rooms = new Map(online.rooms.map(room => [room.id, room])); data.rooms.forEach(room => rooms.set(room.id, room)); - online = {...data, rooms:[...rooms.values()]}; + online = {...online, ...data, rooms:[...rooms.values()]}; } else online = data; directoryError = ''; } catch (error) { @@ -257,6 +314,13 @@ async function action(action, id, target) { if (action === 'online' || action === 'speedruns' || action === 'post-run') { await go(action); return true; } + if (action === 'online-period') { + if (activityPeriods.some(([value]) => value === id)) { + activityPeriod = id; + refreshRegion('[data-online-region]',onlineContent); + } + return true; + } if (action === 'online-refresh' || action === 'online-more') { await loadOnline({ fresh:action === 'online-refresh', more:action === 'online-more' }); return true; } diff --git a/runtime-recomp/src/game/mod_library/website/assets/racing.css b/runtime-recomp/src/game/mod_library/website/assets/racing.css index 44fcc94c..73d05553 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/racing.css +++ b/runtime-recomp/src/game/mod_library/website/assets/racing.css @@ -15,3 +15,45 @@ } #dkr-mod-library .dkr-run-table th:last-child, #dkr-mod-library .dkr-run-table td:last-child { text-align: right; } #dkr-mod-library .dkr-racing-file { width: 100%; max-width: 100%; } +#dkr-mod-library .dkr-online-stats { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 7.5rem), 1fr)); + gap: .9rem 1.25rem; + border-top: 1px solid #31515d; + margin: 0; + padding-top: .9rem; +} +#dkr-mod-library .dkr-online-stats dt { color: #abc4cd; font-size: .8rem; } +#dkr-mod-library .dkr-online-stats dd { margin: .25rem 0 0; } +#dkr-mod-library .dkr-online-stats dd:not(.dkr-small) { font-size: 1.25rem; font-weight: 700; } +#dkr-mod-library .dkr-online-history-stats { border: 0; padding: 0; } +#dkr-mod-library .dkr-online-periods { border-top: 1px solid #31515d; padding-top: .9rem; } +#dkr-mod-library .dkr-online-periods button[aria-pressed="true"] { + background: #b53722; + border-color: #ffc15a; + color: #fff1c1; +} +#dkr-mod-library .dkr-online-history { + background: #091d2a; + border: 1px solid #31515d; + border-radius: 8px; + padding: .65rem .8rem; +} +#dkr-mod-library .dkr-online-bars { + list-style: none; + display: flex; + align-items: end; + justify-content: space-between; + gap: clamp(2px, 1vw, 8px); + height: 3.25rem; + padding: 0; + margin: .55rem 0 .35rem; + border-bottom: 1px solid #31515d; +} +#dkr-mod-library .dkr-online-bars li { + flex: 1; + max-width: 3rem; + height: max(2px, var(--peak)); + background: #1abfa9; + border-radius: 3px 3px 0 0; +} diff --git a/runtime-recomp/src/game/mod_library/website/index.html b/runtime-recomp/src/game/mod_library/website/index.html index 6c9dc258..eb3867a7 100644 --- a/runtime-recomp/src/game/mod_library/website/index.html +++ b/runtime-recomp/src/game/mod_library/website/index.html @@ -22,9 +22,9 @@ - - - + + +
diff --git a/runtime-recomp/src/game/mod_library/website/privacy.html b/runtime-recomp/src/game/mod_library/website/privacy.html index 7bd47bbe..392fee53 100644 --- a/runtime-recomp/src/game/mod_library/website/privacy.html +++ b/runtime-recomp/src/game/mod_library/website/privacy.html @@ -14,7 +14,7 @@

What we keep

Download countersDisplay tracked website download requests for each mod.Visitors see aggregate totals. Temporary retry and rate-limit records stay in the private service. Ratings, reviews and datesHelp players choose mods and keep one rating per account for each mod.Visitors when the review is visible. Hidden reviews remain available to their author and staff. Mod requests and repliesCheck a suggested mod and tell you the outcome.The requester and staff. Private staff notes are visible only to staff. -Online player count and public lobby detailsShow how many signed-in players are connected and which lobbies are open to the public.Visitors see the total, public lobby title and available places. Private lobbies and join credentials stay in the launcher. +Online player count and public lobby detailsShow how many signed-in players are connected, the number of active accounts, peak activity, and which lobbies are open to the public.Visitors see aggregate counts and peak times, plus public lobby titles and available places. Private lobbies and join credentials stay in the launcher. Speedrun replays, game inputs and run detailsCheck the time, ruleset, ROM revision, track version, platform and recorded inputs before a run is published.You and authorised reviewers see pending runs. Visitors can download published replays and see the display name on the leaderboard. Temporary sign-in records, session hashes and optional remembered-device hashesComplete sign-in and protect account actions.The private account service. Staff upload records, filenames, file sizes, transfer checksums and statusResume interrupted transfers and connect completed files to the library.The private library service and authorised staff. Completed mod packages and cover images are served publicly by the web host. diff --git a/runtime-recomp/src/game/mod_store.cpp b/runtime-recomp/src/game/mod_store.cpp index 1aa26638..bfacc562 100644 --- a/runtime-recomp/src/game/mod_store.cpp +++ b/runtime-recomp/src/game/mod_store.cpp @@ -1389,6 +1389,59 @@ void Service::refresh() { auto& p = *impl_; p.queue([&p](std::stop_token stop) { p.refresh(stop); }); } +void Service::load_leaderboards(std::string board, std::string cursor) { + if ((!board.empty() && !identifier(board)) || (!cursor.empty() && !identifier(cursor))) + return; + auto& p = *impl_; + { + std::lock_guard lock(p.mutex); + if (!p.configured || p.state.speedrun_loading) + return; + p.state.speedrun_loading = true; + p.state.speedrun_request = board; + p.state.speedrun_error.clear(); + p.publish(); + } + if (!p.queue([&p, board = std::move(board), cursor = std::move(cursor)](std::stop_token stop) { + try { + const auto url = board.empty() + ? "/v1/speedruns" + (cursor.empty() ? std::string{} : "?cursor=" + cursor) + : "/v1/speedruns/boards/" + board; + auto data = p.get(url, stop); + if (board.empty() && (!data.contains("boards") || !data["boards"].is_array() || + !data.contains("customTracks") || !data["customTracks"].is_array())) + throw Error("The leaderboard service returned an invalid track list."); + if (!board.empty() && (!data.contains("board") || !data["board"].is_object() || + !data.contains("entries") || !data["entries"].is_array())) + throw Error("The leaderboard service returned an invalid result list."); + p.update([&](Snapshot& state) { + state.speedrun_loading = false; + if (!board.empty()) { + state.speedrun_board = std::make_shared(std::move(data)); + return; + } + if (!cursor.empty() && state.speedrun_catalogue) { + Json combined = *state.speedrun_catalogue; + for (auto& track : data["customTracks"]) + combined["customTracks"].push_back(std::move(track)); + combined["nextCursor"] = data["nextCursor"]; + data = std::move(combined); + } + state.speedrun_catalogue = std::make_shared(std::move(data)); + }); + } catch (const std::exception&) { + p.update([](Snapshot& state) { + state.speedrun_loading = false; + state.speedrun_error = "Leaderboards are unavailable. Try refreshing."; + }); + } + })) { + p.update([](Snapshot& state) { + state.speedrun_loading = false; + state.speedrun_error = "Wait for the current library request to finish."; + }); + } +} bool Service::refresh_names() { auto& p = *impl_; { diff --git a/runtime-recomp/src/game/mod_store.hpp b/runtime-recomp/src/game/mod_store.hpp index 6505b138..5b3c873f 100644 --- a/runtime-recomp/src/game/mod_store.hpp +++ b/runtime-recomp/src/game/mod_store.hpp @@ -22,6 +22,9 @@ struct Image { }; struct Snapshot { std::shared_ptr items = std::make_shared(Json::array()); + std::shared_ptr speedrun_catalogue, speedrun_board; + std::string speedrun_request, speedrun_error; + bool speedrun_loading = false; Json user = nullptr, personal = Json::object(), staff = Json::object(), admin = Json::object(); Json reviews = Json::object(), uploads = Json::array(), assets = Json::array(), upload = Json::object(); std::vector downloads; @@ -42,6 +45,7 @@ class Service { void configure(const std::filesystem::path&, std::string version); std::shared_ptr view() const; void refresh(); + void load_leaderboards(std::string board = {}, std::string cursor = {}); void gameplay(bool active); bool refresh_names(); void layout(int); diff --git a/runtime-recomp/src/game/runtime_mod_library_ui.inl b/runtime-recomp/src/game/runtime_mod_library_ui.inl index 4a0af17c..d54348f9 100644 --- a/runtime-recomp/src/game/runtime_mod_library_ui.inl +++ b/runtime-recomp/src/game/runtime_mod_library_ui.inl @@ -1192,23 +1192,24 @@ void DrawDkrTrackDetails(const std::vector& tracks, bool rom_re // ------------------------------------------------------------ page controls -float PaddockImportButtonWidth(const char* label) { +float PaddockImportButtonWidth(const char* label, bool compact = false) { const auto caption = dkr::localisation::label(label); label = caption.c_str(); - const PaddockType type = PaddockSign(22.0F, 1.1F); - return std::ceil(2.0F + 12.0F + 30.0F + 12.0F + PaddockMeasure(type, label, PaddockLabelEnd(label)) + 20.0F + 2.0F); + const PaddockType type = compact ? PaddockSign(16.F, .8F) : PaddockSign(22.F, 1.1F); + return std::ceil((compact ? 50.F : 78.F) + PaddockMeasure(type, label, PaddockLabelEnd(label))); } // The painted "+ Import mods" sign (.mods-import-button). bool PaddockImportButton(const char* label, float forced_width = 0.0F, bool update_icon = false, - bool website_icon = false, int tool_icon = 0) { + bool website_icon = false, int tool_icon = 0, bool compact = false) { const auto caption = dkr::localisation::label(label); label = caption.c_str(); - const PaddockType type = PaddockSign(22.0F, 1.1F); + const PaddockType type = compact ? PaddockSign(16.F, .8F) : PaddockSign(22.F, 1.1F); const char* end = PaddockLabelEnd(label); - const float natural = PaddockImportButtonWidth(label); + const float natural = PaddockImportButtonWidth(label, compact); const float width = forced_width > 0.0F ? forced_width : natural; - const PaddockPress press = PaddockBeginPress(label, {width, 56.0F}); + const float height = compact ? 40.F : 56.F; + const PaddockPress press = PaddockBeginPress(label, {width, height}); ImDrawList* draw = ImGui::GetWindowDrawList(); PaddockPanelStyle panel; panel.radii = {8.0F, 18.0F, 8.0F, 8.0F}; @@ -1219,50 +1220,62 @@ bool PaddockImportButton(const char* label, float forced_width = 0.0F, bool upda panel.drop_offset = 4.0F; panel.highlight = PaddockRgb(0xFFFFFF, 38U); panel.highlight_width = 2.0F; + if (compact) { + panel.radii = {6.F, 12.F, 6.F, 6.F}; + panel.drop_offset = 3.F; + } PaddockPanel(draw, press.min, press.max, panel); - const float left = press.min.x + (width - natural) * 0.5F + 14.0F; - const ImVec2 symbol{left, press.min.y + 13.0F}; - PaddockFill(draw, symbol, {symbol.x + 30.0F, symbol.y + 30.0F}, PaddockRound(5.0F), PaddockCol(0x6F2B11)); + draw->PushClipRect(press.min, press.max, true); + const float icon_size = compact ? 21.F : 30.F; + const float left = press.min.x + (width - natural) * .5F + (compact ? 10.F : 14.F); + const ImVec2 symbol{left, press.min.y + (height - icon_size) * .5F}; + PaddockFill(draw, symbol, {symbol.x + icon_size, symbol.y + icon_size}, PaddockRound(5.F), PaddockCol(0x6F2B11)); + const auto icon = [&](float x, float y) -> ImVec2 { + const float scale = icon_size / 30.F; + return {symbol.x + x * scale, symbol.y + y * scale}; + }; // Two centred strokes, which a font glyph's baseline would not give // (.import-button-symbol). const ImU32 ink = PaddockCol(0xFFF3C9); if (website_icon) { - draw->AddRect({symbol.x + 7.F, symbol.y + 11.F}, {symbol.x + 19.F, symbol.y + 23.F}, ink, 2.F, 0, 2.F); - draw->AddLine({symbol.x + 13.F, symbol.y + 17.F}, {symbol.x + 23.F, symbol.y + 7.F}, ink, 2.F); - draw->AddLine({symbol.x + 16.F, symbol.y + 7.F}, {symbol.x + 23.F, symbol.y + 7.F}, ink, 2.F); - draw->AddLine({symbol.x + 23.F, symbol.y + 7.F}, {symbol.x + 23.F, symbol.y + 14.F}, ink, 2.F); + draw->AddRect(icon(7.F, 11.F), icon(19.F, 23.F), ink, 2.F, 0, 2.F); + draw->AddLine(icon(13.F, 17.F), icon(23.F, 7.F), ink, 2.F); + draw->AddLine(icon(16.F, 7.F), icon(23.F, 7.F), ink, 2.F); + draw->AddLine(icon(23.F, 7.F), icon(23.F, 14.F), ink, 2.F); } else if (tool_icon == 1) { - draw->AddLine({symbol.x + 9.F, symbol.y + 7.F}, {symbol.x + 21.F, symbol.y + 7.F}, ink, 2.F); - draw->PathArcTo({symbol.x + 15.F, symbol.y + 12.F}, 6.F, 0.F, 3.141593F, 16); + draw->AddLine(icon(9.F, 7.F), icon(21.F, 7.F), ink, 2.F); + draw->PathArcTo(icon(15.F, 12.F), icon_size * .2F, 0.F, 3.141593F, 16); draw->PathStroke(ink, 0, 2.F); - draw->AddLine({symbol.x + 9.F, symbol.y + 7.F}, {symbol.x + 9.F, symbol.y + 12.F}, ink, 2.F); - draw->AddLine({symbol.x + 21.F, symbol.y + 7.F}, {symbol.x + 21.F, symbol.y + 12.F}, ink, 2.F); - draw->AddLine({symbol.x + 15.F, symbol.y + 18.F}, {symbol.x + 15.F, symbol.y + 23.F}, ink, 2.F); - draw->AddLine({symbol.x + 10.F, symbol.y + 23.F}, {symbol.x + 20.F, symbol.y + 23.F}, ink, 2.F); + draw->AddLine(icon(9.F, 7.F), icon(9.F, 12.F), ink, 2.F); + draw->AddLine(icon(21.F, 7.F), icon(21.F, 12.F), ink, 2.F); + draw->AddLine(icon(15.F, 18.F), icon(15.F, 23.F), ink, 2.F); + draw->AddLine(icon(10.F, 23.F), icon(20.F, 23.F), ink, 2.F); } else if (tool_icon == 3) { const bool on = dkr::session_content::next_enabled.load(); - draw->AddRectFilled({symbol.x + 3.F, symbol.y + 9.F}, {symbol.x + 27.F, symbol.y + 21.F}, - PaddockCol(on ? 0x13B99B : 0x32576A), 6.F); - draw->AddCircleFilled({symbol.x + (on ? 21.F : 9.F), symbol.y + 15.F}, 4.F, ink, 16); + draw->AddRectFilled(icon(3.F, 9.F), icon(27.F, 21.F), PaddockCol(on ? 0x13B99B : 0x32576A), 6.F); + draw->AddCircleFilled(icon(on ? 21.F : 9.F, 15.F), icon_size * (4.F / 30.F), ink, 16); } else if (tool_icon == 2) { - draw->AddRect({symbol.x + 7.F, symbol.y + 7.F}, {symbol.x + 23.F, symbol.y + 23.F}, ink, 2.F, 0, 2.F); - draw->AddRect({symbol.x + 11.F, symbol.y + 7.F}, {symbol.x + 19.F, symbol.y + 13.F}, ink, 0.F, 0, 2.F); - draw->AddRect({symbol.x + 11.F, symbol.y + 17.F}, {symbol.x + 19.F, symbol.y + 23.F}, ink, 0.F, 0, 2.F); + draw->AddRect(icon(7.F, 7.F), icon(23.F, 23.F), ink, 2.F, 0, 2.F); + draw->AddRect(icon(11.F, 7.F), icon(19.F, 13.F), ink, 0.F, 0, 2.F); + draw->AddRect(icon(11.F, 17.F), icon(19.F, 23.F), ink, 0.F, 0, 2.F); + } else if (tool_icon == 4) { + draw->AddRectFilled(icon(6.F, 17.F), icon(11.F, 23.F), ink, 1.F); + draw->AddRectFilled(icon(12.5F, 8.F), icon(17.5F, 23.F), ink, 1.F); + draw->AddRectFilled(icon(19.F, 13.F), icon(24.F, 23.F), ink, 1.F); } else if (update_icon) { - draw->PathArcTo({symbol.x + 15.0F, symbol.y + 15.0F}, 8.0F, -1.4F, 3.8F, 20); + draw->PathArcTo(icon(15.0F, 15.0F), 8.0F, -1.4F, 3.8F, 20); draw->PathStroke(ink, 0, 2.0F); - draw->AddTriangleFilled({symbol.x + 13.0F, symbol.y + 4.0F}, {symbol.x + 22.0F, symbol.y + 8.0F}, - {symbol.x + 14.0F, symbol.y + 12.0F}, ink); + draw->AddTriangleFilled(icon(13.0F, 4.0F), icon(22.0F, 8.0F), icon(14.0F, 12.0F), ink); } else { - PaddockFill(draw, {symbol.x + 8.0F, symbol.y + 14.0F}, {symbol.x + 22.0F, symbol.y + 16.0F}, PaddockRound(1.0F), - ink); - PaddockFill(draw, {symbol.x + 14.0F, symbol.y + 8.0F}, {symbol.x + 16.0F, symbol.y + 22.0F}, PaddockRound(1.0F), - ink); + PaddockFill(draw, icon(8.0F, 14.0F), icon(22.0F, 16.0F), PaddockRound(1.0F), ink); + PaddockFill(draw, icon(14.0F, 8.0F), icon(16.0F, 22.0F), PaddockRound(1.0F), ink); } - const float text_top = press.min.y + (56.0F - type.line) * 0.5F; - PaddockDrawRun(draw, type, {symbol.x + 42.0F, text_top + 2.0F}, PaddockCol(0x632706), label, end); - PaddockDrawRun(draw, type, {symbol.x + 42.0F, text_top}, PaddockCol(0xFFF3C9), label, end); - PaddockEndPress(press, 18.0F); + const float text_top = press.min.y + (height - type.line) * .5F; + const float text_x = symbol.x + icon_size + (compact ? 8.F : 12.F); + PaddockDrawRun(draw, type, {text_x, text_top + 2.0F}, PaddockCol(0x632706), label, end); + PaddockDrawRun(draw, type, {text_x, text_top}, PaddockCol(0xFFF3C9), label, end); + draw->PopClipRect(); + PaddockEndPress(press, compact ? 12.F : 18.F); return press.pressed; } diff --git a/runtime-recomp/src/game/runtime_play_ui.inl b/runtime-recomp/src/game/runtime_play_ui.inl index fff7fec7..14212e59 100644 --- a/runtime-recomp/src/game/runtime_play_ui.inl +++ b/runtime-recomp/src/game/runtime_play_ui.inl @@ -517,6 +517,8 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live ImGui::PopStyleVar(); LibraryNavigationScrollWindow(ImGui::GetCurrentWindow()); width = std::max(1.F, std::min(available_width, ImGui::GetContentRegionAvail().x - 8.F)); + DrawPlayTools(width); + PaddockGap(14.F); DrawLauncherFeatured(width, live); // The ROM pass: status, the ROM list, and the actions for it. @@ -665,19 +667,13 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live ImGui::EndDisabled(); ImGui::PopStyleColor(); const float options_x = side ? at.x + width - options_width - 26.F : at.x + 26.F; - const float tools_width = side ? options_x - at.x - 58.F : width - 52.F; - const float tools_height = PlayToolsHeight(tools_width); - const float left_height = height + tools_height + 16.F; - const float options_y = side ? at.y + 26.F : at.y + left_height + 8.F; + const float options_y = side ? at.y + 26.F : at.y + height + 8.F; ImGui::SetCursorScreenPos({options_x, options_y}); ImGui::BeginGroup(); DrawPlayLaunchOptions(options_width, entered, live); ImGui::EndGroup(); const float options_height = ImGui::GetItemRectSize().y; - const float final_height = - side ? std::max(left_height, options_height + 52.F) : left_height + options_height + 34.F; - ImGui::SetCursorScreenPos({at.x + 26.F, at.y + (side ? final_height : left_height) - 26.F - tools_height}); - DrawPlayTools(tools_width); + const float final_height = side ? std::max(height, options_height + 52.F) : height + options_height + 34.F; if (side) draw->AddLine({options_x - 16.F, at.y + 26.F}, {options_x - 16.F, at.y + final_height - 26.F}, PaddockCol(0x325365)); diff --git a/runtime-recomp/tests/library_ui_tests.cpp b/runtime-recomp/tests/library_ui_tests.cpp index 41651434..0c1c88aa 100644 --- a/runtime-recomp/tests/library_ui_tests.cpp +++ b/runtime-recomp/tests/library_ui_tests.cpp @@ -129,7 +129,8 @@ int main() { assert(pages.size() == PageCount); for (int page = 0; page < PageCount + 3; ++page) assert(pages.contains(page) == (page != 8 && page != 4 && page != 9)); - assert(sidebar_parent(4) == 0 && sidebar_parent(9) == 0); + assert(sidebar_parent(4) == 0 && sidebar_parent(9) == 0 && sidebar_parent(LeaderboardsPage) == 0); + assert(!pages.contains(LeaderboardsPage)); for (int page : SidebarOrder) assert(sidebar_parent(page) == page); assert(ModsSections.size() == 5); diff --git a/runtime-recomp/tests/play_launch_layout_tests.py b/runtime-recomp/tests/play_launch_layout_tests.py index f0809c8a..5121a639 100644 --- a/runtime-recomp/tests/play_launch_layout_tests.py +++ b/runtime-recomp/tests/play_launch_layout_tests.py @@ -25,8 +25,11 @@ def main(): parser.add_argument("--surface", choices=("launcher", "overlay"), default="launcher") parser.add_argument("--language", default="en") parser.add_argument("--sidebar", choices=("shoulders", "dpad"), default="shoulders") + parser.add_argument("--leaderboards", action="store_true", help="Capture Play, leaderboard categories and results") parser.add_argument("--save", type=Path, help="Check the Save Manager draft bar using an isolated copy") args = parser.parse_args() + if args.leaderboards and args.save: + parser.error("Choose a single layout check") output = args.output.resolve() output.mkdir(parents=True, exist_ok=False) profile = output / ("dkr-ui-navigation-check-" + secrets.token_hex(8)) @@ -56,7 +59,8 @@ def main(): env.update( DKR_LAUNCHER_UI_CHECK_TOKEN=token, DKR_OWNED_CHECK_LAYOUT_UI=args.size, - DKR_OWNED_CHECK_PLAY_LAUNCH="save" if args.save else "1", + DKR_OWNED_CHECK_PLAY_LAUNCH="save" if args.save else "0" if args.leaderboards else "1", + DKR_OWNED_CHECK_LEADERBOARD_LAYOUT="1" if args.leaderboards else "0", DKR_OWNED_CHECK_LAYOUT_SURFACE=args.surface, SDL_AUDIODRIVER="dummy", APPDATA=str(output / "appdata"), @@ -93,6 +97,18 @@ def main(): proc.wait(timeout=15) raise AssertionError("The isolated layout check did not finish") from None text = (profile / "logs/runtime.log").read_text(errors="replace") + if args.leaderboards: + matches = re.findall( + r"\[launcher-layout\]\[isolated-check\] step=(\d+) page=(\d+) width=(\d+) height=(\d+) captured", text + ) + assert code == 0 and len(matches) == 4, matches + assert [int(match[1]) for match in matches] == [0, 14, 14, 14] + for step, _, width, height in matches: + data = (profile / f"layout-{step}.bmp").read_bytes() + assert data[:2] == b"BM" and struct.unpack_from(" stamp) return accountTotals.result; + const today = Math.floor(stamp / 86_400_000) * 86400; + const result = Promise.resolve().then(() => db.prepare(`SELECT COUNT(*) AS total, + COUNT(CASE WHEN created_at>=? THEN 1 END) AS new7, + COUNT(CASE WHEN created_at>=? THEN 1 END) AS new30 FROM accounts WHERE status='active'`) + .bind(today - 6 * 86400, today - 29 * 86400).first()).catch(() => null); + accountTotals = { db, result, until: stamp + 60_000 }; + return result; +} + // The website uses a read-only projection. Never forward browser credentials // or actor headers to the directory. async function publicOnline(request, env, url) { @@ -20,7 +36,13 @@ async function publicOnline(request, env, url) { const response = await env.ONLINE_DIRECTORY.fetch(new Request(forwarded)); if (!response.ok) return error(503, 'unavailable'); headers['Cache-Control'] = 'public, max-age=15, s-maxage=15'; - return Response.json(await response.json(), { headers }); + const snapshot = await response.json(); + if (!cursor) { + const accounts = await registeredPlayers(env.DB); + snapshot.totalSignedUp = accounts?.total ?? null; + snapshot.newSignups = { '7': accounts?.new7 ?? null, '30': accounts?.new30 ?? null }; + } + return Response.json(snapshot, { headers }); } catch { return error(503, 'unavailable'); } diff --git a/services/online-directory/directory.mjs b/services/online-directory/directory.mjs index 1795b26e..3b9a66af 100644 --- a/services/online-directory/directory.mjs +++ b/services/online-directory/directory.mjs @@ -4,6 +4,7 @@ import { DurableObject } from 'cloudflare:workers'; const PROTOCOL = 1; const LEASE = 60_000, AUTH_LEASE = 125_000, RESERVATION = 30_000; +const HOUR = 3_600_000, DAY = 24 * HOUR, MAX_HISTORY_HOURS = 30 * 24; const MAX_BODY = 16_384, MAX_ROOMS = 1000, MAX_SESSIONS = 5000; const phases = new Set(['waiting', 'testing', 'starting', 'loading', 'racing', 'returning']); const identifier = /^[A-Za-z0-9_-]{1,160}$/; @@ -94,7 +95,13 @@ export class WorldwideDirectory extends DurableObject { CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value INTEGER NOT NULL); INSERT OR IGNORE INTO meta VALUES('revision',1); INSERT OR IGNORE INTO meta VALUES('published',0); - INSERT OR IGNORE INTO meta VALUES('connection',0);`); + INSERT OR IGNORE INTO meta VALUES('connection',0); + CREATE TABLE IF NOT EXISTS online_hourly_peaks(hour INTEGER PRIMARY KEY, players INTEGER NOT NULL); + CREATE TABLE IF NOT EXISTS online_monthly_peaks(month INTEGER PRIMARY KEY, players INTEGER NOT NULL); + CREATE TABLE IF NOT EXISTS online_yearly_peaks(year INTEGER PRIMARY KEY, players INTEGER NOT NULL); + CREATE TABLE IF NOT EXISTS online_peak(singleton INTEGER PRIMARY KEY CHECK(singleton=1), players INTEGER NOT NULL, observed_at INTEGER NOT NULL);`); + this.onlineHour = -1; + this.hourPeak = 0; for (const socket of ctx.getWebSockets()) { const data = socket.deserializeAttachment(); if (data?.instance && data?.account && (!this.sessions.has(data.instance) || (data.connection || 0) > (this.sessions.get(data.instance).data.connection || 0))) @@ -134,21 +141,107 @@ export class WorldwideDirectory extends DurableObject { catch { try { session.socket.close(1013, 'Reconnect to refresh'); } catch {} } } count() { return new Set([...this.sessions.values()].filter(s => this.live(s.data)).map(s => s.data.account)).size; } - list(cursor = '') { + observeOnline(players, time = Date.now()) { + if (players === 0) return; + try { + const hour = Math.floor(time / HOUR); + if (hour !== this.onlineHour) { + this.hourPeak = this.rows('SELECT players FROM online_hourly_peaks WHERE hour=?', hour)[0]?.players ?? 0; + this.sql.exec('DELETE FROM online_hourly_peaks WHERE hour { + this.sql.exec(`INSERT INTO online_hourly_peaks VALUES(?,?) + ON CONFLICT(hour) DO UPDATE SET players=MAX(players,excluded.players)`, hour, players); + this.sql.exec(`INSERT INTO online_peak VALUES(1,?,?) + ON CONFLICT(singleton) DO UPDATE SET players=excluded.players,observed_at=excluded.observed_at + WHERE excluded.players>online_peak.players`, players, time); + this.sql.exec(`INSERT INTO online_monthly_peaks VALUES(?,?) + ON CONFLICT(month) DO UPDATE SET players=MAX(players,excluded.players)`, month, players); + this.sql.exec('DELETE FROM online_monthly_peaks WHERE month lastDay) { + this.sql.exec("INSERT OR IGNORE INTO meta VALUES('online_stats_started',?)", time); + this.sql.exec("INSERT OR REPLACE INTO meta VALUES('online_stats_last_day',?)", day); + this.sql.exec(`INSERT INTO meta VALUES('online_stats_active_days',1) + ON CONFLICT(key) DO UPDATE SET value=value+1`); + } + }); + this.hourPeak = players; + } catch { + console.error('Failed to record directory activity.'); + } + } + onlineHistory(time) { + const hour = Math.floor(time / HOUR); + const day = Math.floor(time / DAY); + const peak = this.rows('SELECT players,observed_at AS observedAt FROM online_peak WHERE singleton=1')[0] ?? null; + const hourly = this.rows('SELECT hour,players FROM online_hourly_peaks WHERE hour>=? ORDER BY hour', + (day - 29) * 24); + const range = days => { + const cutoff = (day - days + 1) * 24; + let busiest = null; + const daily = new Map(); + for (const row of hourly) { + if (row.hour < cutoff) continue; + const dayStart = Math.floor(row.hour / 24) * DAY; + daily.set(dayStart, Math.max(row.players, daily.get(dayStart) ?? 0)); + if (!busiest || row.players > busiest.players) busiest = row; + } + return { peak: busiest?.players ?? null, + busiestHour: busiest ? { startsAt: busiest.hour * HOUR, players: busiest.players } : null, + activeDays: daily.size, history: [...daily].map(([startsAt, players]) => ({ startsAt, players })) }; + }; + const date = new Date(time); + const month = date.getUTCFullYear() * 12 + date.getUTCMonth(); + const metadata = Object.fromEntries(this.rows("SELECT key,value FROM meta WHERE key IN ('online_stats_started','online_stats_active_days')").map(row => [row.key,row.value])); + const oldestMonth = Date.UTC(Math.floor((month - 11) / 12), (month - 11) % 12, 1); + const yearly = metadata.online_stats_started < oldestMonth; + const lifetime = yearly + ? this.rows('SELECT year,players FROM online_yearly_peaks ORDER BY year') + .map(row => ({ startsAt: Date.UTC(row.year, 0, 1), players: row.players })) + : this.rows('SELECT month,players FROM online_monthly_peaks WHERE month>=? ORDER BY month', month - 11) + .map(row => ({ startsAt: Date.UTC(Math.floor(row.month / 12), row.month % 12, 1), players: row.players })); + return { peak, trackedSince: metadata.online_stats_started ?? null, periods: { + '7': range(7), '30': range(30), all: { + peak: peak?.players ?? null, + busiestHour: peak ? { startsAt: Math.floor(peak.observedAt / HOUR) * HOUR, players: peak.players } : null, + activeDays: metadata.online_stats_active_days ?? 0, interval: yearly ? 'year' : 'month', history: lifetime + } + } }; + } + list(cursor = '', web = false) { need(typeof cursor === 'string' && (!cursor || identifier.test(cursor)), 400, 'cursor', 'Invalid list cursor.'); const active = this.rows('SELECT data FROM rooms WHERE id>? ORDER BY id', cursor) .map(row => JSON.parse(row.data)).filter(room => room.visibility === 'public' && this.roomLive(room)); - return { rooms: active.slice(0, 50).map(room => publicRoom(room, this.env.RUNNING_SPECTATORS_ENABLED === 'true')), nextCursor: active.length > 50 ? active[49].id : '', - online: this.count(), revision: this.revision(), serverTime: Date.now() }; + const rooms = active.slice(0, 50).map(room => publicRoom(room, this.env.RUNNING_SPECTATORS_ENABLED === 'true')); + return { rooms, nextCursor: active.length > 50 ? active[49].id : '', + online: this.count(), revision: this.revision(), serverTime: Date.now(), ...(web && !cursor ? { + publicLobbies: active.length, + publicRacers: active.reduce((total, room) => total + room.racers, 0), + publicSpectators: active.reduce((total, room) => total + room.spectators, 0) + } : {}) }; } publicSnapshot(cursor) { - const { rooms, online, nextCursor, serverTime } = this.list(cursor); - return { - online, nextCursor, serverTime, + const { rooms, online, nextCursor, serverTime, publicLobbies, publicRacers, publicSpectators } = this.list(cursor, true); + const snapshot = { online, nextCursor, serverTime, rooms: rooms.map(({ id, title, phase, racers, maxRacers, spectators, maxSpectators, canJoin, canSpectate }) => ({ id, title, phase, racers, maxRacers, spectators, maxSpectators, canJoin, canSpectate })) }; + if (!cursor) { + snapshot.stats = { publicLobbies, publicRacers, publicSpectators }; + try { + Object.assign(snapshot.stats, this.onlineHistory(serverTime)); + } catch { console.error('Failed to read directory activity history.'); } + } + return snapshot; } cleanup() { const now = Date.now(); let changed = false; @@ -237,7 +330,10 @@ export class WorldwideDirectory extends DurableObject { this.ctx.acceptWebSocket(socket); socket.serializeAttachment(data); this.sessions.set(who.instance, { socket, data }); if (old) { try { old.socket.close(1000, 'Reconnected'); } catch {} } - this.changed(); this.send({ socket, data }, { type: 'snapshot', ...this.list() }); + this.changed(); + const snapshot = this.list(); + this.observeOnline(snapshot.online, now); + this.send({ socket, data }, { type: 'snapshot', ...snapshot }); return new Response(null, { status: 101, webSocket: client, headers: { 'Sec-WebSocket-Protocol': 'dkrr-online-v1' } }); } const current = this.sessions.get(who.instance); @@ -478,13 +574,15 @@ export class WorldwideDirectory extends DurableObject { async alarm() { this.sql.exec("INSERT OR REPLACE INTO meta VALUES('alarm',0)"); this.cleanup(); + const online = this.count(); + this.observeOnline(online); const revision = this.revision(); if (revision > this.rows("SELECT value FROM meta WHERE key='published'")[0].value) { const changes = this.rows('SELECT id,data FROM changes'); const batches = Math.max(1, Math.ceil(changes.length / 50)); for (let index = 0; index < batches; index++) { const batch = changes.slice(index * 50, (index + 1) * 50); - const delta = { type: 'delta', revision, online: this.count(), + const delta = { type: 'delta', revision, online, upsert: batch.filter(row => row.data !== 'null').map(row => JSON.parse(row.data)), remove: batch.filter(row => row.data === 'null').map(row => row.id) }; for (const session of this.sessions.values()) if (this.live(session.data)) this.send(session, delta); diff --git a/services/online-directory/tests/runtime.cjs b/services/online-directory/tests/runtime.cjs index e679a901..73747bd8 100644 --- a/services/online-directory/tests/runtime.cjs +++ b/services/online-directory/tests/runtime.cjs @@ -25,7 +25,7 @@ async function main(){ const now=Math.floor(Date.now()/1000),tokens={}; for(const name of ['host','guest','other','intruder','closer']){ const token=randomBytes(32).toString('base64url');tokens[name]=token; - await db.prepare('INSERT INTO accounts VALUES(?,?,?,?,?,?,?)').bind(name,name,'Player '+name,'player','active',now,now).run(); + await db.prepare('INSERT INTO accounts VALUES(?,?,?,?,?,?,?)').bind(name,name,'Player '+name,'player','active',name==='closer'?now-45*86400:now,now).run(); await db.prepare('INSERT INTO sessions VALUES(?,?,?,?,?,?,NULL)').bind(createHash('sha256').update(token).digest('base64url'),name,now,now,now+3600,now+86400).run(); } const api={fetch:(...args)=>mf.dispatchFetch(...args)}; @@ -77,6 +77,27 @@ async function main(){ }; await client.event('snapshot');return client; } + // Use a separate private object to exercise retention without waiting months. + const namespace=await mf.getDurableObjectNamespace('DIRECTORY','online'); + const historyObject=namespace.get(namespace.idFromName('activity-history-test')); + const today=Date.now(), day=86400000; + await historyObject.observeOnline(45,today-400*day); + await historyObject.observeOnline(30,today-15*day); + await historyObject.observeOnline(9,today); + const history=await historyObject.onlineHistory(today); + equal(history.periods['7'].peak,9,'weekly peak ignores older activity'); + equal(history.periods['30'].peak,30,'monthly peak includes activity from two weeks ago'); + equal(history.periods.all.peak,45,'old records retain the lifetime peak'); + equal(history.periods.all.activeDays,3,'lifetime tracks active days beyond recent retention'); + equal(history.periods.all.interval,'year','lifetime chart groups old observations by year'); + check(history.periods.all.history.some(point=>point.players===45),'the yearly chart keeps older records'); + const emptyActivity=await (await http('/v1/online/public')).json(); + equal(emptyActivity.online,0,'empty directory has a real zero online count'); + equal(emptyActivity.totalSignedUp,5,'registered count uses the library account table'); + equal(emptyActivity.stats.peak,null,'unobserved peak is not invented'); + equal(emptyActivity.stats.periods.all.busiestHour,null,'unobserved peak time is not invented'); + equal(emptyActivity.newSignups['7'],4,'weekly sign-ups exclude an older account'); + equal(emptyActivity.newSignups['30'],4,'monthly sign-ups exclude an older account'); let host=await open('host');const guest=await open('guest'),duplicate=await open('guest'),other=await open('other'); equal((await guest.call({type:'heartbeat'})).data.online,3,'online count deduplicates accounts across instances'); equal((await api.fetch('https://test.invalid/v1/online/session',{method:'POST',headers:{Origin:'https://positron-portal.com',Authorization:'bearer '+tokens.other,'X-DKRR-Instance':other.instance},body:'{}'})).status,200,'authorization scheme casing does not change session binding'); @@ -88,6 +109,20 @@ async function main(){ const webPrivate=await (await http('/v1/online/public')).json(); equal(webPrivate.online,3,'website sees the same deduplicated active player count'); equal(webPrivate.rooms.length,0,'website excludes live private rooms'); + equal(webPrivate.stats.publicLobbies,0,'private rooms do not appear in public lobby totals'); + equal(webPrivate.stats.peak.players,3,'peak counts distinct concurrent accounts'); + check(webPrivate.stats.peak.observedAt<=webPrivate.serverTime,'recorded peak has a server timestamp'); + for (const span of ['7','30','all']) { + const period=webPrivate.stats.periods[span]; + equal(period.peak,3,'the current peak uses the same count for '+span); + equal(period.busiestHour.startsAt%3600000,0,'busiest hour starts on a UTC hour boundary for '+span); + equal(period.activeDays,1,'activity counts the current date once for '+span); + equal(period.history[0].players,3,'recorded history has the observed peak for '+span); + } + equal(webPrivate.stats.periods.all.interval,'month','new lifetime history is grouped by month'); + check(webPrivate.stats.trackedSince<=webPrivate.stats.peak.observedAt,'all-time tracking begins before the peak'); + equal(webPrivate.stats.publicRacers,0,'private racers are not counted in public totals'); + equal(webPrivate.stats.publicSpectators,0,'private spectators are not counted in public totals'); equal((await http('/v1/online/public',null,null,'POST')).status,405,'website projection is read-only'); equal((await http('/v1/online/public?cursor=invalid')).status,400,'invalid public cursor is refused'); equal((await http('/v1/online/lobbies')).status,401,'launcher list remains authenticated'); @@ -109,6 +144,10 @@ async function main(){ equal(webResponse.headers.get('Cache-Control'),'public, max-age=15, s-maxage=15','website projection is briefly cacheable'); const web=await webResponse.json(); equal(web.rooms.length,1,'public lobby visible on the website'); + equal(web.stats.publicLobbies,1,'live public lobby appears in the aggregate'); + equal(web.stats.publicRacers,1,'public racer occupancy is included'); + equal(web.stats.publicSpectators,0,'public spectator occupancy is separate'); + equal(web.stats.peak.observedAt,webPrivate.stats.peak.observedAt,'equal counts preserve the first all-time peak timestamp'); const projection=web.rooms[0]; assert.deepEqual(Object.keys(projection).sort(), ['canJoin','canSpectate','id','maxRacers','maxSpectators','phase','racers','spectators','title']); From f8bf6f6ee62f4575911639fde66db334ba87304f Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Sun, 22 Nov 2026 00:59:40 +0000 Subject: [PATCH 13/31] Compact the Ready to Race card and restore its Play tools --- .../src/game/library_ui/automatic_ui.inl | 4 +- .../src/game/localisation/settings_ui.inl | 3 +- runtime-recomp/src/game/runtime_play_ui.inl | 160 ++++++++++-------- .../tests/launcher_copy_inventory.json | 2 +- 4 files changed, 95 insertions(+), 74 deletions(-) diff --git a/runtime-recomp/src/game/library_ui/automatic_ui.inl b/runtime-recomp/src/game/library_ui/automatic_ui.inl index e3d90227..e1e3ef02 100644 --- a/runtime-recomp/src/game/library_ui/automatic_ui.inl +++ b/runtime-recomp/src/game/library_ui/automatic_ui.inl @@ -1,10 +1,8 @@ void DrawSkipLauncherSetting(float width) { if (PaddockCheckbox("##skip-launcher", "Skip launcher", &dkr::library_ui::skip_launcher, width)) SaveSettings(); - PaddockGap(6.F); - PaddockText(PaddockReading(13.F, false, 1.5F), PaddockRgb(0xABC0CC), + PaddockText(PaddockReading(13.F, false, 1.4F), PaddockRgb(0xABC0CC), dkr::localisation::text("play.skip_launcher_help"), width); - PaddockGap(8.F); } bool AutomaticStartHasMods() { diff --git a/runtime-recomp/src/game/localisation/settings_ui.inl b/runtime-recomp/src/game/localisation/settings_ui.inl index 20fb19e2..6137f931 100644 --- a/runtime-recomp/src/game/localisation/settings_ui.inl +++ b/runtime-recomp/src/game/localisation/settings_ui.inl @@ -10,12 +10,11 @@ void DrawLanguageSetting(float width) { if (preference() == choices[i].code) selected = int(i + 1); } - PaddockGap(14.F); const auto caption = text("common.language"); if (SettingsDropdown("launcher-language", caption, &selected, options, width)) { if (select(selected == 0 ? "auto" : choices[std::size_t(selected - 1)].code)) SaveSettings(); } - PaddockGap(6.F); + PaddockGap(5.F); PaddockText(PaddockReading(13.F, false, 1.5F), PaddockRgb(0xABC0CC), text("common.language_help"), width); } diff --git a/runtime-recomp/src/game/runtime_play_ui.inl b/runtime-recomp/src/game/runtime_play_ui.inl index 14212e59..02fd28e8 100644 --- a/runtime-recomp/src/game/runtime_play_ui.inl +++ b/runtime-recomp/src/game/runtime_play_ui.inl @@ -403,55 +403,67 @@ void DrawLanguageSetting(float); #include "library_ui/automatic_ui.inl" #include "library_ui/handoff_ui.inl" -void DrawPlayLaunchOptions(float width, bool entered, bool live) { +void DrawPlayIntroSettings(float width, bool live) { ImGui::BeginDisabled(live); - if (PaddockCheckbox("##skip-intro", "Skip intro", &g_skip_intro, width)) { + if (PaddockCheckbox("##skip-intro", "Skip intro", &g_skip_intro, width)) SaveSettings(); - } if (g_skip_intro) { - PaddockGap(12.0F); + PaddockGap(4.F); if (SettingsDropdown("skip-intro-destination", "Start at", &g_skip_intro_destination, {"Start menu", "Character select"}, width, false, {})) SaveSettings(); + PaddockGap(5.F); + PaddockText(PaddockReading(13.F, false, 1.4F), PaddockRgb(0xB0C9CC), "Offline launches only.", width); } - PaddockGap(8.0F); - if (g_skip_intro) - PaddockText(PaddockReading(14.0F, false, 1.5F), PaddockRgb(0xB0C9CC), "Offline launches only.", width); - PaddockGap(16.0F); - if (dkr::runtime::portable::supported()) { - // Inspect only on page entry or an explicit click, never per-frame I/O. - static bool portable_enabled = false; - static std::string portable_status; - if (entered) + ImGui::EndDisabled(); +} + +void DrawPlayPortableSetting(float width, bool entered, bool live) { + if (!dkr::runtime::portable::supported()) + return; + // Inspect only on page entry or an explicit click, never per-frame I/O. + static bool portable_enabled = false; + static std::string portable_status; + if (entered) + portable_enabled = dkr::runtime::portable::enabled(); + ImGui::BeginDisabled(live); + if (PaddockCheckbox("##portable-mode", "Portable mode", &portable_enabled, width)) { + if (!dkr::runtime::portable::set_enabled(portable_enabled, portable_status)) portable_enabled = dkr::runtime::portable::enabled(); - if (PaddockCheckbox("##portable-mode", "Portable mode", &portable_enabled, width)) { - std::string error; - if (!dkr::runtime::portable::set_enabled(portable_enabled, error)) { - portable_enabled = dkr::runtime::portable::enabled(); - portable_status = std::move(error); - } else { - portable_status = "Restart DKR-R to apply. Existing saves aren't moved automatically."; - } - } - PaddockGap(8.0F); - PaddockText(PaddockReading(14.0F, false, 1.5F), PaddockRgb(0xB0C9CC), "Keep saves and settings beside DKR-R.", - width); - if (portable_enabled != dkr::runtime::portable::enabled_at_startup()) { - PaddockText(PaddockReading(14.0F, true, 1.5F), PaddockRgb(0xFFAB14), "Restart DKR-R to apply.", width); - } - if (!portable_status.empty()) { - if (dkr::runtime::copy::looks_like_error(portable_status)) - DrawIssue(portable_status, dkr::runtime::copy::Area::Portable); - else - PaddockText(PaddockReading(14.0F, false, 1.5F), PaddockRgb(0xB0C9CC), - "Existing saves aren't moved automatically.", width); - } - PaddockGap(16.0F); + else + portable_status.clear(); } ImGui::EndDisabled(); - DrawSkipLauncherSetting(width); - DrawLanguageSetting(width); - DrawPlaySaveSummary(width, live); + const auto help = PaddockReading(13.F, false, 1.4F); + PaddockText(help, PaddockRgb(0xB0C9CC), "Keep saves and settings beside DKR-R.", width); + if (!portable_status.empty()) + DrawIssue(portable_status, dkr::runtime::copy::Area::Portable); + if (portable_enabled != dkr::runtime::portable::enabled_at_startup()) { + PaddockGap(4.F); + PaddockText(help, PaddockRgb(0xFFAB14), "Restart DKR-R to apply.", width); + PaddockText(help, PaddockRgb(0xB0C9CC), "Existing saves aren't moved automatically.", width); + } + PaddockGap(6.F); +} + +void DrawPlayLaunchOptions(float width, bool entered, bool live) { + constexpr float gap = 14.F; + const bool paired = width >= 318.F; + const float column = paired ? (width - gap) * .5F : width; + const auto at = ImGui::GetCursorScreenPos(); + ImGui::BeginGroup(); + DrawPlayIntroSettings(column, live); + PaddockGap(8.F); + DrawLanguageSetting(column); + ImGui::EndGroup(); + if (paired) + ImGui::SetCursorScreenPos({at.x + column + gap, at.y}); + else + PaddockGap(10.F); + ImGui::BeginGroup(); + DrawPlayPortableSetting(column, entered, live); + DrawSkipLauncherSetting(column); + ImGui::EndGroup(); } #include "library_ui/play_launch_bar.inl" @@ -517,8 +529,6 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live ImGui::PopStyleVar(); LibraryNavigationScrollWindow(ImGui::GetCurrentWindow()); width = std::max(1.F, std::min(available_width, ImGui::GetContentRegionAvail().x - 8.F)); - DrawPlayTools(width); - PaddockGap(14.F); DrawLauncherFeatured(width, live); // The ROM pass: status, the ROM list, and the actions for it. @@ -527,19 +537,21 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live const std::size_t count = play.rom_catalog.size(); const ImVec2 at = ImGui::GetCursorScreenPos(); ImDrawList* draw = ImGui::GetWindowDrawList(); - // The pass fills the panel, but its lights and ROM controls remain a - // readable, centred group. Narrow panels retain their existing layout. - constexpr float pass_chrome = 2.0F * 2.0F + 24.0F * 2.0F + 42.0F + 20.0F; + constexpr float panel_padding = 20.F, column_gap = 24.F; + constexpr float light_width = 42.F, light_gap = 16.F; + constexpr float pass_chrome = 2.F * panel_padding + light_width + light_gap; constexpr float rom_picker_width = 560.0F; - const bool side = width >= 780.F; - const float options_width = side ? std::clamp(width * .36F, 330.F, 640.F) : std::max(1.F, width - 52.F); - const float slot_width = side ? width - options_width - 32.F : width; + const bool side = width >= 720.F; + const float inner = std::max(1.F, width - 2.F * panel_padding); + const float options_width = side ? std::clamp(inner * .48F, 318.F, 690.F) : inner; + const float slot_width = side ? width - options_width - panel_padding - column_gap : width; const float content_width = std::min(slot_width, rom_picker_width + pass_chrome); const float content_x = at.x + std::floor((slot_width - content_width) * .5F); ImDrawListSplitter pass_layers; pass_layers.Split(draw, 2); pass_layers.SetCurrentChannel(draw, 1); - const float body_x = content_x + 2.0F + 24.0F + 42.0F + 20.0F; + const float content_left = content_x + panel_padding; + const float body_x = content_left + light_width + light_gap; const float body_width = std::max(content_width - pass_chrome, 1.0F); const PaddockType heading = PaddockSign(19.0F, 1.0F, 0.0F); const PaddockType file_type = PaddockReading(15.0F, true, 1.5F); @@ -568,19 +580,20 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live const char* secondary = !state.removed.empty() ? "Undo##rom" : count > 0U && ready ? "Remove from list##rom" : nullptr; - const float primary_width = std::max(240.0F, PaddockRaceButtonWidth(primary, 19.0F, 0.12F)); - const float secondary_width = secondary != nullptr ? PlayTextButtonWidth(secondary) : 0.0F; - const bool actions_row = secondary == nullptr || primary_width + 16.0F + secondary_width <= body_width; - const float actions_height = actions_row ? 46.0F : 46.0F + 8.0F + 44.0F; + const float primary_width = std::max(168.F, PaddockRaceButtonWidth(primary, 19.F, .12F)); + const float secondary_width = secondary != nullptr ? PlayTextButtonWidth(secondary) : 0.F; + constexpr float action_gap = 12.F; + const float content_inner = std::max(1.F, content_width - 2.F * panel_padding); + const float actions_width = primary_width + (secondary ? action_gap + secondary_width : 0.F); + const bool actions_row = actions_width <= content_inner; + const float action_x = + actions_row ? std::max(content_left, body_x - std::max(0.F, actions_width - body_width)) : body_x; + const float actions_height = actions_row || !secondary ? 46.F : 46.F + 6.F + 44.F; const float pick_width = std::min(body_width, rom_picker_width); const float pick_height = 4.0F + pick_label.line + 6.0F + 60.0F + 8.0F; const auto no_rom = dkr::localisation::source("Choose a Diddy Kong Racing ROM to start."); const float detail_height = count > 0U ? pick_height : PaddockTextHeight(file_type, no_rom, body_width); const float meta_height = PaddockTextHeight(meta_type, meta, body_width); - const float body_height = - 6.0F + heading.line + 8.0F + detail_height + 2.0F + meta_height + 16.0F + actions_height; - const float height = 2.0F + 20.0F + std::max(112.0F, body_height) + 20.0F + 2.0F; - // The border turns green with the last light. const float since = static_cast(PaddockClock() - state.arrived_at); ImU32 border = PaddockRgb(ready ? 0x1AC2A3U : 0xE82E21U); @@ -592,7 +605,7 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live panel.fill = PaddockRgb(0x0B2E40, 245U); panel.border = border; panel.border_width = 2.0F; - DrawPlayLights(draw, {content_x + 2.0F + 24.0F, at.y + 2.0F + 20.0F}, ready, state.arrived_at); + DrawPlayLights(draw, {content_left, at.y + panel_padding}, ready, state.arrived_at); float y = at.y + 2.0F + 20.0F + 6.0F; const auto title = dkr::localisation::source(ready ? "Ready to race" : "ROM not loaded"); @@ -631,9 +644,9 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live PaddockTextStyle meta_style; meta_style.colour = PaddockCol(meta_colour); PaddockTextAt(draw, meta_type, {body_x, y}, body_width, meta, meta_style); - y += meta_height + 16.0F; + y += meta_height + 10.F; - ImGui::SetCursorScreenPos({body_x, y}); + ImGui::SetCursorScreenPos({action_x, y}); if (state.focus == PlayPageState::Focus::Browse && !ready) { if (nav) ImGui::SetKeyboardFocusHere(); @@ -644,12 +657,13 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live look.hover_in = 0.12F; look.ellipsis_spread = 0.12F; ImGui::BeginDisabled(live || lobby || launch_modal); - if (PaddockRaceButton(primary, {std::min(body_width, primary_width), 46.0F}, look)) { + const float action_width = std::clamp(content_left + content_inner - action_x, 1.F, primary_width); + if (PaddockRaceButton(primary, {action_width, 46.F}, look)) { OpenRomBrowser(play.selected_rom); } if (secondary != nullptr) { - ImGui::SetCursorScreenPos(actions_row ? ImVec2{body_x + primary_width + 16.0F, y + 1.0F} - : ImVec2{body_x - 8.0F, y + 46.0F + 8.0F}); + ImGui::SetCursorScreenPos(actions_row ? ImVec2{action_x + primary_width + action_gap, y + 1.F} + : ImVec2{body_x, y + 46.F + 6.F}); if (state.removed.empty()) { ImGui::BeginDisabled(lobby || launch_modal); if (PlayTextButton(secondary, true)) { @@ -666,17 +680,27 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live } ImGui::EndDisabled(); ImGui::PopStyleColor(); - const float options_x = side ? at.x + width - options_width - 26.F : at.x + 26.F; - const float options_y = side ? at.y + 26.F : at.y + height + 8.F; + ImGui::SetCursorScreenPos({content_left, y + actions_height + 14.F}); + ImGui::BeginGroup(); + DrawPlaySaveSummary(content_inner, live); + ImGui::EndGroup(); + const float resume_bottom = ImGui::GetItemRectMax().y; + + const float options_x = side ? at.x + width - panel_padding - options_width : at.x + panel_padding; + const float options_y = side ? at.y + panel_padding : resume_bottom + 6.F; ImGui::SetCursorScreenPos({options_x, options_y}); ImGui::BeginGroup(); DrawPlayLaunchOptions(options_width, entered, live); ImGui::EndGroup(); - const float options_height = ImGui::GetItemRectSize().y; - const float final_height = side ? std::max(height, options_height + 52.F) : height + options_height + 34.F; + const float tools_y = std::max(resume_bottom, ImGui::GetItemRectMax().y) + 8.F; + const float tools_width = std::max(1.F, width - 36.F); + ImGui::SetCursorScreenPos({at.x + 18.F, tools_y + 10.F}); + DrawPlayTools(tools_width); + const float final_height = ImGui::GetItemRectMax().y + 18.F - at.y; + draw->AddLine({at.x + 18.F, tools_y}, {at.x + width - 18.F, tools_y}, PaddockCol(0x325365)); if (side) - draw->AddLine({options_x - 16.F, at.y + 26.F}, {options_x - 16.F, at.y + final_height - 26.F}, - PaddockCol(0x325365)); + draw->AddLine({options_x - column_gap * .5F, at.y + panel_padding}, + {options_x - column_gap * .5F, tools_y - 8.F}, PaddockCol(0x325365)); pass_layers.SetCurrentChannel(draw, 0); PaddockPanel(draw, at, {at.x + width, at.y + final_height}, panel); pass_layers.Merge(draw); diff --git a/runtime-recomp/tests/launcher_copy_inventory.json b/runtime-recomp/tests/launcher_copy_inventory.json index a1ac4da9..1f739e80 100644 --- a/runtime-recomp/tests/launcher_copy_inventory.json +++ b/runtime-recomp/tests/launcher_copy_inventory.json @@ -54,7 +54,7 @@ "id": "COPY-008", "file": "runtime_play_ui.inl", "previous": "Portable mode preference saved. Existing saves and settings were not moved or replaced.", - "approved": "Restart DKR-R to apply. Existing saves aren't moved automatically.", + "approved": "Restart DKR-R to apply.", "verification": "literal" }, { From 1a8bb0df81f1ba245fb57706dfdb983da1d71d24 Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Sun, 22 Nov 2026 01:09:30 +0000 Subject: [PATCH 14/31] Order Play startup checkboxes together --- runtime-recomp/src/game/runtime_play_ui.inl | 36 +++++++++------------ 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/runtime-recomp/src/game/runtime_play_ui.inl b/runtime-recomp/src/game/runtime_play_ui.inl index 02fd28e8..b3e52976 100644 --- a/runtime-recomp/src/game/runtime_play_ui.inl +++ b/runtime-recomp/src/game/runtime_play_ui.inl @@ -403,21 +403,6 @@ void DrawLanguageSetting(float); #include "library_ui/automatic_ui.inl" #include "library_ui/handoff_ui.inl" -void DrawPlayIntroSettings(float width, bool live) { - ImGui::BeginDisabled(live); - if (PaddockCheckbox("##skip-intro", "Skip intro", &g_skip_intro, width)) - SaveSettings(); - if (g_skip_intro) { - PaddockGap(4.F); - if (SettingsDropdown("skip-intro-destination", "Start at", &g_skip_intro_destination, - {"Start menu", "Character select"}, width, false, {})) - SaveSettings(); - PaddockGap(5.F); - PaddockText(PaddockReading(13.F, false, 1.4F), PaddockRgb(0xB0C9CC), "Offline launches only.", width); - } - ImGui::EndDisabled(); -} - void DrawPlayPortableSetting(float width, bool entered, bool live) { if (!dkr::runtime::portable::supported()) return; @@ -452,17 +437,28 @@ void DrawPlayLaunchOptions(float width, bool entered, bool live) { const float column = paired ? (width - gap) * .5F : width; const auto at = ImGui::GetCursorScreenPos(); ImGui::BeginGroup(); - DrawPlayIntroSettings(column, live); - PaddockGap(8.F); - DrawLanguageSetting(column); + DrawPlayPortableSetting(column, entered, live); + DrawSkipLauncherSetting(column); + PaddockGap(6.F); + ImGui::BeginDisabled(live); + if (PaddockCheckbox("##skip-intro", "Skip intro", &g_skip_intro, column)) + SaveSettings(); + ImGui::EndDisabled(); ImGui::EndGroup(); if (paired) ImGui::SetCursorScreenPos({at.x + column + gap, at.y}); else PaddockGap(10.F); ImGui::BeginGroup(); - DrawPlayPortableSetting(column, entered, live); - DrawSkipLauncherSetting(column); + if (g_skip_intro) { + if (SettingsDropdown("skip-intro-destination", "Start at", &g_skip_intro_destination, + {"Start menu", "Character select"}, column, live, {})) + SaveSettings(); + PaddockGap(5.F); + PaddockText(PaddockReading(13.F, false, 1.4F), PaddockRgb(0xB0C9CC), "Offline launches only.", column); + PaddockGap(8.F); + } + DrawLanguageSetting(column); ImGui::EndGroup(); } From d5aa98a2014ec849dd94e51e8b20b0bf5f8ced16 Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Sun, 22 Nov 2026 01:13:56 +0000 Subject: [PATCH 15/31] Align Start at with Skip intro below Language --- runtime-recomp/src/game/runtime_play_ui.inl | 43 +++++++++++++++------ 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/runtime-recomp/src/game/runtime_play_ui.inl b/runtime-recomp/src/game/runtime_play_ui.inl index b3e52976..95aa4be4 100644 --- a/runtime-recomp/src/game/runtime_play_ui.inl +++ b/runtime-recomp/src/game/runtime_play_ui.inl @@ -431,35 +431,56 @@ void DrawPlayPortableSetting(float width, bool entered, bool live) { PaddockGap(6.F); } +void SettingsLabel(std::string_view label, float width); + void DrawPlayLaunchOptions(float width, bool entered, bool live) { constexpr float gap = 14.F; const bool paired = width >= 318.F; const float column = paired ? (width - gap) * .5F : width; const auto at = ImGui::GetCursorScreenPos(); + const float fields_x = paired ? at.x + column + gap : at.x; + const auto draw_skip_intro = [&] { + ImGui::BeginDisabled(live); + if (PaddockCheckbox("##skip-intro", "Skip intro", &g_skip_intro, column)) + SaveSettings(); + ImGui::EndDisabled(); + }; + ImGui::BeginGroup(); DrawPlayPortableSetting(column, entered, live); DrawSkipLauncherSetting(column); - PaddockGap(6.F); - ImGui::BeginDisabled(live); - if (PaddockCheckbox("##skip-intro", "Skip intro", &g_skip_intro, column)) - SaveSettings(); - ImGui::EndDisabled(); ImGui::EndGroup(); - if (paired) - ImGui::SetCursorScreenPos({at.x + column + gap, at.y}); - else + const float startup_bottom = ImGui::GetItemRectMax().y; + + if (paired) { + ImGui::SetCursorScreenPos({fields_x, at.y}); + } else { + PaddockGap(6.F); + draw_skip_intro(); PaddockGap(10.F); + } + ImGui::BeginGroup(); + DrawLanguageSetting(column); + const float pair_top = std::max(startup_bottom, ImGui::GetCursorScreenPos().y) + 8.F; + float skip_y = pair_top; if (g_skip_intro) { - if (SettingsDropdown("skip-intro-destination", "Start at", &g_skip_intro_destination, + ImGui::SetCursorScreenPos({fields_x, pair_top}); + SettingsLabel("Start at", column); + // Match the centres of the 42 px checkbox row and the 52 px field. + skip_y = ImGui::GetCursorScreenPos().y + 5.F; + if (SettingsDropdown("skip-intro-destination", {}, &g_skip_intro_destination, {"Start menu", "Character select"}, column, live, {})) SaveSettings(); PaddockGap(5.F); PaddockText(PaddockReading(13.F, false, 1.4F), PaddockRgb(0xB0C9CC), "Offline launches only.", column); - PaddockGap(8.F); } - DrawLanguageSetting(column); ImGui::EndGroup(); + + if (paired) { + ImGui::SetCursorScreenPos({at.x, skip_y}); + draw_skip_intro(); + } } #include "library_ui/play_launch_bar.inl" From 6395dc482ffe17d9f53376da552622f2a9548b37 Mon Sep 17 00:00:00 2001 From: ThatGuyMcd Date: Wed, 25 Nov 2026 19:22:10 +0000 Subject: [PATCH 16/31] Preserve local online, speedrunning and launcher work for v1.0.16 --- CHANGELOG.md | 30 + VERSION | 2 +- architecture/online-identity-inputs.json | 15 +- docs/LAUNCHER.md | 9 +- docs/SAVES.md | 47 +- ...-11-22-adventure-custom-replay-playtest.md | 67 + .../2026-11-22-adventure-rng-qualification.md | 89 + .../notes/2026-11-22-ancient-lake-playtest.md | 24 + .../2026-11-22-ranked-replay-expansion.md | 73 + .../2026-11-22-ranked-theatre-playtest.md | 143 + docs/notes/2026-11-22-ranked-verification.md | 79 + .../2026-11-22-time-trial-qualification.md | 71 + .../notes/2026-11-23-replay-video-playtest.md | 89 + packaging/linux/dkr-port.appdata.xml | 4 + patches/manifest.json | 4 + .../0022-offline-replay-present-capture.patch | 155 + runtime-recomp/CMakeLists.txt | 15 + .../assets/speedrunning/AncientLake.jpg | Bin 0 -> 138377 bytes runtime-recomp/guest-hooks/hooks.toml | 137 + runtime-recomp/src/android/mobile_ui.cpp | 6 +- runtime-recomp/src/game/achievement_ui.inl | 479 +-- runtime-recomp/src/game/cloud_saves/jobs.inl | 26 + .../src/game/cloud_saves/play_ui.inl | 125 + .../src/game/cloud_saves/progress.hpp | 107 + runtime-recomp/src/game/cloud_saves/sync.hpp | 30 + runtime-recomp/src/game/cloud_saves/ui.inl | 25 + runtime-recomp/src/game/custom_tracks.cpp | 87 +- runtime-recomp/src/game/custom_tracks.hpp | 12 + runtime-recomp/src/game/dialog_style.hpp | 62 + runtime-recomp/src/game/f3ddkr_rt64.cpp | 79 +- runtime-recomp/src/game/game_main.cpp | 206 +- runtime-recomp/src/game/hud_layout_editor.cpp | 27 +- runtime-recomp/src/game/invite_ui.inl | 7 +- .../src/game/library_ui/automatic_ui.inl | 16 +- .../src/game/library_ui/handoff_ui.inl | 21 + .../game/library_ui/leaderboard_rankings.inl | 523 ++++ .../src/game/library_ui/leaderboards_page.inl | 2590 ++++++++++++++++- .../src/game/library_ui/navigation_check.inl | 25 +- .../src/game/library_ui/play_launch_bar.inl | 24 +- .../src/game/library_ui/play_tools.inl | 12 +- runtime-recomp/src/game/library_ui/policy.hpp | 10 + .../src/game/library_ui/replay_library.inl | 328 +++ .../src/game/library_ui/save_indicator.inl | 71 +- .../src/game/library_ui/shared_page_ui.inl | 13 +- .../game/library_ui/speedrunning_options.inl | 335 +++ .../game/library_ui/speedrunning_welcome.inl | 92 + .../src/game/library_ui/submitted_runs.inl | 195 ++ runtime-recomp/src/game/lobby_controls.inl | 2 +- .../src/game/localisation/imgui_ui.hpp | 9 + .../src/game/localisation/literal_ui.inl | 8 +- .../website/assets/adventure-catalogue.js | 15 + .../mod_library/website/assets/api-store.js | 13 +- .../game/mod_library/website/assets/app.js | 13 +- .../website/assets/notifications-ui.js | 162 ++ .../mod_library/website/assets/racing-ui.js | 651 ++++- .../mod_library/website/assets/racing.css | 177 ++ .../website/assets/replay-format.js | 117 +- .../src/game/mod_library/website/index.html | 11 +- .../src/game/mod_library/website/privacy.html | 2 + runtime-recomp/src/game/mod_store.cpp | 473 ++- runtime-recomp/src/game/mod_store.hpp | 34 +- runtime-recomp/src/game/mod_store_style.inl | 14 +- runtime-recomp/src/game/mod_store_ui.inl | 3 + .../src/game/mods/legacy_mod_launch.cpp | 12 +- .../src/game/mods/sdk2_tools_ui.inl | 3 +- .../src/game/netplay/session_chat/ui.inl | 2 +- .../src/game/online_nameplates_rt64.cpp | 82 +- .../src/game/online_nameplates_rt64.hpp | 5 + runtime-recomp/src/game/online_view_rt64.cpp | 29 +- runtime-recomp/src/game/online_view_rt64.hpp | 5 + .../src/game/personal_adventure_paths.hpp | 17 + .../src/game/presentation_identity.cpp | 107 +- .../src/game/presentation_identity.hpp | 13 +- runtime-recomp/src/game/record_store.inl | 2 +- runtime-recomp/src/game/rt64_renderer.cpp | 144 +- runtime-recomp/src/game/rt64_renderer.hpp | 14 + .../src/game/runtime_camera_tuning_ui.inl | 2 +- .../src/game/runtime_hud_layout.cpp | 25 +- .../src/game/runtime_legacy_mods.cpp | 3 +- .../src/game/runtime_messages_ui.inl | 2 + .../src/game/runtime_mipmap_modal.hpp | 7 +- runtime-recomp/src/game/runtime_netplay.cpp | 4 +- .../src/game/runtime_online_mods_ui.inl | 28 +- runtime-recomp/src/game/runtime_online_ui.inl | 12 +- runtime-recomp/src/game/runtime_platform.cpp | 162 +- runtime-recomp/src/game/runtime_platform.hpp | 6 + runtime-recomp/src/game/runtime_play_ui.inl | 4 +- .../src/game/runtime_quick_restart.cpp | 4 + .../src/game/runtime_save_routing.cpp | 43 +- .../src/game/runtime_save_routing.hpp | 2 + runtime-recomp/src/game/runtime_saves_ui.inl | 1008 ++++--- .../src/game/runtime_settings_ui.inl | 33 +- runtime-recomp/src/game/runtime_stubs.cpp | 16 +- .../src/game/runtime_texture_packs.cpp | 10 +- runtime-recomp/src/game/runtime_ui.cpp | 401 ++- runtime-recomp/src/game/runtime_ui.hpp | 2 + .../src/game/runtime_ui_paddock.inl | 34 +- runtime-recomp/src/game/save_manager.cpp | 181 +- runtime-recomp/src/game/save_manager.hpp | 27 +- runtime-recomp/src/game/save_storage.hpp | 34 +- .../src/game/shared_save_backend.inl | 64 +- runtime-recomp/src/game/shared_save_jobs.inl | 19 +- runtime-recomp/src/game/shared_saves.hpp | 14 +- runtime-recomp/src/game/texture_dump_ui.inl | 8 +- .../src/game/time_trial/adventure_rules.hpp | 136 + .../src/game/time_trial/adventure_splits.hpp | 227 ++ .../src/game/time_trial/courses.hpp | 58 + .../src/game/time_trial/ghost_file.hpp | 20 + .../src/game/time_trial/options.hpp | 122 + .../src/game/time_trial/session.cpp | 2146 ++++++++++++++ .../src/game/time_trial/session.hpp | 201 ++ .../src/game/time_trial/theatre_frames.hpp | 198 ++ runtime-recomp/src/game/virtual_pak.cpp | 2 +- .../symbols/time_trial_symbols.toml | 42 + .../tests/adventure_replay_rules_tests.cpp | 113 + .../tests/gen_guest_symbols_tests.py | 1 + runtime-recomp/tests/library_ui_tests.cpp | 15 + .../tests/localisation_ui_tests.cpp | 16 +- .../tests/play_launch_layout_tests.py | 24 +- runtime-recomp/tests/save_manager_tests.cpp | 212 ++ scripts/tests/test_ranked_track_package.py | 72 + scripts/tests/test_ranked_video_capture.py | 55 + scripts/tests/test_verify_time_trial.py | 78 + scripts/verify_time_trial.py | 278 ++ services/library-workflow/build.py | 2 +- services/online-directory/DEPLOYMENT.md | 177 ++ .../online-directory/api/cloud_saves_api.mjs | 96 + .../api/cloud_saves_schema.sql | 13 + services/online-directory/api/library_api.mjs | 14 +- .../api/modded_adventure_schema.sql | 10 + .../online-directory/api/notification_api.mjs | 103 + .../api/notification_schema.sql | 72 + .../online-directory/api/speedrun_api.mjs | 530 +++- .../online-directory/api/speedrun_ghost.mjs | 26 + .../api/speedrun_rankings.mjs | 218 ++ .../online-directory/api/speedrun_rules.mjs | 62 + .../online-directory/api/speedrun_schema.sql | 83 +- .../online-directory/api/speedrun_storage.mjs | 86 + .../online-directory/api/speedrun_tracks.mjs | 26 + .../api/speedrun_verifier.mjs | 348 +++ .../online-directory/api/speedrun_video.mjs | 152 + services/online-directory/api/worker.mjs | 7 + services/online-directory/build.py | 3 + .../online-directory/ranked_track_package.py | 120 + .../online-directory/render_ranked_jobs.cjs | 109 + .../online-directory/render_ranked_video.py | 420 +++ .../online-directory/run_local_ranked.cjs | 236 ++ .../online-directory/run_public_ranked.py | 210 ++ .../run_public_ranked_video.py | 220 ++ .../tests/adventure_ranked_api.cjs | 198 ++ .../tests/cloud_saves_api.cjs | 111 + .../tests/custom_ranked_e2e.cjs | 155 + .../tests/notification_api.cjs | 94 + .../online-directory/tests/speedrun_api.cjs | 536 +++- .../tests/speedrun_hosted_video.mjs | 41 + .../tests/speedrun_rankings_api.cjs | 83 + .../tests/speedrun_storage.cjs | 57 + .../tests/video_archive_fixture.cjs | 39 + services/online-directory/verify_ranked.cjs | 73 + 159 files changed, 18084 insertions(+), 1542 deletions(-) create mode 100644 docs/notes/2026-11-22-adventure-custom-replay-playtest.md create mode 100644 docs/notes/2026-11-22-adventure-rng-qualification.md create mode 100644 docs/notes/2026-11-22-ancient-lake-playtest.md create mode 100644 docs/notes/2026-11-22-ranked-replay-expansion.md create mode 100644 docs/notes/2026-11-22-ranked-theatre-playtest.md create mode 100644 docs/notes/2026-11-22-ranked-verification.md create mode 100644 docs/notes/2026-11-22-time-trial-qualification.md create mode 100644 docs/notes/2026-11-23-replay-video-playtest.md create mode 100644 patches/rt64/0022-offline-replay-present-capture.patch create mode 100644 runtime-recomp/assets/speedrunning/AncientLake.jpg create mode 100644 runtime-recomp/src/game/cloud_saves/jobs.inl create mode 100644 runtime-recomp/src/game/cloud_saves/play_ui.inl create mode 100644 runtime-recomp/src/game/cloud_saves/progress.hpp create mode 100644 runtime-recomp/src/game/cloud_saves/sync.hpp create mode 100644 runtime-recomp/src/game/cloud_saves/ui.inl create mode 100644 runtime-recomp/src/game/dialog_style.hpp create mode 100644 runtime-recomp/src/game/library_ui/leaderboard_rankings.inl create mode 100644 runtime-recomp/src/game/library_ui/replay_library.inl create mode 100644 runtime-recomp/src/game/library_ui/speedrunning_options.inl create mode 100644 runtime-recomp/src/game/library_ui/speedrunning_welcome.inl create mode 100644 runtime-recomp/src/game/library_ui/submitted_runs.inl create mode 100644 runtime-recomp/src/game/mod_library/website/assets/adventure-catalogue.js create mode 100644 runtime-recomp/src/game/mod_library/website/assets/notifications-ui.js create mode 100644 runtime-recomp/src/game/personal_adventure_paths.hpp create mode 100644 runtime-recomp/src/game/time_trial/adventure_rules.hpp create mode 100644 runtime-recomp/src/game/time_trial/adventure_splits.hpp create mode 100644 runtime-recomp/src/game/time_trial/courses.hpp create mode 100644 runtime-recomp/src/game/time_trial/ghost_file.hpp create mode 100644 runtime-recomp/src/game/time_trial/options.hpp create mode 100644 runtime-recomp/src/game/time_trial/session.cpp create mode 100644 runtime-recomp/src/game/time_trial/session.hpp create mode 100644 runtime-recomp/src/game/time_trial/theatre_frames.hpp create mode 100644 runtime-recomp/symbols/time_trial_symbols.toml create mode 100644 runtime-recomp/tests/adventure_replay_rules_tests.cpp create mode 100644 scripts/tests/test_ranked_track_package.py create mode 100644 scripts/tests/test_ranked_video_capture.py create mode 100644 scripts/tests/test_verify_time_trial.py create mode 100644 scripts/verify_time_trial.py create mode 100644 services/online-directory/api/cloud_saves_api.mjs create mode 100644 services/online-directory/api/cloud_saves_schema.sql create mode 100644 services/online-directory/api/modded_adventure_schema.sql create mode 100644 services/online-directory/api/notification_api.mjs create mode 100644 services/online-directory/api/notification_schema.sql create mode 100644 services/online-directory/api/speedrun_ghost.mjs create mode 100644 services/online-directory/api/speedrun_rankings.mjs create mode 100644 services/online-directory/api/speedrun_rules.mjs create mode 100644 services/online-directory/api/speedrun_storage.mjs create mode 100644 services/online-directory/api/speedrun_tracks.mjs create mode 100644 services/online-directory/api/speedrun_verifier.mjs create mode 100644 services/online-directory/api/speedrun_video.mjs create mode 100644 services/online-directory/ranked_track_package.py create mode 100644 services/online-directory/render_ranked_jobs.cjs create mode 100644 services/online-directory/render_ranked_video.py create mode 100644 services/online-directory/run_local_ranked.cjs create mode 100644 services/online-directory/run_public_ranked.py create mode 100644 services/online-directory/run_public_ranked_video.py create mode 100644 services/online-directory/tests/adventure_ranked_api.cjs create mode 100644 services/online-directory/tests/cloud_saves_api.cjs create mode 100644 services/online-directory/tests/custom_ranked_e2e.cjs create mode 100644 services/online-directory/tests/notification_api.cjs create mode 100644 services/online-directory/tests/speedrun_hosted_video.mjs create mode 100644 services/online-directory/tests/speedrun_rankings_api.cjs create mode 100644 services/online-directory/tests/speedrun_storage.cjs create mode 100644 services/online-directory/tests/video_archive_fixture.cjs create mode 100644 services/online-directory/verify_ranked.cjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 19bcea03..d2bb9d9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,35 @@ # DKR-R changelog +## 1.0.16 playtest 5 — 2026-11-25 + +- Browse Achievements in the Badge Gallery with search, filters and individual + badge details. +- Use the standard launcher tabs in Save Manager. Progress shows every editing + tool, including the Max Out actions. Files groups transfer and recovery tools. + +## 1.0.16 playtest 4 — 2026-11-25 + +- Put Adventure slots beside the editor in Save Manager for both Vanilla and + Modded saves. Keep Progress, Unlocks, Records and Files in a single workspace. +- Keep Apply Changes and Discard Changes visible while the editor scrolls. + Vanilla and Modded saves keep separate drafts, backups and Cloud Saves slots. + +## 1.0.16 playtest 3 — 2026-11-24 + +- Give Speedrunning Options its own tab under Runs. Arrange related settings + across the available width and show HUD changes over an Ancient Lake + gameplay screenshot. +- Enable Cloud Saves for signed-in players. The Play tab can turn sync on or + off beside the active save. Select the cloud icon to sync and check its status. +- Use the cloud save when devices diverge and keep the replaced copy in local + save history. A device can upload progress made from the current cloud save. +- Refresh Cloud Saves before a new Online lobby chooses its save. Sync again + when returning to the launcher, including hosted progress in an open lobby. +- Show a brief Saving Progress indicator after a game save. Send changes to + cloud-synced saves in the background once the local write succeeds. +- Give Session Mods its own Adventure save and sync it separately from Vanilla. + Existing Adventure progress stays in the Vanilla save. + ## 1.0.16 playtest 1 — 2026-11-17 - Bring our online work onto the latest contributor code. Keep the upstream diff --git a/VERSION b/VERSION index 0f210008..3b2c00a0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.0.16-playtest.1 +1.0.16-playtest.5 diff --git a/architecture/online-identity-inputs.json b/architecture/online-identity-inputs.json index 2ded3020..5d7cb32e 100644 --- a/architecture/online-identity-inputs.json +++ b/architecture/online-identity-inputs.json @@ -42,7 +42,7 @@ "patches/n64recomp/0003-null-statement-before-instruction-hooks.patch": "f864ffd285ff4b09f2a3f4e453e5f0e5b2c39e345bc05dd88f47a46b01d3dac7", "runtime-recomp/dkr.us.v77.recomp-policy.json": "c4deefd55aca1dc1af1391a86d5df366624dabed2827a0fab055e8ffad8cd702", "runtime-recomp/dkr.us.v80.recomp-policy.json": "b8a89ed014f6e6a7f1113adf72fe8c92b1f8cf8323ac4c35de00a258c28adb9b", - "runtime-recomp/guest-hooks/hooks.toml": "8a59c63567639bfc4b27f0eb7c83d9a8c3846e09d88b4021eb18d77c864761f8", + "runtime-recomp/guest-hooks/hooks.toml": "a1e443751fe3e39876ae843992e9b3a2a79956e5d4fb152ce4c36821d153f98e", "runtime-recomp/legacy-character-menu.v77.recomp-fragment.json": "82db39e16f1e30eff1851d74eaf443cd962a2b65517d95f531f4cc0924357ce0", "runtime-recomp/legacy-character-menu.v80.recomp-fragment.json": "36a304eca1e8e889216e931b52a1838b993261bb16e39c2372731b8dad6afb90", "runtime-recomp/legacy-characters.v77.recomp-fragment.json": "bf7c193ef8c7c3737720da9bec4c8c9fe4e2eb13b92d2b8b50e68ebba7f93274", @@ -108,11 +108,11 @@ "runtime-recomp/src/game/party_release.hpp": "0f364dfe23f991223547679858ca894056974d891040527a2c6e0ea6065e3676", "runtime-recomp/src/game/party_runtime.cpp": "bc72a11cf8e128929e60184a90f3e028600b28ec005f8501ccdadaf582b0ebeb", "runtime-recomp/src/game/party_runtime.hpp": "f71d5b873f71fd24000c43833171967fa40860468f2ee6f50367ac1c1c60b404", - "runtime-recomp/src/game/runtime_save_routing.cpp": "837917b9ede8d0f9cadd86edaa325da50c7e88a6c34242758f18228112737890", - "runtime-recomp/src/game/runtime_save_routing.hpp": "cb3ae802050f29e38def0d42c60c01345be2cc46a515a95e9c50d49a06cf6879", - "runtime-recomp/src/game/save_manager.cpp": "e9f129814e79576fd2369c19734d83aeff04c979068ce2cf204998f3e278f662", - "runtime-recomp/src/game/save_manager.hpp": "c004fb91343bebc9afb2361f4d4988cd28603ff94830d98daf2f01542053801c", - "runtime-recomp/src/game/save_storage.hpp": "ca3a5457b5f7a6341473661e10a662fa590f64bf240053648a4a120a7838bc78", + "runtime-recomp/src/game/runtime_save_routing.cpp": "5ff3de1c1cec5b401b5a83348845621690e839922617a44681fc4323c9e0a297", + "runtime-recomp/src/game/runtime_save_routing.hpp": "ede6f9dbaaefa85a66b795434290d996563380b3292612e33680fe891ff956ea", + "runtime-recomp/src/game/save_manager.cpp": "f0b6978a8656cc610a783fb2cbce1a4aa20701d92e4d438529af5bf9fcc6549e", + "runtime-recomp/src/game/save_manager.hpp": "c500856477ae48fc35b4894469a7d6b55c0785a416a3ba6b0401701ed6315037", + "runtime-recomp/src/game/save_storage.hpp": "15051bb636fdc60535c3b2a3e9daa93d47496b1b27a063b483ceb1969140ff1a", "runtime-recomp/src/game/track_select_draw_guest.h": "053e11b284c433b88b19470534003519ad3d16bc3e625ce4bcc2b5f4f172041e", "runtime-recomp/symbols/achievement_symbols.toml": "565d8e8c96549fc69e47d741753766e535187241275b87d54b546cd133df69f2", "runtime-recomp/symbols/audio_queue_symbols.toml": "6f0a404ec4901866bb680d02c37f19ecabf81b2e3079e046eac7d52b345bee8e", @@ -134,6 +134,7 @@ "runtime-recomp/symbols/revision_addresses.toml": "f86967949aaa21cae2a2ef804968e7d6341c6d771ff8a4afd197dfbebf872d97", "runtime-recomp/symbols/scenery_symbols.toml": "d291719ffa176a7073de3e6c48fa4cff73584cedb8e0d8a2ceda2be72dbe4f14", "runtime-recomp/symbols/startup_symbols.toml": "e4bf2f3fc699742f73ad2ac84445e0651b480bef53f26675454a7090d91ef7d2", + "runtime-recomp/symbols/time_trial_symbols.toml": "cff8034acdb874dc87e28432e557d98845d72e66d97a6c136106817cdb3a89e2", "runtime-recomp/symbols/title_text_symbols.toml": "e0ae1ea2c67d97949bfc3b51776fa7b874b1fac2d63d5351d2897a8a5103b354", "runtime-recomp/symbols/vehicle_symbols.toml": "2582392e1618d17eaebfb721ea046918acb524fe025dcba94aa5d6ab5886992f", "runtime-recomp/symbols/water_symbols.toml": "dcfb86d7645abda20caa1fea159db4b064f32246589979e6c10653ac91ce4484", @@ -207,6 +208,6 @@ }, "last_update": { "identity_changed": false, - "reason": "Add bounded checkpoint delivery diagnostics only; no message format, simulation, admission or queue policy changes." + "reason": "The offline save editor now selects Vanilla or Modded Adventure. The online path, seeds, guest data and simulation are unchanged." } } diff --git a/docs/LAUNCHER.md b/docs/LAUNCHER.md index f1b22f5a..c8867609 100644 --- a/docs/LAUNCHER.md +++ b/docs/LAUNCHER.md @@ -17,9 +17,10 @@ in both modes, including Textures and its legacy ROM installation notice. **Ready to race** is centred within its part of the Play card. The save summary has a small three-light indicator: green for Vanilla, amber for Modded and blue for Online. The label says **Using** for the running game and **Next** before -launch. Ordinary offline mods still use your shared personal Adventure; the -amber label says so. Online and isolated development progress use their own -saves, and the preview follows the running save owner. +launch. **Session Mods** selects Vanilla Adventure when off and Modded +Adventure when on. Each has separate progress and its own Cloud Saves slot. +Online and development progress use separate saves. The preview follows the +running save while you play. Use **Sidebar navigation**, just above the divider and Restart button, to choose **LB / RB** or **D-pad**. In D-pad mode, Up and Down change sidebar pages @@ -113,7 +114,7 @@ has Export, Capture and My Dumps tabs; switching tabs does not cancel an active job. See [Textures](TEXTURE_PACKS.md). CRT filters are in **Graphics > HUD & effects**. -**Play > Achievements** shows 94 local goals, filters, pinned goals, +**Play > Achievements** opens the Badge Gallery with 94 local goals, filters, pinned goals, notification settings and progress import/export. It needs no account. See [Achievements](ACHIEVEMENTS.md). diff --git a/docs/SAVES.md b/docs/SAVES.md index 6de060b2..a6c9e89a 100644 --- a/docs/SAVES.md +++ b/docs/SAVES.md @@ -1,15 +1,16 @@ # Saves and Save Manager -Your normal Adventure now stays with you when you change mods. There is one -personal save with three slots, not a new playthrough for every mod list. -Online and development progress still have their own owners. +## Vanilla and Modded Adventure -## Your personal Adventure +In **Play**, turn **Session Mods** off to play Vanilla Adventure or on to play +Modded Adventure. Each has three Adventure slots with independent balloons, +unlocks and built-in course records. All ordinary offline mod sets share the +same Modded Adventure. Your existing Adventure stays in Vanilla. Modded starts +with empty slots on first use. -Normal play, character mods, custom tracks and ordinary Custom Magic Codes use -the same personal 512-byte EEPROM. Installing a .dkrmap must not change the -stock EEPROM layout. Added-course records are stored in a separate companion -file, so extra tracks cannot shift your initials or balloon totals. +Cloud Saves syncs each Adventure independently. Sign in with the same Discord +account and enable Cloud Saves on both devices. Online Adventure, custom-course +records and Controller Paks have their own sync entries. Older saves under `saves/mods//` are kept for recovery. They are not automatically combined. Open **Save Manager > Backups & Recovery**, @@ -18,12 +19,24 @@ save is backed up first. Do not delete the old folders to tidy your profile. ## Save Manager -- **Personal save:** manage the three Adventure slots, shared unlocks and records. +Select a slot from the Adventure list to open its editor. **Progress** shows +initials, balloons, Trophy Races, amulets, keys and course progress. Use +**Max Out This Save** or **Max Out This Slot** at the top of Progress. +**Unlocks** and **Files** sit alongside Progress. **Apply Changes** and +**Discard Changes** stay visible while the editor scrolls. + + +- **Vanilla Save:** manage the Vanilla Adventure slots, progress and unlocks. +- **Modded Save:** manage the Modded Adventure slots, progress and unlocks. - **Edit progress:** choose the intended slot before changing progress. Max Out and unlock actions save after confirmation. Manual edits need Apply Changes. -- **Transfer & Paks:** import/export saves, Controller Paks and supported bundles. +- **Transfer & Paks:** a bundle includes the selected Adventure and any shared + custom-course records and Controller Paks. Import an older bundle from the + Adventure tab where you want its progress to go. +- **Reset Save:** reset the selected Adventure's slots, unlocks and built-in + records. The shared custom-course records and Controller Paks are kept. - **Online:** inspect the host's separate Adventure and choose progress for hosting. -- **Backups & Recovery:** find older mod-set saves, history and recovery copies. +- **Backups & Recovery:** find older saves and choose Vanilla or Modded as the restore destination. - **Development:** tools such as the Dev Menu use isolated development progress. Writes are checked by reading the saved bytes back. A draft opened before @@ -53,8 +66,9 @@ the application. Android uses private app storage; use its export controls. Portable mode takes effect on the next application launch. It selects another location; it does not silently move saves, mods or settings. A config override can also select another profile. Check the selected location before assuming -progress has disappeared. Personal desktop EEPROM is `saves/dkr.us.v77.bin`; -both supported US revisions use the compatible stock layout. +progress has disappeared. Vanilla uses `saves/dkr.us.v77.bin` and Modded +uses `saves/modded/dkr.us.v77.bin`. Both supported US revisions use the +compatible stock EEPROM layout. Back up your data before updating. To recover, export and inspect the surviving copy first, then restore it deliberately. No editor can recreate progress when @@ -75,10 +89,9 @@ gameplay progress. See [Achievements](ACHIEVEMENTS.md) and [Spectators](SPECTATO Open Save Manager from **Play > Save Manager**. The three-light summary in Play describes Vanilla, Modded or Online, with Using for a running session and Next -for the next launch. A modded label does not create a separate offline save: ordinary -offline mods still share personal Adventure. The accepted route is frozen until -the running game/lobby releases it. Session mods changes the next content set -without changing individual selections, copying progress or deleting saves. +for the next launch. The save chosen at launch stays active until the game +or lobby ends. Session Mods changes the save and content for the next offline +launch while preserving your individual mod selections. Save Manager keeps its pending-changes bar against the panel edges while the editor scrolls. Discard and Apply retain their existing backup and conflict diff --git a/docs/notes/2026-11-22-adventure-custom-replay-playtest.md b/docs/notes/2026-11-22-adventure-custom-replay-playtest.md new file mode 100644 index 00000000..96785c93 --- /dev/null +++ b/docs/notes/2026-11-22-adventure-custom-replay-playtest.md @@ -0,0 +1,67 @@ +# Adventure and installed track replay playtest + +## Recording in the launcher + +Select a US v1.1 ROM in Play. Open Leaderboards, choose Full Game, and +select Practice under Any%, 100%, or All Trophy Races. The timer starts +when the fresh Adventure reaches the central hub. It continues through +travel, races, menus and cutscenes after that point. The game checks the +final Wizpig victory, the 100% checklist, or the fourth Adventure gold +cup depending on the category. These sessions start with a blank memory +save and disable the usual game content, Magic Codes and save writes. + +Open Custom Tracks and scroll to Installed tracks to practice a compatible +three-lap, standalone .dkrmap. The session freezes the selected track, +excluding the rest of the local mod collection. The replay identifies the +track by its ID and a digest of the ordered gameplay assets. It loads the +level assigned to that package in the new session. The available vehicles +come from the track's authored header. + +Completed practice runs go in the local speedruns folder. Use the Replay +Theatre for Time Trials. The command-line verifier can check Adventure runs +from a fresh profile. For a custom track, pass its exact .dkrmap directory +with `--track-package`. For a full Adventure run, pass a `--timeout` in +seconds greater than the run's playback duration. + +## Leaderboards + +The launcher and overlay share the website's category order, track search, +world/vehicle/status filters, course-wide rankings, racer and vehicle +filters, lap and race views, pagination, and replay downloads. The launcher +also offers Watch, local practice and Replay Theatre. My runs follows the +signed-in account. Review runs uses the existing moderator API and role +checks. The Windows layout capture covers 1920×1080 and 1280×800. + +## Verification + +The Windows ZIP and Linux AppImage replayed the same Ancient Lake DS car +recording to 4,908 race ticks (1:21.800). Both reproduced the three lap +splits and all five gameplay checkpoints. The verifier rejected a changed +track package before playback and rejected changed inputs in the race. +The sample came from the ordinary installed Track Lab archive. The +automated driver produced the recording and a separate run verified it. + +On Windows, all three Adventure categories reached a fresh hub at update +869 and rejected an unearned finish. The Linux AppImage also reproduced +the Any% start and rejected the unearned finish. The clock matched at +update 1,800, but the gameplay hash varied between runs. A diagnostic +Windows/Linux pair matched when comparing RNG, Adventure state, racer +motion and animation separately. A subsequent run from the delivered +Windows package diverged from a previously measured prefix. That +intermittent divergence blocks ranking before qualification of complete +Adventure runs. + +All 215 host checks, the replay verifier tests and the ranked API tests +passed. The broader tooling check reports the same two Android patch +fixture errors in the integration checkout. + +## Submission gate + +The new formats are local practice formats. The public API and the +production verifier still use the existing qualified Time Trial rules. +A public custom board also needs the native content digest bound to the +published release, retrieval of the exact package by the verifier, and +signed attempt and moderation tests for that release. Battle maps and +legacy patch-based tracks need their own rules. Each Adventure category +needs a complete replay that reaches its genuine objective and repeats +on an independent verifier before enabling uploads. diff --git a/docs/notes/2026-11-22-adventure-rng-qualification.md b/docs/notes/2026-11-22-adventure-rng-qualification.md new file mode 100644 index 00000000..597c6bc6 --- /dev/null +++ b/docs/notes/2026-11-22-adventure-rng-qualification.md @@ -0,0 +1,89 @@ +# Adventure RNG and Time Trial qualification + +The intermittent replay divergence began just after entering a fresh +Adventure hub. Taj's ambience chose random timers based on the audio +channel mask. Wheel effects and visual particle emitters could also draw +from the gameplay stream. Adventure replay ruleset `adventure-us80-3` +uses the existing presentation RNG for those calls. The gameplay +checkpoints still include the gameplay seed, racer motion and Adventure +progress. Earlier practice replays keep their original rules. + +## Hub verification + +Four Windows and four Linux playbacks reached the clean hub at update +869 and independently produced the same gameplay checkpoint at update +1,800. The inputs exercised the opening of all three categories. +The packaged Windows build and Linux AppImage also matched both +checkpoints through 3,600 updates with steering and acceleration after +entering the hub. Both rejected the replay when the input ended before +the objective. The staged submission test rejected those same signed +inputs before moderation. + +Both builds reproduced the existing Ancient Lake car replay. The host +suite passed all 215 tests. The broader tooling suite still reports two +pre-existing Android patch fixture failures. + +## Recording complete qualification runs + +Use a US v1.1 ROM with the Adventure RNG playtest. In the launcher select +**Play → Leaderboards → Full Game**. Select **Practice** in the category +to start with a clean Adventure save. Capture a complete `.dkrreplay` +for each objective. + +- **Any%** ends on the final Wizpig win in Future Fun Land. +- **100%** needs 47 balloons, all four keys, both full amulets and four + gold trophy cups before the final Wizpig win. +- **All Trophy Races** ends after the fourth gold cup in Adventure. + +An independent runtime must reproduce the objective, input checkpoints +and exact finish. Use the staged Worker test with a completed practice +replay. + +```text +node services/online-directory/tests/adventure_ranked_api.cjs BUNDLE RUNTIME ROM PRACTICE_REPLAY +``` + +It issues a local attempt, keeps the recorded controller bytes, reads the +archived replay back, and requires a native engine proof before it can +check moderator approval and the replay download in staging. Without a +replay argument it checks only the API contract. + +Verify each of the same captures independently with the Linux AppImage +using `scripts/verify_time_trial.py` with `--xvfb` and +`--isolate-network`. Compare the finish, clock ticks and every +checkpoint with the proof from Windows. + +Full-game submissions remain closed pending all three completed proofs. + +## Time Trial boards + +Each new board opened after Windows verified a signed replay through all +three laps, rejected altered controls and passed moderator review in +staging. The live-pinned Linux verifier independently reproduced the +finish, lap splits and all gameplay checkpoints. + +| Course | Vehicle | +| --- | --- | +| Ancient Lake | Plane | +| Boulder Canyon | Hovercraft | +| Everfrost Peak | Plane | +| Fossil Canyon DS | Car | +| Frosty Village | Car | +| Greenwood Village | Car | +| Haunted Woods | Car | +| Hot Top Volcano | Hovercraft | +| Pirate Lagoon | Hovercraft | +| Snowball Valley | Car | +| Spacedust Alley | Car | +| Splashdown Pass | Car | +| Star City | Plane | +| Treasure Caves | Car | +| Windmill Plains | Car | + +The public catalogue now has 32 boards. It covers 20 of the 47 retail +course and vehicle combinations, with additional racer boards and three +custom boards. The two new custom boards bind the exact current Mod +Library releases. A new package revision needs its own qualification. +The automated practice +driver did not finish Crescent Island car, Darkmoon Caverns hovercraft, +Spaceport Alpha plane or Walrus Cove car in this pass. diff --git a/docs/notes/2026-11-22-ancient-lake-playtest.md b/docs/notes/2026-11-22-ancient-lake-playtest.md new file mode 100644 index 00000000..facc3223 --- /dev/null +++ b/docs/notes/2026-11-22-ancient-lake-playtest.md @@ -0,0 +1,24 @@ +# Ancient Lake replay playtest + +## Play and watch + +1. Add or select a US v1.1 Game Pak in **Play**. +2. Open **Leaderboards** from the Ready to Race card and keep **Vanilla Tracks** selected. +3. Choose **Practice** to race Ancient Lake with Diddy and the car. The overlay shows the running clock and last lap. Finish all three laps to save a replay. +4. Choose **Watch last replay** for the completed attempt, or **Open replay** to play the supplied `Ancient-Lake.dkrreplay`. Playback starts the real track and feeds the recorded controller inputs into the engine. The launcher displays the result when playback finishes. + +Practice uses a blank, in-memory save and no gameplay mods. Completing or leaving a practice run preserves your normal save and mod selections. Finished runs are stored in the profile's `speedruns` folder. These playtest replays are local practice files, so the public upload form does not accept them. + +## Qualification + +The packaged replay was recorded on Windows x64 using the retail Time Trial timer and the local test driver. It completed in **1:21.666**. The cumulative splits were **0:28.233**, **0:54.966**, and **1:21.666**. Fresh Windows and Linux x86_64 runs reproduced all **2,534** simulation updates, **4,900** race-clock ticks, and all five gameplay and random-state checkpoints. A copy with altered throttle inputs failed at the first checkpoint. A real Steam Deck hardware check is separate from the Linux software-renderer result. + +The replay comprises a bounded manifest and one effective pad sample per simulation update. A pad sample is four bytes, holding the buttons and two stick axes. The game consumes 30 simulation updates per second and scores in 60 Hz units. The initial seed comes from the Time Trial profile. Audio, HUD and other presentation code use their own random stream during the attempt. + +`scripts/verify_time_trial.py` runs the native verifier in a fresh local profile, requires a successful engine finish and reports the input file digest, recomputed clock and checkpoint hashes. It accepts a local runtime and a legally obtained US v1.1 ROM. On Linux, use `--xvfb` to verify with a local virtual display and software Vulkan. + +## Release gates + +The playtest covers Ancient Lake, one vehicle and one racer. The independent verifier covers this rules profile. Public ranking still needs account-bound attempts and native verification connected to the submission queue, followed by the moderation pilot. Other courses, ROM revisions, custom releases and the full-game categories need their own qualification. Replay playback currently runs at normal speed from the start. + +The local API test checks that deleting a runner removes their records immediately and queues the private replay for deletion. It also checks that storage cleanup retries after a failure, and that deleting a moderator preserves other players' published times. diff --git a/docs/notes/2026-11-22-ranked-replay-expansion.md b/docs/notes/2026-11-22-ranked-replay-expansion.md new file mode 100644 index 00000000..6e0d6e81 --- /dev/null +++ b/docs/notes/2026-11-22-ranked-replay-expansion.md @@ -0,0 +1,73 @@ +# Ranked replay expansion + +## Retail Time Trial + +The local launcher can select any of the 20 retail Time Trial courses and +the 47 course and vehicle combinations used by the retail save records. +The recording keeps its selected racer. Ancient Lake in the car retains +its original format and board IDs. Other combinations bind the course and +vehicle into a versioned replay and confirm them against the loaded race. + +A new board requires an independently reproduced race. Verify the same +recording against the Windows build and pinned Linux verifier, compare the +finish, lap splits, input digest and gameplay checkpoints, and confirm that +a replay with altered controls fails. Register a board for its specific +course, vehicle and racer after this check. Returning an attempt ticket from +the API is separate from verifying that player's replay and moderator approval. + +### Local proof + +Windows and the Linux AppImage reproduced the same Fossil Canyon car +fixture: 3,946 updates, 7,724 race-clock ticks (2:08.733), 2,534 best-lap +ticks, three lap splits and seven matching gameplay checkpoints. +The native verifier rejected altered input at checkpoint 600. The local +submission test issued an attempt ticket, queued the authentic recording, +verified it in the Windows package, and confirmed that it appeared on the +leaderboard after staff approval. The published replay matched the submitted +bytes. The expanded Windows package also verified the original Ancient Lake +recording. A separate Ancient Lake hovercraft smoke test confirmed the vehicle +loaded and reached checkpoint 600. Hovercraft needs a full-race proof. + +The packages are local playtests. The public submission service still +accepts the existing Ancient Lake car qualification. + +## Adventure + +Any%, 100% and All Trophy Races need a full-session format. The recorder +must include the inputs consumed in menus, during races and between levels. +Start from an isolated new Adventure save and define the exact timer start +and finish event for each category. Recent checkpoints should include RNG, +game mode, course, player state and Adventure progress from the engine. + +The existing Time Trial input hook skips menu frames. Adventure needs the +regular `input_update` call in the game thread, with the separate boot sample +kept out of the run clock. Capture the exact step rate and verify checkpoints +before and after level loads. + +For Any%, reproduce the final Wizpig victory in Future Fun Land. The retail +boss finish path records it only for first place, and the separate central +island victory cannot count. For 100%, require that victory, the 47 balloons, +the four world keys, both complete amulets and first place in the four cups. +For All Trophy Races, watch the Adventure rankings menu write the fourth +first-place cup. A bronze or silver trophy and a cup won in Tracks mode +cannot count. Derive elapsed time and progress from the clean simulation. + +The verifier now renews the active job claim and advertises its health while +a replay is running. The local API tests confirm renewal, reclaim after +expiry, and rejection of old claims. Full sessions still need a streaming +input format, separate job and archive limits, and isolated playback that +can run while short Time Trials remain eligible for verification. + +## Custom tracks + +Pin each ranked board to the exact track release and a digest of the +simulation content. Independently install that release in a fresh +verifier profile, admit only that track, and derive the map ID after loading +the track. Runtime map IDs for installed custom tracks are local assignments +and can differ across installations. + +Test native racing maps and legacy patch-based tracks separately. Battle maps +have different finish conditions from Time Trial. A locally installed track +with no identical downloadable release needs a way to supply that exact +package to the verifier before it can accept public records. A changed upload +creates a separate qualification for the new release. diff --git a/docs/notes/2026-11-22-ranked-theatre-playtest.md b/docs/notes/2026-11-22-ranked-theatre-playtest.md new file mode 100644 index 00000000..7921719e --- /dev/null +++ b/docs/notes/2026-11-22-ranked-theatre-playtest.md @@ -0,0 +1,143 @@ +# Ancient Lake ranked and Replay Theatre playtest + +Use the US v1.1 ROM you already have. The pilot runs Ancient Lake in the stock +car, solo, for three laps. It uses a fresh in-memory save and a fixed starting +seed. The profile's mods and Magic Codes are disabled for the attempt. + +In **Play > Leaderboards**, choose a stock **Racer**, then select **Practice** +or **Start ranked run**. Ranked times are grouped by racer. Finish all three +laps and allow seven seconds for the replay to capture the finish sequence. +Use **Post last run** or choose your completed file with **Post a run**. +Open **My runs** to check the submission and watch your uploaded replay. A +single approved replay counts for both **Full race** and **Best lap** for its +racer. The recorded time and splits stop at the finish line. Staff review +still applies before a time is public. + +The attempt is bound to its account, board and ruleset. A replay contains the +inputs delivered to the game and gameplay checkpoints. The verifier runs +the game with its own clean profile, compares the checkpoints and takes the +time from the reproduced race. This checks repeatability of the recorded +inputs. Moderators can also review playback. + +## Run the local pilot + +The local test server uses disposable accounts, storage and a loopback-only +address. Close it with Ctrl+C when finished. It needs Node.js, Python, a +fresh launcher profile directory, the rebuilt game executable and your own +US v1.1 ROM. On Linux pass `--xvfb` to run the verifier on a separate display. + +```sh +python services/online-directory/build.py --output build/local-ranked-worker +node services/online-directory/run_local_ranked.cjs --bundle build/local-ranked-worker --runtime --rom --jobs --profile +``` + +Start the game executable with `--config `. Add the same +ROM in Play if the profile has no ROM selected. After a verified run has been +reviewed, enter `publish ` in the local test server console. Published +rows have a **Watch** button when a launcher profile is active. + +For the automated verifier proof, replace `--profile ` +with `--fixture `. This wraps a known input +fixture in a disposable test ticket. It verifies and publishes the original +and checks that changed inputs are rejected. The script uses separate +processes and profiles for verification. + +## Replay Theatre + +In **My replays**, select **Watch** beside a local recording or download. +**Open replay folder** opens the `speedruns` folder in the active launcher +profile. Use **Open replay** for a `.dkrreplay` saved elsewhere, or select +**Watch** on a published result. Older replay files still open and end at +their recorded finish. + +Use the timeline, lap starts and **Finish** to skip through a replay. The +frame buttons move one recorded simulation update at a time. Space, Escape +and controller Start play or pause. Comma steps back and period steps +forward. Select **Exit** to return to the launcher. **Inputs** shows the +recorded stick and buttons. The speed choices are 0.5x, 1x and 2x. You can +change the target, cancel the seek, or choose whether playback resumes on +arrival. + +Replay Theatre prepares a temporary local frame index once each time a +replay is opened. The **Preparing replay** counter and the thin timeline +bar show how far that pass has reached. Playback can start while the index +is being built. Click or drag backwards or forwards through prepared +footage to display a frame without rerunning the race. An unprepared target +opens when it becomes available. **Finish** skips to the crossing, and the +timeline extends through any recorded finish sequence. + +Shared replays contain inputs and verification hashes. The Theatre uses the +racer in the recording, with Diddy implied for the original Diddy-only files. +The presentation index lives locally and is removed on normal exit. + +## Earlier local test results + +The original Ancient Lake fixture reproduced all 2,534 updates and five +gameplay checkpoints on Windows and Linux. Its full race time was 1:21.666 +and its best lap was 0:26.700. The local ranked test uploaded the fixture, +rejected altered inputs and required moderation before listing the valid +result on either board. + +At 1280x800, Replay Theatre paused, stepped from frame 49 to 50 and back to +49 and displayed the recorded controls. The timeline jumped to frame 934, +Lap 2 jumped back to frame 931 and Start rewound to frame 1. Linux tests ran +using Xvfb on WSL. + +## Earlier replay library playtest results + +A Pipsy practice recording crossed at simulation update 2,501 and played to +update 2,711 in the Linux AppImage. The Windows verifier accepted the official +race time of 1:20.566 and best lap of 0:26.233. A disposable local leaderboard +placed the run on Pipsy's full race and best lap boards after moderation and +rejected the altered-input fixture. + +The original 1:01.700 Ancient Lake replay still plays. In the 1280x800 Linux +test, Escape paused in the Theatre and playback stepped back from frame 874 +to 873 using checkpoint 870 in about 0.3 seconds. Jumps to frames 859 and +494 required exact reloads. The replay then reached update 1,935 with the +original finish and all gameplay checkpoints verified. + +The host CTest run passed 213 of 214 checks. The regression harness timed +out on the Windows-mounted checkout and passed all 25 tests from the native +Linux filesystem. The separate tooling check reports two existing Android +patch fixture failures. The guard and ranked API checks passed. + +## Whole-run scrubbing checks + +On Windows, the original Ancient Lake replay verified its 1:01.700 finish. +The Theatre presented both backward and forward jumps within the same race, +including frame 748 back to 84 and frame 204 forward to 998. A conflicting +racer option did not change the recorded Diddy. At 1280x800 on Linux, the +same replay verified all 1,935 frames and jumped from frame 1,800 back to 415 +in about 130 ms and forward to 1,154 in about 170 ms. In the packaged +AppImage, dragging the timeline while paused showed Pipsy move from frame +138 to 31 before the mouse button was released. The current Linux host +suite passed all 214 checks. The separate Windows tooling suite still reports two +existing Android patch fixture failures. + +## Agenda + +- Add **Download replay** and **Race ghost** to published leaderboard runs. + Also let players race a compatible file from **My replays**, so a saved + ghost can be used offline. +- Start with Ancient Lake Time Trial. Require the recorded route, vehicle, + and compatible rules and track release. Prepare the opponent from the + recording's inputs, with its recorded racer and timing. +- Render the ghost as a non-interacting opponent. Keep collisions, pickups, + the player's timer and save progress independent. Compare splits against + the ghost and qualify competition with a ghost before enabling it in ranked + attempts. + +### Website notifications + +The website bell appears between Moderation and Sign in or the account name. Signed-out +visitors can use it to sign in. Signed-in players see changes to their own +mod and ranked-run submissions, with a link to the relevant status page. +Moderators and admins also see mod submissions and independently verified +runs that are ready for review. Players have no access to the staff queue. + +The service records a single event per committed status change and stores read state per +account across devices. The bell shows an unread count and opens a list +with timestamps, status, and Mark all as read. Give reviewers the current +queue state when they follow a notification, including items already handled +by another moderator. The tests cover deduplication, moderation role changes, cross-device read state and deletion. The bell is also checked on narrow screens. diff --git a/docs/notes/2026-11-22-ranked-verification.md b/docs/notes/2026-11-22-ranked-verification.md new file mode 100644 index 00000000..f2c34fdd --- /dev/null +++ b/docs/notes/2026-11-22-ranked-verification.md @@ -0,0 +1,79 @@ +# Ranked replay verification playtest + +## Playtest builds + +Use the v1.0.16-playtest.1 Ranked Replay Verification Windows ZIP or Linux +AppImage with a US v1.1 ROM. In Play, open Leaderboards to practice or submit a +recording on a qualified board. The local Replay Theatre can open Time Trial +recordings, including the post-race tail. Adventure replays use linear in-game +playback while long-run verification is in testing. + +For Ancient Lake DS, install the current release through the Mod Library. +Select the installed track in Leaderboards and use Diddy in the car. For +Fossil Canyon, select Diddy and the car under Vanilla Tracks. Posting a result +queues it for independent replay. A moderator or admin reviews the verified +result before it appears in the public ranking. + +## Public boards + +The portal accepts Diddy Time Trial submissions for these newly qualified +selections. + +| Track | Vehicle | +| --- | --- | +| Ancient Lake | Hovercraft | +| Ancient Lake DS, current Mod Library release | Car | +| Fossil Canyon | Car and hovercraft | +| Hot Top Volcano | Plane | +| Jungle Falls | Car | +| Whale Bay | Hovercraft | + +The public verifier uses the existing Linux service and the same encrypted +replay storage as the previous ranked pilot. The previously queued Ancient +Lake run independently verified at 3,664 race-clock ticks and moved to +staff review. + +## Evidence + +- Ancient Lake DS, Diddy and car, reproduced 4,908 race-clock ticks (1:21.800) + on Windows and Linux. Staging used the exact published Mod Library ZIP. The + test covered the signed attempt, download and package hash, independent + replay, altered-input rejection, staff-only publication and replay download. +- Fossil Canyon, Diddy and car, reproduced 7,724 race-clock ticks (2:08.733) + on Windows and Linux. The staged submission checked the race and lap + rankings, rejected altered inputs, and downloaded the original replay after + staff approval. +- Ancient Lake hovercraft and Jungle Falls car, both with Diddy, reproduced + 5,084 and 5,626 race-clock ticks respectively on Windows and Linux. Both + passed staged attempt, altered-input rejection and moderator publication. +- Fossil Canyon hovercraft, Whale Bay hovercraft and Hot Top Volcano plane + passed the same checks at 7,498, 5,598 and 8,650 race-clock ticks. +- The Windows launcher navigation checks captured Play, track lists, results + and Full Game layouts at desktop size and 1280×800. +- The live verifier's account home was hidden by its service, and Mesa could + exhaust its thread limit. Each replay now gets a private writable home and + bounded software renderer threads. The updated pinned AppImage reproduced + the queued Ancient Lake run's finish and four gameplay checkpoints using + the production service restrictions. The recorded post-race frames were + preserved while the result was attested at the earlier finish tick. +- All 215 host tests passed, along with the pattern and identity guards. + The broader tooling suite still reports two existing Android patch fixture + failures. + +## Qualification still in progress + +Any%, 100% and All Trophy Races have separate native finish conditions and a +separate verification queue. The new checkpoint format captures all three +axes of racer position and velocity. Repeated Adventure inputs reached the +same hub and produced matching motion and save progress, while the gameplay +RNG first diverged four updates after hub entry in the traced run. One +playback consumed an extra random draw on that update and caught up five +updates later. The staging API test confirms role and proof checks. +Full-game submissions stay closed pending repeatable native playback +of a complete run in each category. + +Additional vanilla track and vehicle pairs have complete test recordings. +Public qualification is applied only to pairs that pass independent +playback and the ranked submission path. Legacy patch tracks and battle +maps need their own competition rules and evidence. + diff --git a/docs/notes/2026-11-22-time-trial-qualification.md b/docs/notes/2026-11-22-time-trial-qualification.md new file mode 100644 index 00000000..6a51ffbf --- /dev/null +++ b/docs/notes/2026-11-22-time-trial-qualification.md @@ -0,0 +1,71 @@ +# Additional Time Trial qualification + +Each public board requires an exact three-lap replay, signed submission +and moderator approval in staging, rejection of altered inputs, and +matching finish time, lap splits and checkpoints on the pinned Linux +verifier. An automated drive runs in practice and its time does not go +on the public leaderboard. + +## Retail loop sections + +Walrus Cove and Darkmoon Caverns use a temporary retail vehicle mode +for loops. The verifier treated that mode as a change of vehicle. +It now accepts the loop mode on those courses when the original vehicle +recorded by the game still matches the attempt. The selected course, +racer, base vehicle and gameplay checkpoint requirements still apply. + +The old executable rejected the same Walrus Cove replay at update 315 +for car and at update 333 for hovercraft. Both complete captures passed +the staged Windows submission and altered-input tests on the rebuilt +game. The rebuilt Linux AppImage reproduced the car's nine checkpoints +and 9,600-tick finish, and the hovercraft's eight checkpoints and +9,254-tick finish. + +The public verifier uses the previous pinned package. Both Walrus Cove +boards remain closed pending qualification against a live verifier that +can reproduce the loop sections. + +## Boards opened in this pass + +The public catalogue now has 54 boards, including five custom boards. +The 49 retail boards cover 40 of the 47 course and vehicle pairings. +Racer variants account for the additional retail boards. + +| Course | New vehicles | +| --- | --- | +| Crescent Island | Car (Pipsy), hovercraft | +| Everfrost Peak | Car, hovercraft | +| Fossil Canyon | Plane | +| Frosty Village | Hovercraft, plane | +| Greenwood Village | Hovercraft | +| Haunted Woods | Hovercraft | +| Jungle Falls | Hovercraft, plane | +| Snowball Valley | Hovercraft | +| Spacedust Alley | Hovercraft, plane | +| Spaceport Alpha | Plane (Pipsy) | +| Star City | Car, hovercraft | +| Treasure Caves | Hovercraft | +| Windmill Plains | Hovercraft, plane | +| Luigi's Raceway | Car | +| Sherbet Land | Hovercraft | + +Some Windows moves from the temporary proof filename failed after +the Linux verification had finished. Publication checked the complete +proof JSON against the pinned runtime digest, replay bytes, splits and +checkpoints in either filename. + +## Remaining retail pairings + +| Course | Vehicles | Status | +| --- | --- | --- | +| Walrus Cove | Car, hovercraft | Both verified on the rebuilt packages | +| Darkmoon Caverns | Car, hovercraft | Need completed three-lap replays | +| Spaceport Alpha | Car, hovercraft | Need completed three-lap replays | +| Treasure Caves | Plane | Needs a completed three-lap replay | + +The other custom car attempts in this pass did not yield a full +recording. Those were Mario Circuit, MSUSA Chicago, Royal Raceway, +Toad's Turnpike and Wario Stadium. + +The source guard and all 215 host tests passed. Both playtest +packages match their recorded SHA-256 checksums. diff --git a/docs/notes/2026-11-23-replay-video-playtest.md b/docs/notes/2026-11-23-replay-video-playtest.md new file mode 100644 index 00000000..bb7c3c59 --- /dev/null +++ b/docs/notes/2026-11-23-replay-video-playtest.md @@ -0,0 +1,89 @@ +# Replay and video playtest + +## Test scope + +- The local portal runs on loopback with a disposable leaderboard database and object buckets. Its Ancient Lake entry is copied from the existing verified result. No production services are used by these tests. +- The original Ancient Lake replay reproduced a 1:01.066 finish, a 0:19.566 best lap, and all four recorded gameplay checkpoints on the rebuilt Windows runtime and the Linux AppImage. +- A separate test used the same controller input bytes with a ticket issued to a disposable local account. The verifier accepted those inputs and rejected an altered recording. The verified result went through the local moderation path. +- The AppImage opened Ancient Lake through the launcher and used all 1,916 downloaded ghost samples without preparing the replay again. The shared splash stayed visible during the renderer change. The replay and ghost downloads stayed outside My Replays. +- The two Walrus Cove loop recordings reproduced their complete checkpoints on Windows. The car finished in 2:40.000 and the hovercraft in 2:34.233. +- Treasure Caves (plane, 1:39.400) and MSUSA Chicago (car, 2:38.500) matched on a Windows build and on Linux, including the replay digest, lap splits, and final checkpoint. The local portal uses the exact Mod Library release and track hashes for MSUSA Chicago. +- The portal and launcher show the eleven Full Game categories from the supplied LiveSplit templates. The stage labels and route order come from the templates. The templates do not provide engine events or proof that a category can verify end to end. +- The cold Adventure path uses an isolated, uninitialised EEPROM image. The AppImage reproduced the native new-save intro. Existing Adventure replay versions retain their original boot behaviour. + +## Local video workflow + +Run `services/online-directory/render_ranked_video.py` as a dedicated unprivileged Linux user with Python, Xvfb, libX11, xauth, xdotool and FFmpeg available. Supply `--runtime`, `--rom`, `--replay` and a new `--output` directory. Custom tracks also require `--track-package` pointing to the exact recorded track package. The job creates its own display in a private network namespace. The runtime sends the RT64 presentations and their matching 48 kHz stereo interval for each replay update over a private local socket. The export highlights buttons and moves the N64 stick using the inputs from the same recorded update. The Replay Theatre spinner and transport controls stay in the interactive viewer. + +The job writes `verified.mp4` and `proof.json` after checking the engine result against the replay clock, finish update and checkpoints. The queue leases each verified Time Trial once and retries failed captures. The portal checks the object's replay digest and serves a seekable MP4 after moderation publishes the run. + +The original 30 Hz Ancient Lake video had 2,126 authored frames and ran for 1:10.867. Picture and audio both start at zero, and the first race picture appears at 0.067 seconds. Edge played and sought through the local copy. Nineteen frame samples, including consecutive frames at two A-button transitions, matched the replay. The controller goes neutral during the finish tail. + +## Outstanding + +- Full-length native recordings for Full Game qualification and personal best and leaderboard split comparisons. The native v5 Adventure recorder now writes splits triggered by gameplay milestones. The verifier independently regenerates them and checks the result before moderation. +- Qualification of the remaining course and vehicle pairs with incomplete recordings and of custom track releases with no complete proof. +- Full Game video rendering, which needs the long-session path rather than the Time Trial frame archive. + +## Native video cadence and texture packs + +- Website video capture reads each RT64 swap before the next swap can replace it. The + private capture socket carries 60 Hz pictures and one 48 kHz PCM block per 30 Hz + replay update. The encoder keeps both RT64 pictures during motion and repeats + the authored image for transitions that supply a single picture. Check native + paired pictures during the timed race as well as the output frame rate. + The local Ancient Lake export produced two distinct RT64 pictures for every + one of its 1,832 timed updates and reproduced the original 1:01.066 finish. + Deploy the matching runtime and exporter together because the capture protocol changed. +- The planned website render profile retains a pinned copy of Sr.gu's HD pack, + 0.00 LOD bias, generated mipmaps and 16x anisotropic filtering. Keep these + settings separate from the submitter's graphics choices. Use Ancient Lake to + compare a native 60 Hz capture against the old blended preview. +- Allow the packs enabled in Graphics for live vanilla, custom-track, Ghost and + Full Game runs. Keep them in the renderer's visual settings so gameplay + mods, custom Magic Codes and unqualified track packages remain subject to the + existing ranked rules. Honour the existing Modern presentation and pack + priority rules. Keep the verifier's simulation independent of installed packs. +- Qualify the live texture change by comparing the inputs, splits, finish and + gameplay checkpoint hashes with and without a pack. Include a custom track, + a ghost run and a Full Game attempt, and confirm both US ROM revisions can + verify evidence produced with the pack enabled. + + +## Remaining work and public video backfill + +The native cadence is verified locally. The public video worker still needs the +matching Linux runtime and exporter, plus a managed render profile that loads +the pinned Sr.gu v0.2.8 pack with mip generation and sampling enabled, LOD bias +at 0.00 and 16x anisotropic filtering. Test 1080p60 as the standard Time Trial +output and keep the existing adaptive encoding and size limit for long Full +Game runs. Check a vanilla replay, a custom track with its exact package, and a +Full Game replay with its split panel before switching the public worker. + +Re-render every existing public run video. Count and deduplicate the published +video assets in D1 by run ID and source replay digest at the start of the +backfill. The public racing and lap lists show personal bests, so the inventory +needs to include older published videos still available by their run links. + +1. Record each current video digest and length, run ID, replay digest, ROM + revision, credited runner and any exact custom track package required. + Process the inventory in a resumable batch alongside the normal video queue. + Keep moderation jobs ahead of the backfill. +2. Reproduce the verified finish, splits and gameplay checkpoints before + staging each replacement. Check the RT64 cadence, widescreen presentation, + audio sync, N64 input viewer, DKR-R intro, outro and watermark, and racer + credit. For Full Game videos, check the split panel and controller placement. +3. Upload the replacement as a separate digest-named archive to the existing + FTPS storage. Check the staged video and seek ranges, then update its + current video reference only if the source replay and prior video still + match the inventory. Keep the same public run link and preserve its leaderboard + entry, replay and ghost. Retain the previous archive until the playback audit + passes so an individual replacement can be rolled back. +4. Audit every inventory row and report replaced, skipped and failed videos. + Leave the current video available for any run that needs replay compatibility + work or another render attempt. + +The in-game pack policy above is a separate launcher change. Cloud Saves are +also pending. Implement opt-in sync through the existing Discord login for +Offline, Modded and persistent Online saves. Test revision conflicts, offline +recovery and safe imports across Windows and Steam Deck before rollout. diff --git a/packaging/linux/dkr-port.appdata.xml b/packaging/linux/dkr-port.appdata.xml index e9263c4a..c571a73d 100644 --- a/packaging/linux/dkr-port.appdata.xml +++ b/packaging/linux/dkr-port.appdata.xml @@ -16,6 +16,10 @@ +

Achievement Badge Gallery and clearer Save Manager tools.

+

Save Manager keeps the Adventure slots beside the editor on Windows and Steam Deck.

+

Speedrunning Options has its own tab under Runs.

+

Rounded corners and more room around text and buttons in Launcher and in-game Overlay dialogs.

Combined upstream integration playtest with direct racer inputs, consented host handover, retained save ownership and lower-cost online picture correction.

Improved online input recovery, lower-cost checkpoints, buffered spectators and live host settings. Added storage cleanup, a pinned Play button, native custom-character names, isolated file dialogs and better crash diagnostics.

Online responsiveness and sync presentation, a unified launcher and overlay, analogue driving, controller feedback, automatic seasons, languages, display options and opt-in crash reporting.

diff --git a/patches/manifest.json b/patches/manifest.json index 2c00a6db..149c440f 100644 --- a/patches/manifest.json +++ b/patches/manifest.json @@ -238,6 +238,10 @@ { "path": "patches/rt64/0021-macos-runtime-msl-shaders.patch", "sha256": "2916492f9aefa6fccbe9bcf664ef30624f310f11be3f807305ce5ee819adf736" + }, + { + "path": "patches/rt64/0022-offline-replay-present-capture.patch", + "sha256": "d123d62b4a414657b7b31b91e3dfdbc7cc5ed9454821acdc932342ab6c02bac7" } ] }, diff --git a/patches/rt64/0022-offline-replay-present-capture.patch b/patches/rt64/0022-offline-replay-present-capture.patch new file mode 100644 index 00000000..a867600c --- /dev/null +++ b/patches/rt64/0022-offline-replay-present-capture.patch @@ -0,0 +1,155 @@ +diff --git a/src/hle/rt64_present_queue.cpp b/src/hle/rt64_present_queue.cpp +--- a/src/hle/rt64_present_queue.cpp ++++ b/src/hle/rt64_present_queue.cpp +@@ -96,6 +96,7 @@ + FramebufferManager &fbManager = ext.sharedResources->framebufferManager; + RenderTargetManager &targetManager = ext.sharedResources->renderTargetManager; + const bool usingMSAA = (targetManager.multisampling.sampleCount > 1); ++ const auto *capture = offlineCapture.load(std::memory_order_acquire); + hlslpp::float2 resolutionScale; + EnhancementConfiguration::Presentation::Mode presentationMode; + bool removeBlackBorders; +@@ -363,6 +364,16 @@ + inspector->draw(commandList); + } + ++ if (capture != nullptr) { ++ const uint32_t tag = capture->firstTag + i; ++ const int32_t width = static_cast(ext.swapChain->getWidth()); ++ const int32_t height = static_cast(ext.swapChain->getHeight()); ++ const RenderRect rect(width - 4, height - 4, width, height); ++ const RenderColor color((tag & 255U) / 255.0f, ((tag >> 8) & 255U) / 255.0f, ++ (0xA5U ^ (tag >> 16)) / 255.0f); ++ commandList->clearColor(0, color, &rect, 1); ++ } ++ + commandList->barriers(RenderBarrierStage::NONE, RenderTextureBarrier(swapChainTexture, RenderTextureLayout::PRESENT)); + commandList->end(); + const RenderCommandList *commandList = ext.presentGraphicsWorker->commandList.get(); +@@ -413,6 +424,9 @@ + if (swapChainValid && (framesToPresent > 1) && ((i + 1) < framesToPresent)) { + ext.sharedResources->totalInterpolatedPresentations.fetch_add( + 1, std::memory_order_relaxed); ++ } ++ if (swapChainValid && (capture != nullptr)) { ++ capture->presented(capture->context, static_cast(i)); + } + } + } +diff --git a/src/hle/rt64_present_queue.h b/src/hle/rt64_present_queue.h +--- a/src/hle/rt64_present_queue.h ++++ b/src/hle/rt64_present_queue.h +@@ -58,6 +58,14 @@ + VIHistory viHistory; + bool presentWaitEnabled = false; + ++ // A synchronous capture consumer reads each tagged swap before the next one can overwrite it. ++ struct OfflineCapture { ++ uint32_t firstTag; ++ void *context; ++ void (*presented)(void *context, uint32_t index); ++ }; ++ std::atomic offlineCapture{ nullptr }; ++ + PresentQueue(); + ~PresentQueue(); + void reset(); +diff --git a/src/hle/rt64_state.cpp b/src/hle/rt64_state.cpp +--- a/src/hle/rt64_state.cpp ++++ b/src/hle/rt64_state.cpp +@@ -1781,7 +1781,21 @@ + const bool presentEarly = !ext.presentQueue->viewRDRAM && (ext.enhancementConfig->presentation.mode == EnhancementConfiguration::Presentation::Mode::PresentEarly); + workload.earlyPresentApproved = false; + workload.earlyPresentColorAddress = 0; +- if (presentEarly && (workload.fbPairCount > 0)) { ++ if ((offlineCaptureVI != nullptr) && offlineCaptureVI->visible()) { ++ const VI &vi = *offlineCaptureVI; ++ for (int32_t f = workload.fbPairCount - 1; f >= 0; f--) { ++ const FramebufferPair &pair = workload.fbPairs[f]; ++ if ((pair.colorImage.address == vi.fbAddress()) && ++ (pair.colorImage.width == vi.fbSize().x) && (pair.colorImage.siz == vi.fbSiz()) && ++ pair.earlyPresentCandidate()) ++ { ++ workload.earlyPresentApproved = true; ++ workload.earlyPresentColorAddress = pair.colorImage.address; ++ break; ++ } ++ } ++ } ++ else if (presentEarly && (workload.fbPairCount > 0)) { + thread_local std::unordered_set approvalColorImageAddressSet; + approvalColorImageAddressSet.clear(); + +@@ -1963,7 +1977,11 @@ + // CPU changes directly to it and recreating them in the render thread at low resolution. + RenderWorker *worker = ext.framebufferGraphicsWorker; + Framebuffer *screenFb = framebufferManager.find(screenFbAddress); +- if (screenFb != nullptr) { ++ // The archived replay's matched framebuffer already contains this ++ // presentation. Live RDRAM belongs to the replay producer and ++ // must not overwrite the first RT64 target in the capture pair. ++ const bool replayColorTarget = (offlineCaptureVI != nullptr) && !present.colorImageAddresses.empty(); ++ if ((screenFb != nullptr) && !replayColorTarget) { + // Check compatibility of the high resolution framebuffer with the VI first. + // Ensure both the siz and width are the same. + if ((screenFbSize.x == screenFb->width) && (screenFbSiz == screenFb->siz)) { +diff --git a/src/hle/rt64_state.h b/src/hle/rt64_state.h +--- a/src/hle/rt64_state.h ++++ b/src/hle/rt64_state.h +@@ -148,6 +148,8 @@ + void fullSyncFramebufferPairTiles(Workload &workload, FramebufferPair &fbPair, uint32_t &loadOpCursor, uint32_t &rdpTileCursor); + void listProcessBegin(); + void listProcessEnd(); ++ // The replay archive owns its VI rather than deriving it from display history. ++ const VI *offlineCaptureVI = nullptr; + void updateScreen(const VI &newVI, bool fromEarlyPresent); + void updateMultisampling(); + void inspect(); +diff --git a/src/hle/rt64_workload_queue.cpp b/src/hle/rt64_workload_queue.cpp +--- a/src/hle/rt64_workload_queue.cpp ++++ b/src/hle/rt64_workload_queue.cpp +@@ -222,7 +222,8 @@ + workloadConfig.targetRate = ext.sharedResources->userConfig.refreshRateTarget; + + // Limit the target rate to the rate detected by the swap chain. +- if ((ext.sharedResources->swapChainRate > 0) && (workloadConfig.targetRate > ext.sharedResources->swapChainRate)) { ++ if ((ext.presentQueue->offlineCapture.load(std::memory_order_acquire) == nullptr) && ++ (ext.sharedResources->swapChainRate > 0) && (workloadConfig.targetRate > ext.sharedResources->swapChainRate)) { + workloadConfig.targetRate = ext.sharedResources->swapChainRate; + } + +@@ -916,6 +917,7 @@ + ElapsedTimer workloadTimer; + workloadProfiler.start(); + threadConfigurationUpdate(workload.viFbSize, workloadConfig); ++ const bool offlineCapture = ext.presentQueue->offlineCapture.load(std::memory_order_acquire) != nullptr; + + // FIXME: This is a very hacky way to find out if we need to advance the frame if the workload was paused for the first time. + if (!workload.paused || (!gameFrames[curFrameIndex].workloads.empty() && (gameFrames[curFrameIndex].workloads[0] != (uint32_t)processCursor))) { +@@ -1019,7 +1021,7 @@ + displayFrames = uint32_t((logicalTicks - displayTicks) / workload.viOriginalRate); + deltaTimeMs = 1.0f / float(workloadConfig.targetRate); + +- if ((displayFrames > 1) && frameReduction) { ++ if (!offlineCapture && (displayFrames > 1) && frameReduction) { + displayTicks += workload.viOriginalRate; + displayFrames--; + frameReduction = false; +@@ -1081,7 +1083,7 @@ + int64_t renderTimeTotalMicro = 0; + for (uint32_t frame = 0; (frame < displayFrames) && !skipWorkloadNow; frame++) { + // Evaluate if this frame should be skipped. Measure the current time and compare it to what frame is estimated should be have been rendered by now. +- if ((frame > 0) && (originalTimeMicro > 0)) { ++ if (!offlineCapture && (frame > 0) && (originalTimeMicro > 0)) { + const int64_t currentTimeMicro = workloadTimer.elapsedMicroseconds() - setupTimeMicro; + const int64_t expectedTimeMicro = frame * maxTimePerFrameMicro; + const int64_t measuredFrameMicro = renderTimeTotalMicro / framesRendered; +@@ -1147,7 +1149,7 @@ + if (generateInterpolatedFrames && (usingMSAA || (frame > 0))) { + { + std::scoped_lock cursorLock(cursorMutex); +- skipWorkloadNow = ((frame + 1) < displayFrames) && (writeCursor != threadCursor); ++ skipWorkloadNow = !offlineCapture && ((frame + 1) < displayFrames) && (writeCursor != threadCursor); + } + + { diff --git a/runtime-recomp/CMakeLists.txt b/runtime-recomp/CMakeLists.txt index 04de382d..62119257 100644 --- a/runtime-recomp/CMakeLists.txt +++ b/runtime-recomp/CMakeLists.txt @@ -1201,6 +1201,7 @@ if(DKR_RUNTIME_BUILD_GENERATED OR DKR_RUNTIME_BUILD_RT64) endif() set(DKR_GAME_SOURCES src/game/runtime_code_mods.cpp + src/game/time_trial/session.cpp src/game/audio_equalizer.cpp # The policy's asset hooks call into these with or without RT64; the # table logic itself is DKRCustomTracksCore, via DKRLegacyModLaunch. @@ -1319,6 +1320,18 @@ if(DKR_RUNTIME_BUILD_GENERATED OR DKR_RUNTIME_BUILD_RT64) list(APPEND DKR_GAME_SOURCES src/android/android_platform.cpp src/android/mobile_ui.cpp) endif() add_library(DKRPortGameCore OBJECT ${DKR_GAME_SOURCES}) + if(TARGET file_to_c) + set(preview_source "${CMAKE_CURRENT_LIST_DIR}/assets/speedrunning/AncientLake.jpg") + set(preview_blob "${CMAKE_CURRENT_BINARY_DIR}/generated/speedrunning_hud_preview") + add_custom_command( + OUTPUT "${preview_blob}.c" "${preview_blob}.h" + COMMAND "${CMAKE_COMMAND}" -E make_directory "${CMAKE_CURRENT_BINARY_DIR}/generated" + COMMAND file_to_c "${preview_source}" SpeedrunningHudPreview "${preview_blob}.c" "${preview_blob}.h" + DEPENDS "${preview_source}" file_to_c + VERBATIM + ) + target_sources(DKRPortGameCore PRIVATE "${preview_blob}.c") + endif() dkr_guest_symbols(DKRPortGameCore) if(NOT DKR_RUNTIME_BUILD_GENERATED) # host-full-nogen compiles the shipped configuration, which always has @@ -3181,6 +3194,8 @@ if(BUILD_TESTING) target_include_directories(DKRSaveStorageTests PRIVATE "${CMAKE_CURRENT_LIST_DIR}/src/game") add_test(NAME DKRSaveStorage COMMAND DKRSaveStorageTests) + add_executable(DKRAdventureReplayRulesTests tests/adventure_replay_rules_tests.cpp) + add_test(NAME DKRAdventureReplayRules COMMAND DKRAdventureReplayRulesTests) add_executable(DKRSaveCodecTests tests/dkr_save_codec_tests.cpp src/game/dkr_save_codec.cpp) target_include_directories(DKRSaveCodecTests PRIVATE "${CMAKE_CURRENT_LIST_DIR}/src/game") add_test(NAME DKRSaveCodec COMMAND DKRSaveCodecTests) diff --git a/runtime-recomp/assets/speedrunning/AncientLake.jpg b/runtime-recomp/assets/speedrunning/AncientLake.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8d4e3828762a3efac5d6913323a3c8ef117851c7 GIT binary patch literal 138377 zcmc$_bx>T<7be&QO>hV_?h@P^Cjo*>g1fsk?(W{W1r6@fXyXpS-6gm?1OfzDemhgM zGdr_YyIWhe=Z~*m)w}n-uim}&&N<&b=XL3I6M!WvDI*Dhg9H2*dtC*H0}$T9!^6Kr zcmsqtLwt{f_-3dmC`j+oQPI)SQPI#aus&jAVB%t;q2UnV;Nsx}fj|swLSjOEqL27M z{Qo=z?msgT5kDXyeZa>=!^Ho8Y_Ht_Y?OCXhyZvvD!@BzICyNh*M0yg0PyY|Jlucd z3jn|)yh8-QAt9r@f4gml1%QKphX{v=2#<{XMi~JU4)6{h0UHqshmu1S8J9}Q=p(0N zU;>I*9v-!_F|=nIpG({+C~*r&qf$5Xp8Knbb5e4C{p=O3s#<~WGhpGW#mucd4r&$$I+JUr5!Y&$Jz9zOF z&uWvAnJ)+Mgv~v^7BQRS9wGp-?RpXAC^w-dN`EHS)ekEgoIQKa>0wwi7~ea;53tKn zJF-}*;VKJ<1Tl9U@R%+R-sAWCMTZPtuV&~yw2=qh5|LQ*YxC%a%wd>B-K6#3U4LZO zkcu!;7I)Yu_Q5lq3oS8hcAVqck%%}PRrBiiG@{Obk3c%V8C0RI2{mS9euJq04sO^ zNJb+WD?Sqk5ig9V?%g-*U#{qK+Pa#yxJ+==K~Upy%?ht<8{J9_5gWOWO2z}x|9=6P zEQ$(op;By#aTKE%SKOGlj_a~5&Q;mM5X3l58~~Fws$rpao!a~xz2pMS^ie}|nTXtL zVgjc_pNO$aQ$ZtDkb#Wq5yrcRVyXcXG{I_)lu5vOS|(O94&0uRUmS*(Sovse|CQu0 zeEOo66W%w@jvb|gamL5xHQzk~GvO^(p~@96Q52A7;3+#_vFL8qH+oHH%U-kyk0rj0;qa8TZ} zZ5c{bPi2-58i>aKl>fg&H>)i+F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h~Zm;cOui1`$Qa-Kb z=Dyml=^*miihoF!0A(lH3o$6vak^g{e4R05{W^9xvUfhbX`W)B0&Z-d-#)N6dGm6k z!SSTO_wFxi;XKWUF)36p1K0mRjDp`A;4ju6uI!$XYWu{IZk7zgZe`KhKIh0-u^#9U zrDQ8yKe%jfC4``j5Yg&Y0DGilhmhJ$-)y z&(4h(o$8;Ba(?afobTx&YSV}d3Z)|^8H3CqG3SRsatVKXU3!#Mkr&=q=$^}52k!Ck zEpJ6@7B`vvD+sG{G5K@qT6;V}8?^+ldQ@dhyYW7Bu(DejSq^sI9d7H;4T$cD`( zO|DBj58@T(LVlFHuQ~IOy&hhw%KiH# z6~h04443bGJr@}<5@_cX=`fNv_{rtn)59-wMmAUS^B&UVT4VlNNcQZ0;mx!Q^<)fZ zixFYwkPN#7N*fTAVLX7&#|?)J2reK4-G=6}FnB)#p24*iD%X~xXU6YKVceSn6UiL} z+*BMYo3tOVgrE{^nmmZqUeP`n0mL=$(Sm%iaJ~1_@ z?4}T|a75b*7N?V;)OwzE-lvd^hxH~bw{<3rkvwtHSl(EMFju{M3ss)I^{GdB2%4#o zfe^f&pFro}k|Qkxr!0pDpG-S6+v;v*<>4@;K*z#*t9Sb0ZmN2qk!4O)5w*IXO0eca zMmhfU)vz&JtO|z6E`tRO2u^#7F#8E>=#X%}@(sRzRnT*;bWLSiKsc`Dgx=ud-8-VXb}r2 = 0; }''' +[[hook.edits]] +match = "timetrial_ghost_staff(rdram, ctx);" +replace = '''{ extern int dkr_practice_ghost_marker(int); + if (dkr_practice_ghost_marker(1)) timetrial_ghost_staff(rdram, ctx); else ctx->r2 = 0; }''' + +# A replay's mixer follows authored updates rather than host retraces. +[[hook]] +id = "theatre-audio-clock" +function = "__amMain" +payloads = ["funcs"] +[[hook.edits]] +match = "__amHandleFrameMsg(rdram, ctx);" +replace = '''{ extern int dkr_theatre_audio_begin(void); if (!dkr_theatre_audio_begin()) goto L_80002B20; } + __amHandleFrameMsg(rdram, ctx);''' +[[hook.edits]] +match = "__amHandleDoneMsg(rdram, ctx);" +replace = '''__amHandleDoneMsg(rdram, ctx); + { extern void dkr_theatre_audio_done(void); dkr_theatre_audio_done(); }''' + +# These rolls depend on the music channel mask and only set ambience timers. +[[hook]] +id = "adventure-parkwarden-music-rng" +function = "obj_loop_parkwarden" +payloads = ["funcs"] +[[hook.edits]] +match = '''rand_range(rdram, ctx); + goto after_91;''' +replace = '''{ extern void dkr_adventure_presentation_begin(void); extern void dkr_adventure_presentation_end(void); dkr_adventure_presentation_begin(); rand_range(rdram, ctx); dkr_adventure_presentation_end(); } + goto after_91;''' +[[hook.edits]] +match = '''rand_range(rdram, ctx); + goto after_93;''' +replace = '''{ extern void dkr_adventure_presentation_begin(void); extern void dkr_adventure_presentation_end(void); dkr_adventure_presentation_begin(); rand_range(rdram, ctx); dkr_adventure_presentation_end(); } + goto after_93;''' + +# The stock car rolls these bits only to enable visual wheel particles. +[[hook]] +id = "adventure-car-particle-mask-rng" +function = "func_8004F7F4" +payloads = ["funcs"] +[[hook.edits]] +match = '''rand_range(rdram, ctx); + goto after_30;''' +replace = '''{ extern void dkr_adventure_presentation_begin(void); extern void dkr_adventure_presentation_end(void); dkr_adventure_presentation_begin(); rand_range(rdram, ctx); dkr_adventure_presentation_end(); } + goto after_30;''' +[[hook.edits]] +match = '''rand_range(rdram, ctx); + goto after_31;''' +replace = '''{ extern void dkr_adventure_presentation_begin(void); extern void dkr_adventure_presentation_end(void); dkr_adventure_presentation_begin(); rand_range(rdram, ctx); dkr_adventure_presentation_end(); } + goto after_31;''' + +# Particle pools can change which visual draws are actually evaluated. +[[hook]] +id = "adventure-particle-emission-rng" +function = "obj_trigger_emitter" +payloads = ["funcs"] +entry = "extern void dkr_adventure_presentation_begin(void); dkr_adventure_presentation_begin();" +returns = "extern void dkr_adventure_presentation_end(void); dkr_adventure_presentation_end();" + # Achievements: observe the frame after each main loop pass (achievements). [[hook]] id = "achievements-observe" diff --git a/runtime-recomp/src/android/mobile_ui.cpp b/runtime-recomp/src/android/mobile_ui.cpp index b52a99cb..9c7f2890 100644 --- a/runtime-recomp/src/android/mobile_ui.cpp +++ b/runtime-recomp/src/android/mobile_ui.cpp @@ -3,6 +3,7 @@ #include "../game/runtime_ui.hpp" #include "imgui/imgui.h" #include "imgui/imgui_internal.h" +#include "../game/dialog_style.hpp" #include #if defined(__ANDROID__) && !defined(DKR_MOBILE_UI_TEST) #include @@ -626,7 +627,10 @@ void editor() { // expose controls beneath it. Gameplay remains blocked for its lifetime. ImGui::SetNextWindowPos({safe.x + std::max(0.0F, (safe.w - 340.0F) * .5F), safe.y}, ImGuiCond_Appearing); ImGui::SetNextWindowSize({std::min(340.0F, safe.w), std::min(330.0F, safe.h)}, ImGuiCond_Appearing); - ImGui::Begin("Touch layout - options", nullptr, ImGuiWindowFlags_NoSavedSettings); + if (!ui::begin_dialog_window("Touch layout - options", nullptr, ImGuiWindowFlags_NoSavedSettings)) { + ImGui::End(); + return; + } ImGui::TextWrapped("Drag a group. Collapse this sheet to reach covered controls."); if (ImGui::BeginCombo("Group", labels[selection])) { for (int i = 0; i < group_count; ++i) diff --git a/runtime-recomp/src/game/achievement_ui.inl b/runtime-recomp/src/game/achievement_ui.inl index 77d0ffb6..f1faca74 100644 --- a/runtime-recomp/src/game/achievement_ui.inl +++ b/runtime-recomp/src/game/achievement_ui.inl @@ -2,15 +2,16 @@ namespace ach = dkr::runtime::achievements; int g_achievement_filter = 0, g_achievement_sort = 0; std::string g_achievement_category, g_achievement_detail; std::array g_achievement_search{}; +bool g_achievement_reset_scroll = false; bool g_achievement_settings = false, g_achievement_reset = false, g_achievement_recognise = false; -bool g_achievement_focus_detail = false; std::string g_achievement_focus_row; -float g_achievement_return_scroll = 0; ach::Toast g_achievement_toast; double g_achievement_toast_started = 0; SDL_AudioDeviceID g_achievement_audio = 0; -void AchievementChime() { +void AchievementChime(float gain = 1.F) { + if (gain <= 0.F) + return; if (!g_achievement_audio) { SDL_AudioSpec wanted{}, actual{}; wanted.freq = 48000; @@ -23,7 +24,7 @@ void AchievementChime() { SDL_PauseAudioDevice(g_achievement_audio, 0); } std::vector samples(48000 * 2 * 3 / 5); - const float volume = .10F * dkr::runtime::audio::sound_effects_volume(); + const float volume = gain * .10F * dkr::runtime::audio::sound_effects_volume(); for (unsigned i = 0; i < samples.size() / 2; ++i) { const float t = float(i) / 48000.F; const float envelope = std::min(t * 90.F, 1.F) * std::exp(-6.F * t); @@ -189,81 +190,143 @@ void DrawAchievementPreferences(float width, const ach::View& state) { g_achievement_settings = false; return; } - PaddockGap(18); - DetailHeading("Notifications", width); + PaddockGap(14.F); + constexpr float gap = 12.F; + const bool side_by_side = width >= 640.F; + const float column = side_by_side ? (width - gap) * .5F : width; + const auto top = ImGui::GetCursorScreenPos(); + const auto paint = [](ImDrawList* draw, ImVec2 min, ImVec2 max) { + PaddockPanel(draw, min, max, {PaddockRound(10.F), PaddockRgb(0x0C293A), PaddockRgb(kSetBorder), 1.F}); + }; + + PaddockBox notifications(column, {14.F, 14.F}); + float inner = notifications.Inner(); + DetailHeading("Notifications", inner); auto p = state.preferences; bool changed = false; - changed |= SettingsCheck("##achievement-popups", "Show unlock notifications", &p.notifications, width); - changed |= SettingsCheck("##achievement-chime", "Play unlock sound", &p.sound, width); - changed |= SettingsCheck("##achievement-motion", "Reduce notification motion", &p.reduced_motion, width); - SettingsLabel("Position", width); - const char* positions[]{"Bottom centre", "Bottom right", "Top right"}; - ImGui::SetNextItemWidth(std::min(width, 300.F)); - changed |= ImGui::Combo("##achievement-position", &p.position, positions, 3); - SettingsLabel("Size", width); - ImGui::SetNextItemWidth(std::min(width, 360.F)); - changed |= ImGui::SliderFloat("##achievement-size", &p.scale, .7F, 1.6F, "%.1fx"); - SettingsLabel("Duration", width); - ImGui::SetNextItemWidth(std::min(width, 360.F)); - changed |= ImGui::SliderFloat("##achievement-duration", &p.duration, 2.F, 10.F, "%.0f seconds"); + changed |= SettingsCheck("##achievement-popups", "Show unlock notifications", &p.notifications, inner); + changed |= SettingsCheck("##achievement-chime", "Play unlock sound", &p.sound, inner); + changed |= SettingsCheck("##achievement-motion", "Reduce notification motion", &p.reduced_motion, inner); + changed |= SettingsDropdown("##achievement-position", "Position", &p.position, + {"Bottom centre", "Bottom right", "Top right"}, inner); + PaddockGap(8.F); + int scale = static_cast(std::lround(p.scale * 10.F)); + if (SettingsRange("##achievement-size", "Size", &scale, 7, 16, inner, [](int value) { + return SettingsRangeValue{std::to_string(value / 10) + "." + std::to_string(value % 10), "x"}; + })) { + p.scale = float(scale) / 10.F; + changed = true; + } + PaddockGap(8.F); + int duration = static_cast(std::lround(p.duration)); + if (SettingsRange("##achievement-duration", "Duration", &duration, 2, 10, inner, [](int value) { + return SettingsRangeValue{std::to_string(value), " seconds"}; + })) { + p.duration = float(duration); + changed = true; + } if (changed) ach::preferences(p); + PaddockGap(8.F); if (SettingsButton("Preview notification")) ach::preview(); - PaddockGap(22); - DetailHeading("Your collection", width); - DetailText("Achievements stay separate from your game saves. Starting another adventure will not erase them.", - width); - DumpActionRow files(width); + const float left_height = notifications.End(paint); + + ImGui::SetCursorScreenPos(side_by_side ? ImVec2{top.x + column + gap, top.y} + : ImVec2{top.x, top.y + left_height + gap}); + PaddockBox collection(column, {14.F, 14.F}); + inner = collection.Inner(); + DetailHeading("Your collection", inner); + DetailText("Achievements stay separate from your game saves. Starting another adventure will not erase them.", inner); + DumpActionRow files(inner); if (files.Button("Export backup")) AchievementFileDialog(false); if (files.Button("Import backup")) AchievementFileDialog(true); if (files.Button("Recognise existing progress")) g_achievement_recognise = true; - PaddockGap(16); + PaddockGap(16.F); if (SettingsButton("Reset achievement collection")) g_achievement_reset = true; + collection.End(paint); + ImGui::SetCursorScreenPos({top.x, std::max(top.y + left_height, ImGui::GetItemRectMax().y)}); + ImGui::Dummy({width, 0.F}); PaddockGap(18); DetailText( "Challenge objectives inspired by Delmaru's Diddy Kong Racing achievement set. Local DKR-R implementation, wording and badge designs. Not connected to RetroAchievements.", width, kSetMuted); } -void DrawAchievementsPage(float width) { - const auto state = ach::view(); - const auto& definitions = ach::catalogue(); - DrawPageHeading("ACHIEVEMENTS"); - PaddockGap(8); - DetailText("Your challenges. Your collection.", width, kSetMuted, 12); - DetailHeading(std::to_string(state->unlocked) + " / 94 unlocked", width); - ImGui::ProgressBar(float(state->unlocked) / 94.F, {width, 7.F}, ""); - PaddockGap(14); - if (!state->error.empty()) - DetailText(state->error, width, 0xFFAB72); - else if (state->status != "Saved on this device") - DetailText(state->status, width, kSetMuted); - if (g_achievement_settings) { - DrawAchievementPreferences(width, *state); - } else if (!g_achievement_detail.empty()) { - const auto found = std::find_if(definitions.begin(), definitions.end(), - [](const auto& d) { return d.id == g_achievement_detail; }); - if (found == definitions.end()) { - g_achievement_detail.clear(); - return; - } +void AchievementProgressBar(float width, float progress) { + const auto at = ImGui::GetCursorScreenPos(); + auto* draw = ImGui::GetWindowDrawList(); + const auto end = ImVec2{at.x + width, at.y + 6.F}; + PaddockFill(draw, at, end, PaddockRound(3.F), PaddockCol(0x071B28)); + const float filled = width * std::clamp(progress, 0.F, 1.F); + if (filled > 0.F) + PaddockFill(draw, at, {at.x + filled, end.y}, PaddockRound(3.F), PaddockCol(kSetWarm)); + ImGui::Dummy({width, 6.F}); +} + +bool AchievementHasProgress(const ach::Definition& badge) { + return badge.target > 1 && badge.kind != ach::Kind::TimeTrial && badge.kind != ach::Kind::Developer; +} + +bool DrawAchievementGalleryCard(const ach::Definition& badge, const ach::Entry& entry, float width, + float height, bool pinned) { + ImGui::PushID(badge.id.c_str()); + if (g_achievement_focus_row == badge.id) { + ImGui::SetKeyboardFocusHere(); + g_achievement_focus_row.clear(); + } + const auto press = PaddockBeginPress("##badge", {width, height}); + auto* draw = ImGui::GetWindowDrawList(); + const bool active = ImGui::IsItemFocused() || press.hovered; + PaddockPanel(draw, press.min, press.max, + {PaddockRound(10.F), PaddockRgb(active ? 0x123C4E : 0x0C293A), + PaddockRgb(active ? kSetWarm : kSetBorder), 1.F}); + constexpr float pad = 11.F; + DrawAchievementBadge({press.min.x + pad, press.min.y + 8.F}, 36.F, AchievementBadge(badge), entry.unlocked); + const auto title = PaddockReading(16.F, true, 1.17F); + const auto meta = PaddockReading(13.F, false, 1.24F); + const float category_width = std::min(PaddockMeasure(meta, badge.category), width - 64.F); + PaddockTextAt(draw, meta, {press.max.x - pad - category_width, press.min.y + 14.F}, category_width + 0.5F, + badge.category, {PaddockRgb(kSetMuted)}); + PaddockTextAt(draw, title, {press.min.x + pad, press.min.y + 50.F}, width - 2.F * pad, badge.title, + {PaddockRgb(kSetText)}); + const bool progress = AchievementHasProgress(badge) && !entry.unlocked; + const std::string status = entry.unlocked ? (entry.restored ? "Recognised" : "Unlocked") + : pinned ? "Pinned" + : progress ? std::to_string(std::clamp(entry.progress, 0, badge.target)) + " / " + + std::to_string(badge.target) + : "Locked"; + PaddockTextAt(draw, meta, {press.min.x + 12.F, press.max.y - (progress ? 34.F : 25.F)}, width - 24.F, + status, {PaddockRgb(entry.unlocked ? 0x42D6BC : pinned ? kSetWarm : kSetMuted)}); + if (progress) { + const float y = press.max.y - 12.F; + const float fraction = std::clamp(float(entry.progress) / float(badge.target), 0.F, 1.F); + PaddockFill(draw, {press.min.x + 12.F, y}, {press.max.x - 12.F, y + 4.F}, + PaddockRound(2.F), PaddockCol(0x071B28)); + if (fraction > 0.F) + PaddockFill(draw, {press.min.x + 12.F, y}, {press.min.x + 12.F + (width - 24.F) * fraction, y + 4.F}, + PaddockRound(2.F), PaddockCol(kSetWarm)); + } + ImGui::PopID(); + return press.pressed; +} + +void DrawAchievementDetail(const ach::View& state, const std::vector& definitions) { + const auto found = std::ranges::find(definitions, g_achievement_detail, &ach::Definition::id); + if (found == definitions.end()) + return; + if (BeginSettingsDialog("##achievement-detail", found->title, 570.F, 0x0C293A)) { const auto index = std::size_t(found - definitions.begin()); - const auto& entry = state->entries[index]; - if (g_achievement_focus_detail) { - ImGui::SetKeyboardFocusHere(); - g_achievement_focus_detail = false; - } - if (SettingsButton("Back to achievements") || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) { - g_achievement_focus_row = g_achievement_detail; - g_achievement_detail.clear(); - ImGui::SetScrollY(g_achievement_return_scroll); - } - PaddockGap(18); - DetailHeading(found->title, width); + const auto& entry = state.entries[index]; + const float width = SettingsDialogInner(); + const auto summary = ImGui::GetCursorScreenPos(); + DrawAchievementBadge(summary, 44.F, AchievementBadge(*found), entry.unlocked); + ImGui::SetCursorScreenPos({summary.x + 56.F, summary.y + 10.F}); + DetailText(found->category, width - 56.F, kSetWarm); + ImGui::SetCursorScreenPos({summary.x, summary.y + 51.F}); DetailText(found->description, width); DetailText(entry.unlocked ? (entry.restored ? "Recognised from existing progress" : entry.modded ? "Unlocked during modded play" @@ -291,14 +354,15 @@ void DrawAchievementsPage(float width) { char target[48]; std::snprintf(target, sizeof(target), "Target: %d:%02d.%02d", hundredths / 6000, (hundredths / 100) % 60, hundredths % 100); - DetailText(target, width); + constexpr const char* vehicles[]{"Car", "Hovercraft", "Plane"}; + DetailText(std::string(target) + " | " + vehicles[c->vehicle], width); } } else if (found->target > 1) { DetailText(std::to_string(entry.progress) + " / " + std::to_string(found->target), width); - ImGui::ProgressBar(float(entry.progress) / float(found->target), {width, 7.F}, ""); + AchievementProgressBar(width, float(entry.progress) / float(found->target)); } - if (!entry.unlocked && SettingsButton(state->pinned == found->id ? "Unpin goal" : "Pin goal")) - ach::pin(state->pinned == found->id ? "" : found->id); + if (!entry.unlocked && SettingsButton(state.pinned == found->id ? "Unpin goal" : "Pin goal")) + ach::pin(state.pinned == found->id ? "" : found->id); if (!entry.unlocked && found->restorable && entry.progress >= found->target) DetailText( "This milestone is already present in your save. Settings lets you recognise existing progress explicitly.", @@ -310,119 +374,206 @@ void DrawAchievementsPage(float width) { found->kind == ach::Kind::TimeTrial)) DetailText("Original course only. Custom courses and custom cups do not count for this goal.", width, kSetMuted); + PaddockGap(14.F); + if (SettingsButton("Back to gallery") || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) { + g_achievement_focus_row = g_achievement_detail; + ImGui::CloseCurrentPopup(); + } + EndSettingsDialog(); + } +} + +void DrawAchievementGallery(float width, const ach::View& state, const std::vector& definitions) { + const auto pinned = std::ranges::find(definitions, state.pinned, &ach::Definition::id); + const std::string footer = pinned == definitions.end() ? "Select a badge to see how to unlock it." + : "Pinned goal: " + pinned->title; + const auto footer_type = PaddockReading(14.F, false, 1.35F); + const float footer_height = PaddockTextHeight(footer_type, footer, width); + const float height = std::max(112.F, PanelFooterBounds(ImGui::GetCurrentWindow()).Max.y - + ImGui::GetCursorScreenPos().y - footer_height - 24.F); + PaddockGap(10.F); + bool opened = false; + if (std::exchange(g_achievement_reset_scroll, false)) + ImGui::SetNextWindowScroll({-1.F, 0.F}); + if (ImGui::BeginChild("##badge-gallery", {width, height}, false, + ImGuiWindowFlags_NavFlattened | ImGuiWindowFlags_NoBackground)) { + LibraryNavigationScrollWindow(ImGui::GetCurrentWindow()); + std::vector entries; + const auto lower = [](std::string text) { + std::transform(text.begin(), text.end(), text.begin(), + [](unsigned char c) { return char(std::tolower(c)); }); + return text; + }; + const auto search = lower(g_achievement_search.data()); + for (unsigned i = 0; i < definitions.size(); ++i) { + const auto& badge = definitions[i]; + const auto& entry = state.entries[i]; + if ((g_achievement_filter == 1 && entry.unlocked) || (g_achievement_filter == 2 && !entry.unlocked) || + (!g_achievement_category.empty() && badge.category != g_achievement_category)) + continue; + if (search.empty() || lower(badge.title + " " + badge.description + " " + badge.category).find(search) != + std::string::npos) + entries.push_back(i); + } + if (g_achievement_sort == 1) { + std::stable_sort(entries.begin(), entries.end(), + [&](unsigned a, unsigned b) { return state.entries[a].when > state.entries[b].when; }); + } else if (g_achievement_sort == 2) { + const auto completion = [&](unsigned i) { + return state.entries[i].unlocked ? 1.F : AchievementHasProgress(definitions[i]) + ? std::clamp(float(state.entries[i].progress) / float(definitions[i].target), 0.F, 1.F) + : 0.F; + }; + std::stable_sort(entries.begin(), entries.end(), + [&](unsigned a, unsigned b) { return completion(a) > completion(b); }); + } + constexpr float gap = 9.F; + const float available = ImGui::GetContentRegionAvail().x - 4.F; + const std::size_t columns = available >= 660.F ? 3U : available >= 420.F ? 2U : 1U; + const float card_width = std::floor((available - gap * float(columns - 1U)) / float(columns)); + const auto at = ImGui::GetCursorScreenPos(); + const auto title = PaddockReading(16.F, true, 1.17F); + float y = at.y; + for (std::size_t row = 0; row < entries.size(); row += columns) { + const auto end = std::min(row + columns, entries.size()); + float card_height = 109.F; + for (std::size_t index = row; index < end; ++index) { + const auto& badge = definitions[entries[index]]; + card_height = std::max(card_height, 87.F + PaddockTextHeight(title, badge.title, card_width - 22.F)); + } + for (std::size_t index = row; index < end; ++index) { + const unsigned id = entries[index]; + const auto& badge = definitions[id]; + ImGui::SetCursorScreenPos({at.x + float(index - row) * (card_width + gap), y}); + if (DrawAchievementGalleryCard(badge, state.entries[id], card_width, card_height, state.pinned == badge.id)) { + g_achievement_detail = badge.id; + opened = true; + } + } + y += card_height + gap; + } + if (entries.empty()) + DetailText("No achievements match those filters.", available, kSetMuted); + } + ImGui::EndChild(); + PaddockGap(6.F); + PaddockText(footer_type, PaddockRgb(kSetMuted), footer, width); + if (opened) + ImGui::OpenPopup("##achievement-detail"); + DrawAchievementDetail(state, definitions); +} + +void DrawAchievementsPage(float width) { + const auto state = ach::view(); + const auto& definitions = ach::catalogue(); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); + const auto header = ImGui::GetCursorScreenPos(); + DrawPageHeading("ACHIEVEMENTS"); + const auto below = ImGui::GetCursorScreenPos(); + const float back_width = SettingsButtonWidth("Back to Play"); + if (width >= 440.F) + ImGui::SetCursorScreenPos({header.x + width - back_width, header.y + 11.F}); + if (PaddockTextLink("Back to Play")) + g_page_navigation_request = kPagePlay; + ImGui::SetCursorScreenPos({header.x, std::max(below.y, ImGui::GetItemRectMax().y) + 10.F}); + if (g_achievement_settings) { + DrawAchievementPreferences(width, *state); } else { - if (ImGui::IsKeyPressed(ImGuiKey_GamepadL1, false)) - g_achievement_filter = (g_achievement_filter + 2) % 3; - if (ImGui::IsKeyPressed(ImGuiKey_GamepadR1, false)) - g_achievement_filter = (g_achievement_filter + 1) % 3; - DumpActionRow actions(width); - for (int i = 0; i < 3; ++i) { - const char* labels[]{"All", "Locked", "Unlocked"}; - if (actions.Button(labels[i], false, - i == g_achievement_filter ? SettingsButtonTone::Selected : SettingsButtonTone::Plain)) - g_achievement_filter = i; + { + PaddockBox collection(width, {12.F, 10.F}); + const float inner = collection.Inner(); + const auto at = ImGui::GetCursorScreenPos(); + const auto text = std::to_string(state->unlocked) + " / " + std::to_string(definitions.size()) + " unlocked"; + const auto type = PaddockReading(15.F, true, 1.22F); + const float text_width = PaddockMeasure(type, text) + 1.F; + PaddockText(type, PaddockRgb(kSetText), text, inner); + if (inner >= text_width + 112.F) { + ImGui::SetCursorScreenPos({at.x + text_width + 12.F, at.y + (type.line - 6.F) * .5F}); + AchievementProgressBar(inner - text_width - 12.F, float(state->unlocked) / float(definitions.size())); + ImGui::SetCursorScreenPos({at.x, at.y + type.line}); + ImGui::Dummy({inner, 0.F}); + } else { + PaddockGap(4.F); + AchievementProgressBar(inner, float(state->unlocked) / float(definitions.size())); + } + collection.End([](ImDrawList* draw, ImVec2 min, ImVec2 max) { + PaddockPanel(draw, min, max, + {PaddockRound(10.F), PaddockRgb(0x0C293A), PaddockRgb(kSetBorder), 1.F}); + }); + } + if (!state->error.empty()) + DetailText(state->error, width, 0xFFAB72); + else if (state->status != "Saved on this device") + DetailText(state->status, width, kSetMuted); + PaddockGap(10.F); + const int previous_filter = g_achievement_filter; + if (!ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)) { + if (ImGui::IsKeyPressed(ImGuiKey_GamepadL1, false)) + g_achievement_filter = (g_achievement_filter + 2) % 3; + if (ImGui::IsKeyPressed(ImGuiKey_GamepadR1, false)) + g_achievement_filter = (g_achievement_filter + 1) % 3; } - if (actions.Button("Settings")) + const auto tabs = ImGui::GetCursorScreenPos(); + const float settings_width = SettingsButtonWidth("Settings"); + const bool inline_settings = width >= 440.F; + const int filter = SettingsSectionSigns({"ALL", "LOCKED", "UNLOCKED"}, g_achievement_filter, + width - (inline_settings ? settings_width + 9.F : 0.F), true); + if (filter >= 0) + g_achievement_filter = filter; + g_achievement_reset_scroll |= previous_filter != g_achievement_filter; + const float after_tabs = ImGui::GetCursorScreenPos().y; + if (inline_settings) + ImGui::SetCursorScreenPos({tabs.x + width - settings_width, tabs.y}); + if (SettingsButton("Settings", settings_width)) g_achievement_settings = true; - PaddockGap(12); - ImGui::SetNextItemWidth(width >= 240.F ? width - 115.F : width); - ImGui::InputTextWithHint("##achievement-search", "Find an achievement...", g_achievement_search.data(), - g_achievement_search.size()); - if (width >= 240.F) - ImGui::SameLine(); - if (SettingsButton("Keyboard", 100.F)) + ImGui::SetCursorScreenPos({tabs.x, std::max(after_tabs, ImGui::GetItemRectMax().y) + 9.F}); + const bool wide = width >= 620.F; + constexpr float gap = 9.F; + const float field = wide ? std::clamp(width * .25F, 210.F, 240.F) : (width - gap) * .5F; + const float search_width = wide ? width - 2.F * (field + gap) : width; + const auto toolbar = ImGui::GetCursorScreenPos(); + SettingsLabel("Search achievements", search_width); + const auto search = PaddockSearch("achievements", g_achievement_search.data(), g_achievement_search.size(), + "Find an achievement...", search_width); + g_achievement_reset_scroll |= search == PaddockFieldResult::Edited; + if (search == PaddockFieldResult::GamepadActivated) { RequestCustomTextKeyboard("Find an achievement", g_achievement_search.data(), g_achievement_search.size(), [](const std::string& value) { std::snprintf(g_achievement_search.data(), g_achievement_search.size(), "%s", value.c_str()); + g_achievement_reset_scroll = true; }); - PaddockGap(10); - std::vector groups{"All categories"}; - for (const auto& d : definitions) - if (std::find(groups.begin(), groups.end(), d.category) == groups.end()) - groups.push_back(d.category); - ImGui::SetNextItemWidth(std::min(width, 260.F)); - if (ImGui::BeginCombo("##achievement-category", - g_achievement_category.empty() ? "All categories" : g_achievement_category.c_str())) { - for (unsigned i = 0; i < groups.size(); ++i) - if (ImGui::Selectable(groups[i].c_str(), g_achievement_category == groups[i])) - g_achievement_category = i ? groups[i] : ""; - ImGui::EndCombo(); - } - const char* sorts[]{"Collection order", "Recently unlocked", "Most progress"}; - ImGui::SetNextItemWidth(std::min(width, 260.F)); - ImGui::Combo("##achievement-sort", &g_achievement_sort, sorts, 3); - std::vector entries; - std::string search = g_achievement_search.data(); - std::transform(search.begin(), search.end(), search.begin(), - [](unsigned char c) { return char(std::tolower(c)); }); - for (unsigned i = 0; i < definitions.size(); ++i) { - const auto& d = definitions[i]; - const auto& e = state->entries[i]; - if ((g_achievement_filter == 1 && e.unlocked) || (g_achievement_filter == 2 && !e.unlocked) || - (!g_achievement_category.empty() && d.category != g_achievement_category)) - continue; - auto text = d.title + " " + d.description; - std::transform(text.begin(), text.end(), text.begin(), - [](unsigned char c) { return char(std::tolower(c)); }); - if (!search.empty() && text.find(search) == std::string::npos) - continue; - entries.push_back(i); } - if (g_achievement_sort) - std::stable_sort(entries.begin(), entries.end(), [&](unsigned a, unsigned b) { - return g_achievement_sort == 1 ? state->entries[a].when > state->entries[b].when - : double(state->entries[a].progress) / definitions[a].target > - double(state->entries[b].progress) / definitions[b].target; - }); - PaddockGap(12); - if (entries.empty()) - DetailText("No achievements match those filters.", width, kSetMuted); - const auto heading = PaddockReading(17.F, true, 1.3F), body = PaddockReading(14.F, false, 1.3F); - for (const auto index : entries) { - const auto& d = definitions[index]; - const auto& e = state->entries[index]; - ImGui::PushID(d.id.c_str()); - const float badge = 48.F, text_width = std::max(50.F, width - 88.F); - const auto wrapped = body.font->CalcTextSizeA(body.size, FLT_MAX, text_width, d.description.c_str()); - const auto title_size = heading.font->CalcTextSizeA(heading.size, FLT_MAX, text_width, d.title.c_str()); - const float height = std::max(90.F, title_size.y + wrapped.y + 43.F); - if (g_achievement_focus_row == d.id) { - ImGui::SetKeyboardFocusHere(); - g_achievement_focus_row.clear(); + const float search_bottom = ImGui::GetItemRectMax().y; + const float category_x = wide ? toolbar.x + search_width + gap : toolbar.x; + const float filters_y = wide ? toolbar.y : search_bottom + gap; + std::vector categories{{"All categories", {}, false}}; + int selected = 0; + for (const auto& badge : definitions) { + if (std::ranges::find(categories, badge.category, &SettingsChoice::label) == categories.end()) { + if (g_achievement_category == badge.category) + selected = static_cast(categories.size()); + categories.push_back({badge.category, {}, false}); } - const auto at = ImGui::GetCursorScreenPos(); - if (ImGui::Button("##open", {width, height})) { - g_achievement_detail = d.id; - g_achievement_return_scroll = ImGui::GetScrollY(); - g_achievement_focus_detail = true; - ImGui::SetScrollY(0); - } - auto* draw = ImGui::GetWindowDrawList(); - draw->AddRectFilled(at, {at.x + width, at.y + height}, PaddockRgb(0x10364A), 12); - draw->AddRect(at, {at.x + width, at.y + height}, - PaddockRgb(ImGui::IsItemFocused() || ImGui::IsItemHovered() ? 0xFFCB66 : 0x296B70), 12); - DrawAchievementBadge({at.x + 12, at.y + 14}, badge, AchievementBadge(d), e.unlocked); - const ImVec2 text{at.x + 74, at.y + 12}; - draw->AddText(heading.font, heading.size, text, PaddockRgb(0xFFF6DA), d.title.c_str(), nullptr, text_width); - draw->AddText(body.font, body.size, {text.x, text.y + title_size.y + 5}, PaddockRgb(0xB0C9CC), - d.description.c_str(), nullptr, text_width); - const std::string status = e.unlocked ? (e.restored ? "Recognised" : "Unlocked") - : e.progress > 0 ? std::to_string(e.progress) + " / " + std::to_string(d.target) - : "Locked"; - draw->AddText(body.font, body.size, {text.x, at.y + height - body.line - 8}, - PaddockRgb(e.unlocked ? 0x42D6BC : 0xB0C9CC), status.c_str()); - ImGui::PopID(); - PaddockGap(8); } - DetailText("A: Open B: Back LB / RB: Filter", width, kSetMuted); - } - if (!state->pinned.empty()) { - const auto found = - std::find_if(definitions.begin(), definitions.end(), [&](auto& d) { return d.id == state->pinned; }); - if (found != definitions.end()) - DetailText("Pinned: " + found->title, width, kSetMuted); + ImGui::SetCursorScreenPos({category_x, filters_y}); + ImGui::BeginGroup(); + if (SettingsDropdown("##achievement-category", "Category", &selected, categories, field, false, {}, 44.F)) { + g_achievement_category = selected ? categories[selected].label : ""; + g_achievement_reset_scroll = true; + } + ImGui::EndGroup(); + ImGui::SetCursorScreenPos({category_x + field + gap, filters_y}); + ImGui::BeginGroup(); + g_achievement_reset_scroll |= + SettingsDropdown("##achievement-sort", "Sort by", &g_achievement_sort, + {"Collection order", "Recently unlocked", "Most progress"}, field, false, {}, 44.F); + ImGui::EndGroup(); + ImGui::SetCursorScreenPos({toolbar.x, std::max(search_bottom, ImGui::GetItemRectMax().y)}); + ImGui::Dummy({width, 0.F}); + DrawAchievementGallery(width, *state, definitions); } + ImGui::PopStyleVar(); if (g_achievement_reset) { ImGui::OpenPopup("Reset achievements##confirm"); g_achievement_reset = false; diff --git a/runtime-recomp/src/game/cloud_saves/jobs.inl b/runtime-recomp/src/game/cloud_saves/jobs.inl new file mode 100644 index 00000000..5ebb86a6 --- /dev/null +++ b/runtime-recomp/src/game/cloud_saves/jobs.inl @@ -0,0 +1,26 @@ +std::string EnabledCloudSaveAccount() { + const auto profile = dkr::store::service().view(); + auto account = dkr::store::text(profile->user, "id", 160); + return account == profile->cloud_saves_account ? std::move(account) : std::string{}; +} + +bool RunCloudSaveSync(std::string account, dkr::cloud_saves::SyncScope scope = dkr::cloud_saves::SyncScope::All) { + return BeginSharedSaveJob( + [account = std::move(account), scope](std::string&) { + dkr::store::service().sync_cloud_saves(account, scope); + return true; + }, + "Cloud Saves checked. See Save Manager for details."); +} + +void ToggleCloudSaves(std::string account, bool enabled) { + BeginSharedSaveJob( + [account = std::move(account), enabled](std::string&) { + auto& service = dkr::store::service(); + service.set_cloud_saves(account, enabled); + if (enabled) + service.sync_cloud_saves(account); + return true; + }, + enabled ? "Cloud Saves enabled on this device." : "Cloud Saves paused on this device."); +} diff --git a/runtime-recomp/src/game/cloud_saves/play_ui.inl b/runtime-recomp/src/game/cloud_saves/play_ui.inl new file mode 100644 index 00000000..9bd49259 --- /dev/null +++ b/runtime-recomp/src/game/cloud_saves/play_ui.inl @@ -0,0 +1,125 @@ +void DrawCloudStatusGlyph(ImDrawList* draw, ImVec2 centre, dkr::cloud_saves::SyncStatus status, bool enabled) { + using dkr::cloud_saves::SyncStatus; + const bool animate = !dkr::runtime::achievements::view()->preferences.reduced_motion; + const float phase = animate ? float(std::fmod(ImGui::GetTime(), 10.0)) * 6.2831853F : 0.F; + const auto point = [&](float x, float y) { return ImVec2{centre.x + x, centre.y + y}; }; + const unsigned colour = status == SyncStatus::Synced ? 0x5CE1B8 + : status == SyncStatus::Error ? 0xFFB366 + : status == SyncStatus::Unreachable ? 0x8EBDD3 + : enabled ? 0xB9E7F5 + : 0x829EAB; + const auto ink = PaddockCol(colour); + draw->PathLineTo(point(-7.F, 5.F)); + draw->PathBezierCubicCurveTo(point(-15.F, 5.F), point(-15.F, -5.F), point(-8.F, -5.F)); + draw->PathBezierCubicCurveTo(point(-5.F, -13.F), point(5.F, -12.F), point(8.F, -5.F)); + draw->PathBezierCubicCurveTo(point(15.F, -5.F), point(15.F, 5.F), point(8.F, 5.F)); + draw->PathStroke(ink, ImDrawFlags_Closed, 1.6F); + + const auto badge = point(8.F, 5.F); + if (status == SyncStatus::Unreachable) { + const float offset = std::sin(phase * 0.2F) * 1.8F; + const auto first = point(-11.F + offset, 9.F); + const auto last = point(11.F + offset, -10.F); + draw->AddLine(first, last, PaddockCol(0x0A2938), 4.F); + draw->AddLine(first, last, ink, 2.F); + } else if (status != SyncStatus::Idle) { + draw->AddCircleFilled(badge, 6.F, PaddockCol(0x0A2938)); + if (status == SyncStatus::Syncing) { + draw->PathArcTo(badge, 4.5F, phase, phase + 4.5F, 14); + draw->PathStroke(ink, 0, 1.7F); + } else if (status == SyncStatus::Error) { + const float radius = 4.8F + std::sin(phase * 0.2F) * 0.9F; + draw->AddCircle(badge, radius, ink, 16, 1.25F); + draw->AddLine(point(8.F, 2.3F), point(8.F, 5.3F), ink, 1.4F); + draw->AddCircleFilled(point(8.F, 7.2F), 0.8F, ink); + } else { + const ImVec2 tick[]{point(4.5F, 5.F), point(7.F, 7.4F), point(12.F, 2.3F)}; + draw->AddPolyline(tick, 3, ink, 0, 1.8F); + } + } +} + +void CloudControlTooltip(std::string_view action, std::string_view detail = {}) { + if (!ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) || action.empty()) + return; + const dkr::runtime::ui::ScopedDialogStyle style({12.F, 8.F}, 10.F); + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + 275.F); + ImGui::TextUnformatted(action.data(), action.data() + action.size()); + if (!detail.empty() && detail != action) + ImGui::TextUnformatted(detail.data(), detail.data() + detail.size()); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); +} + +constexpr float kPlayCloudControlHeight = 36.F; +constexpr float kPlayCloudGap = 6.F; +constexpr float kPlayCloudIconWidth = 42.F; + +float PlayCloudSwitchWidth() { + return std::ceil(PaddockMeasure(PaddockReading(13.F, true, 1.3F), dkr::localisation::source("Cloud Saves"))) + 61.F; +} + +void DrawPlayCloudSaves(float width, bool locked) { + using dkr::cloud_saves::SyncStatus; + auto& service = dkr::store::service(); + const auto view = service.view(); + const auto account = dkr::store::text(view->user, "id", 160); + const bool enabled = !account.empty() && view->cloud_saves_account == account; + const auto status = account.empty() ? SyncStatus::Idle : view->cloud_sync; + const bool busy = SharedSaveBusy() || status == SyncStatus::Syncing; + const bool blocked = locked || busy || view->signing_in; + const auto caption = dkr::localisation::source("Cloud Saves"); + const auto type = PaddockReading(13.F, true, 1.3F); + const bool inline_icon = width >= kPlayCloudIconWidth + kPlayCloudGap + 92.F; + const float switch_width = std::min(width - (inline_icon ? kPlayCloudIconWidth + kPlayCloudGap : 0.F), + PlayCloudSwitchWidth()); + + ImGui::BeginDisabled(blocked); + const auto toggle = PaddockBeginPress("##play-cloud-opt-in", {switch_width, kPlayCloudControlHeight}); + auto* draw = ImGui::GetWindowDrawList(); + draw->AddRectFilled(toggle.min, toggle.max, PaddockCol(toggle.hovered ? 0x153C4C : 0x0A2938), 8.F); + draw->AddRect(toggle.min, toggle.max, PaddockCol(0x375F71), 8.F); + const ImVec2 track{toggle.min.x + 10.F, toggle.min.y + 9.F}; + draw->AddRectFilled(track, {track.x + 34.F, track.y + 18.F}, PaddockCol(enabled ? 0x12B99B : 0x32576A), 9.F); + draw->AddCircleFilled({track.x + (enabled ? 25.F : 9.F), track.y + 9.F}, 6.5F, PaddockCol(0xFFF3C9), 16); + const auto label = PaddockEllipsize(type, caption, switch_width - 61.F); + PaddockDrawRun(draw, type, {toggle.min.x + 52.F, toggle.min.y + (kPlayCloudControlHeight - type.line) * 0.5F}, + PaddockCol(0xFFF6DA), label.data(), label.data() + label.size()); + PaddockEndPress(toggle, 8.F); + ImGui::EndDisabled(); + const char* toggle_hint = view->signing_in ? "Waiting for Discord sign-in." + : locked ? "Return to the launcher to change Cloud Saves." + : account.empty() ? "Sign in with Discord to enable Cloud Saves." + : enabled ? "Pause Cloud Saves on this device." + : "Enable Cloud Saves on this device."; + CloudControlTooltip(dkr::localisation::source(toggle_hint)); + if (toggle.pressed) { + if (account.empty()) + service.login(); + else + ToggleCloudSaves(account, !enabled); + } + + if (inline_icon) + ImGui::SameLine(0.F, kPlayCloudGap); + ImGui::BeginDisabled(blocked || !enabled); + const auto sync = + PaddockBeginPress("##play-cloud-sync", {std::min(width, kPlayCloudIconWidth), kPlayCloudControlHeight}); + draw->AddRectFilled(sync.min, sync.max, PaddockCol(sync.hovered ? 0x153C4C : 0x0A2938), 8.F); + draw->AddRect(sync.min, sync.max, PaddockCol(0x375F71), 8.F); + DrawCloudStatusGlyph(draw, {(sync.min.x + sync.max.x) * 0.5F, (sync.min.y + sync.max.y) * 0.5F}, status, enabled); + PaddockEndPress(sync, 8.F); + ImGui::EndDisabled(); + + const char* sync_hint = status == SyncStatus::Syncing ? "Syncing Cloud Saves..." + : locked ? "Return to the launcher to sync." + : busy ? "Waiting for the current save operation." + : enabled ? "Sync Cloud Saves now" + : "Enable Cloud Saves to sync."; + CloudControlTooltip(dkr::localisation::source(sync_hint), + account.empty() ? std::string_view{} : dkr::localisation::source(view->cloud_saves_status)); + if (sync.pressed) + RunCloudSaveSync(account); +} + diff --git a/runtime-recomp/src/game/cloud_saves/progress.hpp b/runtime-recomp/src/game/cloud_saves/progress.hpp new file mode 100644 index 00000000..6a0d3774 --- /dev/null +++ b/runtime-recomp/src/game/cloud_saves/progress.hpp @@ -0,0 +1,107 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dkr::cloud_saves { +struct ProgressBatch { + unsigned account_generation; + std::set slots; +}; + +class ProgressWrites { + public: + using Clock = std::chrono::steady_clock; + using Routes = std::vector>; + + void configure(Routes next) { + std::scoped_lock lock(mutex_); + routes_ = std::move(next); + pending_.clear(); + } + void gameplay(bool active) { + std::scoped_lock lock(mutex_); + gameplay_ = active; + if (!active) { + toast_until_ = 0; + next_toast_ = {}; + } + } + void account(std::optional generation) { + std::scoped_lock lock(mutex_); + if (generation == account_) + return; + account_ = generation; + pending_.clear(); + retry_at_ = {}; + changed_.notify_all(); + } + void committed(const std::filesystem::path& path, Clock::time_point now = Clock::now()) { + std::scoped_lock lock(mutex_); + if (!gameplay_) + return; + if (now >= next_toast_) { + toast_until_ = milliseconds(now + std::chrono::milliseconds(850)); + next_toast_ = now + std::chrono::milliseconds(1050); + } + if (account_) { + for (const auto& [candidate, slot] : routes_) { + if (candidate == path) { + pending_.insert(slot); + changed_.notify_one(); + break; + } + } + } + } + bool visible(Clock::time_point now = Clock::now()) const { + return milliseconds(now) < toast_until_.load(); + } + std::optional take(std::stop_token stop) { + std::unique_lock lock(mutex_); + while (!stop.stop_requested()) { + if (!changed_.wait(lock, stop, [&] { return account_ && !pending_.empty(); })) + break; + const auto account = account_; + if (changed_.wait_until(lock, stop, retry_at_, [&] { return account_ != account; })) + continue; + if (!stop.stop_requested()) + return ProgressBatch{*account, std::exchange(pending_, {})}; + } + return std::nullopt; + } + void retry(const ProgressBatch& batch) { + std::scoped_lock lock(mutex_); + if (account_ != batch.account_generation) + return; + pending_.insert(batch.slots.begin(), batch.slots.end()); + retry_at_ = Clock::now() + std::chrono::seconds(5); + changed_.notify_one(); + } + + private: + static std::int64_t milliseconds(Clock::time_point time) { + return std::chrono::duration_cast(time.time_since_epoch()).count(); + } + + std::mutex mutex_; + std::condition_variable_any changed_; + Routes routes_; + std::set pending_; + std::optional account_; + Clock::time_point retry_at_, next_toast_; + std::atomic toast_until_{0}; + bool gameplay_ = false; +}; + +inline ProgressWrites progress_writes; +} // namespace dkr::cloud_saves diff --git a/runtime-recomp/src/game/cloud_saves/sync.hpp b/runtime-recomp/src/game/cloud_saves/sync.hpp new file mode 100644 index 00000000..487f58c5 --- /dev/null +++ b/runtime-recomp/src/game/cloud_saves/sync.hpp @@ -0,0 +1,30 @@ +#pragma once +#include + +namespace dkr::cloud_saves { +enum class Action { None, Upload, Download, Defer }; +enum class SyncScope { All, PublishHostedOnline, PublishProgress }; +enum class SyncStatus { Idle, Syncing, Synced, Error, Unreachable }; + +constexpr SyncStatus sync_failure(bool transport_failed, unsigned http_status) { + const bool unavailable = (http_status >= 502 && http_status <= 504) || + (http_status >= 521 && http_status <= 524); + return transport_failed || unavailable ? SyncStatus::Unreachable : SyncStatus::Error; +} + +constexpr bool includes_slot(SyncScope scope, std::string_view key) { + return scope != SyncScope::PublishHostedOnline || key.starts_with("online-"); +} + +constexpr Action next_action(std::string_view local, std::string_view cloud, std::string_view common, + SyncScope scope = SyncScope::All) { + if (local == cloud) + return Action::None; + // A missing cloud slot can be seeded. Existing cloud progress can be + // advanced only from the copy this device last synchronized. + if (!local.empty() && (cloud.empty() || cloud == common)) + return Action::Upload; + // Publish-only syncs leave a running game or an agreed lobby seed intact. + return scope == SyncScope::All ? Action::Download : Action::Defer; +} +} // namespace dkr::cloud_saves \ No newline at end of file diff --git a/runtime-recomp/src/game/cloud_saves/ui.inl b/runtime-recomp/src/game/cloud_saves/ui.inl new file mode 100644 index 00000000..816ae9e8 --- /dev/null +++ b/runtime-recomp/src/game/cloud_saves/ui.inl @@ -0,0 +1,25 @@ +void DrawCloudSaves(float width, bool locked) { + auto& service = dkr::store::service(); + const auto view = service.view(); + const auto account = dkr::store::text(view->user, "id", 160); + if (account.empty()) { + SavesNote("Sign in with Discord to sync saves between your devices.", width); + if (SavesRaceButton("SIGN IN WITH DISCORD", 0, SavesTone::Primary, locked || view->signing_in)) + service.login(); + return; + } + const bool enabled = view->cloud_saves_account == account; + SavesNote("Existing cloud saves take priority. Progress made from a synced save is uploaded when its cloud copy is current.", width); + PaddockGap(12); + if (SavesRaceButton(enabled ? "PAUSE CLOUD SAVES" : "ENABLE CLOUD SAVES", 0, + enabled ? SavesTone::Plain : SavesTone::Primary, locked)) { + ToggleCloudSaves(account, !enabled); + } + if (!enabled) + return; + PaddockGap(12); + if (SavesRaceButton("SYNC NOW", 0, SavesTone::Primary, locked)) + RunCloudSaveSync(account); + if (!view->cloud_saves_status.empty()) + SavesNote(view->cloud_saves_status, width); +} \ No newline at end of file diff --git a/runtime-recomp/src/game/custom_tracks.cpp b/runtime-recomp/src/game/custom_tracks.cpp index 72fda942..21a128ed 100644 --- a/runtime-recomp/src/game/custom_tracks.cpp +++ b/runtime-recomp/src/game/custom_tracks.cpp @@ -84,6 +84,11 @@ bool g_auto_boot_consumed = false; std::mutex g_mutex; std::vector g_tracks; +std::vector g_replay_tracks; + +const std::vector& active_tracks_locked() { + return g_replay_tracks.empty() ? g_tracks : g_replay_tracks; +} std::array g_sections{}; std::unordered_map g_resolved_level_ids; std::filesystem::path g_directory; @@ -383,6 +388,63 @@ std::vector tracks() { return g_tracks; } +namespace { +const Entry* replay_header(const Track& track) { + if (!track.level_links.empty()) + return nullptr; + const auto header = std::find_if(track.entries.begin(), track.entries.end(), [](const auto& entry) { + return entry.section == Section::LevelHeaders; + }); + if (header == track.entries.end() || header->bytes.size() < 0xC8 || header->bytes[0] != kCustomTrackWorld || + header->bytes[0x4B] < 1 || header->bytes[0x4B] > 5 || header->bytes[0x4C] != 0) + return nullptr; + return &*header; +} +} // namespace + +unsigned replay_vehicles(const Track& track) { + const auto* header = replay_header(track); + return header ? header->bytes[0x4E] & 7U : 0; +} + +unsigned replay_laps(const Track& track) { + const auto* header = replay_header(track); + return header ? header->bytes[0x4B] : 0; +} + +std::vector installed_replay_tracks() { + std::scoped_lock lock(g_mutex); + std::vector choices; + for (const auto& track : g_tracks) + if (const auto vehicles = replay_vehicles(track)) + choices.push_back({track.id, track.name, vehicles}); + return choices; +} + +std::filesystem::path installed_replay_source(const std::string& id) { + std::scoped_lock lock(g_mutex); + const auto track = std::find_if(g_tracks.begin(), g_tracks.end(), + [&](const Track& candidate) { return candidate.id == id; }); + return track == g_tracks.end() ? std::filesystem::path{} : track->source; +} + +void begin_replay_track(Track track) { + std::scoped_lock lock(g_mutex); + g_replay_tracks.clear(); + g_replay_tracks.push_back(std::move(track)); + g_sections = {}; + g_resolved_level_ids.clear(); +} + +void retire_replay_track() { + std::scoped_lock lock(g_mutex); + if (g_replay_tracks.empty()) + return; + g_replay_tracks.clear(); + g_sections = {}; + g_resolved_level_ids.clear(); +} + std::size_t enabled_count() { std::scoped_lock lock(g_mutex); return static_cast( @@ -409,7 +471,7 @@ std::optional music_for_level(std::int32_t level_id) { if (level_id < 0) { return std::nullopt; } - for (const Track& track : g_tracks) { + for (const Track& track : active_tracks_locked()) { const auto resolved = g_resolved_level_ids.find(track.id); if (track.enabled && track.music && resolved != g_resolved_level_ids.end() && resolved->second == level_id) { return track.music; @@ -420,7 +482,7 @@ std::optional music_for_level(std::int32_t level_id) { std::optional water_for_level(std::int32_t level_id) { std::scoped_lock lock(g_mutex); - for (const auto& track : g_tracks) { + for (const auto& track : active_tracks_locked()) { const auto resolved = g_resolved_level_ids.find(track.id); if (track.enabled && track.water && resolved != g_resolved_level_ids.end() && resolved->second == level_id) return track.water; @@ -627,7 +689,7 @@ bool minimap_hidden(std::uint32_t header_offset) { return false; // Retail, or not a track's header. } const Track* track = nullptr; - for (const Track& candidate : g_tracks) { + for (const Track& candidate : active_tracks_locked()) { if (candidate.id == header->track_id) { track = &candidate; } @@ -749,9 +811,9 @@ std::int32_t track_override() { } bool owns_level_id(std::int32_t level_id) { - if (!dkr::session_content::local_assets_allowed()) - return false; std::scoped_lock lock(g_mutex); + if (g_replay_tracks.empty() && !dkr::session_content::local_assets_allowed()) + return false; return std::any_of(g_resolved_level_ids.begin(), g_resolved_level_ids.end(), [level_id](const auto& entry) { return entry.second == level_id; }); } @@ -874,7 +936,7 @@ std::vector level_links_for_object_map(std::uint32_t offset) if (entry.offset != offset || entry.track_id.empty()) { continue; } - for (const Track& track : g_tracks) { + for (const Track& track : active_tracks_locked()) { if (track.id != entry.track_id || !track.enabled) { continue; } @@ -901,7 +963,7 @@ std::int32_t level_race_type(std::int32_t level_id) { if (resolved != level_id) { continue; } - for (const Track& track : g_tracks) { + for (const Track& track : active_tracks_locked()) { if (track.id != track_id || !track.enabled) { continue; } @@ -1074,7 +1136,7 @@ std::int32_t level_model_arena_bytes(std::int32_t level_id) { if (resolved != level_id) { continue; } - for (const Track& track : g_tracks) { + for (const Track& track : active_tracks_locked()) { if (track.id != track_id) { continue; } @@ -1199,11 +1261,12 @@ std::vector build_extended_table(Section section, const std::int32 std::fprintf(stderr, "[custom-tracks] applying deferred rescan\n"); scan_locked(g_directory); } - if (!dkr::session_content::local_assets_allowed()) { + if (g_replay_tracks.empty() && !dkr::session_content::local_assets_allowed()) { const std::vector vanilla; return assemble_table(section, retail_table, vanilla, g_sections, g_resolved_level_ids, table_words); } - return assemble_table(section, retail_table, g_tracks, g_sections, g_resolved_level_ids, table_words); + return assemble_table(section, retail_table, active_tracks_locked(), g_sections, g_resolved_level_ids, + table_words); } PreparedTracks prepare_tracks(std::vector tracks, const std::array, 7>& tables) { @@ -1301,7 +1364,7 @@ PreparedTracks prepare_tracks(std::vector tracks, const std::array installed_replay_tracks(); +[[nodiscard]] std::filesystem::path installed_replay_source(const std::string& id); +[[nodiscard]] unsigned replay_vehicles(const Track& track); +[[nodiscard]] unsigned replay_laps(const Track& track); +// Solo replay assets are frozen separately from the player's enabled library. +// Begin before loading guest resources and retire after the guest has joined. +void begin_replay_track(Track track); +void retire_replay_track(); [[nodiscard]] std::size_t enabled_count(); // Transient selection; library UI uses the persistent, error-reporting overload. void set_enabled(const std::string& id, bool enabled); diff --git a/runtime-recomp/src/game/dialog_style.hpp b/runtime-recomp/src/game/dialog_style.hpp new file mode 100644 index 00000000..ce3000c9 --- /dev/null +++ b/runtime-recomp/src/game/dialog_style.hpp @@ -0,0 +1,62 @@ +#pragma once + +#ifndef IMGUI_VERSION +#include "imgui.h" +#endif + +namespace dkr::runtime::ui { + +// The Launcher and Overlay shells draw their own edges and use zero window +// padding. Give separate dialogs a surface of their own at Begin time. +class ScopedDialogStyle { + public: + explicit ScopedDialogStyle(ImVec2 padding = {18.0F, 14.0F}, float rounding = 16.0F) { + constexpr ImVec4 surface{0.043F, 0.14F, 0.20F, 0.98F}; + constexpr ImVec4 title{0.04F, 0.25F, 0.35F, 1.0F}; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, padding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, rounding); + ImGui::PushStyleVar(ImGuiStyleVar_PopupRounding, rounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0F); + ImGui::PushStyleVar(ImGuiStyleVar_PopupBorderSize, 1.0F); + ImGui::PushStyleColor(ImGuiCol_WindowBg, surface); + ImGui::PushStyleColor(ImGuiCol_PopupBg, surface); + ImGui::PushStyleColor(ImGuiCol_TitleBg, title); + ImGui::PushStyleColor(ImGuiCol_TitleBgActive, title); + ImGui::PushStyleColor(ImGuiCol_TitleBgCollapsed, title); + ImGui::PushStyleColor(ImGuiCol_Border, {0.22F, 0.44F, 0.51F, 1.0F}); + } + + ~ScopedDialogStyle() { + ImGui::PopStyleColor(6); + ImGui::PopStyleVar(5); + } + + ScopedDialogStyle(const ScopedDialogStyle&) = delete; + ScopedDialogStyle& operator=(const ScopedDialogStyle&) = delete; +}; + +inline bool begin_dialog_modal(const char* name, bool* open, ImGuiWindowFlags flags, ImVec2 padding = {18.0F, 14.0F}) { + if (!ImGui::IsPopupOpen(name)) + return ImGui::BeginPopupModal(name, open, flags); + const ScopedDialogStyle style(padding); + return ImGui::BeginPopupModal(name, open, flags); +} + +inline bool begin_dialog_window(const char* name, bool* open, ImGuiWindowFlags flags) { + const ScopedDialogStyle style; + return ImGui::Begin(name, open, flags); +} + +inline bool begin_dialog_popup(const char* name, ImGuiWindowFlags flags = 0) { + if (!ImGui::IsPopupOpen(name)) + return ImGui::BeginPopup(name, flags); + const ScopedDialogStyle style({14.0F, 12.0F}, 12.0F); + return ImGui::BeginPopup(name, flags); +} + +inline bool begin_dialog_tooltip() { + const ScopedDialogStyle style({12.0F, 8.0F}, 10.0F); + return ImGui::BeginTooltip(); +} + +} // namespace dkr::runtime::ui diff --git a/runtime-recomp/src/game/f3ddkr_rt64.cpp b/runtime-recomp/src/game/f3ddkr_rt64.cpp index e24a5f4d..e74d0962 100644 --- a/runtime-recomp/src/game/f3ddkr_rt64.cpp +++ b/runtime-recomp/src/game/f3ddkr_rt64.cpp @@ -6,6 +6,7 @@ #include "camera_rt64.hpp" #include "f3ddkr_execution_policy.hpp" #include "postrace_viewport_rt64.hpp" +#include "time_trial/session.hpp" #include "interpolation_state_policy.hpp" #include "hud_layout_policy.hpp" @@ -253,7 +254,7 @@ std::uint32_t PhysicalAddress(RT64::RSP& rsp, std::uint32_t address) { void SelectInterpolationGroup(RT64::RSP& rsp, std::uint32_t id, bool interpolate_vertices = false, bool interpolate_texcoords = false, bool interpolate_tiles = false, - std::uint8_t aspect_mode = G_EX_ASPECT_AUTO, bool preserve_vertex_interpolation = false, + std::uint8_t aspect_mode = G_EX_ASPECT_AUTO, bool preserve_identity = false, std::uint8_t water_scroll_tag = 0U, bool native_visual = false) { auto current_menu = ReadU32(rsp.state->RDRAM, current_menu_id_address()); #if defined(DKR_WATER_QUALIFICATION) @@ -266,7 +267,7 @@ void SelectInterpolationGroup(RT64::RSP& rsp, std::uint32_t id, bool interpolate #endif interpolate_tiles = dkr::runtime::interpolation::effective_tile_interpolation(interpolate_tiles, current_menu); const bool task_interpolation_allowed = dkr::runtime::presentation::task_interpolation_allowed(); - if (!task_interpolation_allowed && !preserve_vertex_interpolation) { + if (!task_interpolation_allowed && !preserve_identity) { id = G_EX_ID_IGNORE; interpolate_vertices = false; interpolate_texcoords = false; @@ -445,6 +446,7 @@ struct dkr::runtime::F3DDKRRT64Bridge::StateData { std::size_t hud_alignment_depth = 0U; struct HudWidgetScope { hud::groups::Transform transform; + std::uint32_t motion_identity = presentation::kIgnoredIdentity; }; std::array hud_widgets{}; std::size_t hud_widget_depth = 0; @@ -1303,8 +1305,12 @@ void dkr::runtime::F3DDKRRT64Bridge::FinishShadowScope(RT64::State* state) { // the shadow owner remains the same. The fixed canonical stream and // distributed dormant positions make that a bounded geometry morph; // topology diagnostics must never toggle interpolation for the page. - const bool interpolate_page_vertices = + const bool has_shadow_identity = dkr::runtime::presentation::shadow_page_vertex_interpolation(shadow_group.identity); + // Sequential export interpolates the camera and kart, so their + // canonical shadow vertices must move on the same sub-frame too. + const bool interpolate_page_vertices = + has_shadow_identity && (!time_trial::watching() || time_trial::exporting_video()); if (ShadowTraceEnabled() && page_drawn && (!interpolate_page_vertices || page_history.topology_signature != topology_signature)) { @@ -1409,7 +1415,7 @@ void dkr::runtime::F3DDKRRT64Bridge::FinishShadowScope(RT64::State* state) { SelectInterpolationGroup(rsp, dkr::runtime::presentation::make_shadow_page_group_identity( shadow_group.identity, page, history->interpolation_epoch), - interpolate_page_vertices, false, false, shadow_aspect, interpolate_page_vertices, 0U, + interpolate_page_vertices, false, false, shadow_aspect, has_shadow_identity, 0U, data.camera_shadow.has_value()); rsp.modelViewProjChanged = true; auto& workload = state->ext.workloadQueue->workloads[state->ext.workloadQueue->writeCursor]; @@ -2077,11 +2083,16 @@ void dkr::runtime::F3DDKRRT64Bridge::ApplyPresentationMarkers(RT64::State* state for (std::size_t index = 0U; index < markers.count; ++index) { const auto& marker = markers.markers[index]; if (marker.kind == PresentationMarkerKind::CameraWorldBegin || - marker.kind == PresentationMarkerKind::CameraWorldEnd) + marker.kind == PresentationMarkerKind::CameraWorldEnd) { + if (auto* online = active_->data_->online_view) + online->ghost_world_boundary(*state, marker.token, marker.kind == PresentationMarkerKind::CameraWorldEnd); continue; + } if (active_->data_->camera && active_->data_->camera->replaced_command(std::uint32_t(command - rdram_begin)) && - marker.kind != PresentationMarkerKind::SplitViewport && marker.kind != PresentationMarkerKind::HudPass && - marker.kind != PresentationMarkerKind::HudWidget && marker.kind != PresentationMarkerKind::HudRect) + marker.kind != PresentationMarkerKind::SplitViewport && + marker.kind != PresentationMarkerKind::PostraceFullViewport && + marker.kind != PresentationMarkerKind::HudPass && marker.kind != PresentationMarkerKind::HudWidget && + marker.kind != PresentationMarkerKind::HudRect) continue; if (marker.kind == PresentationMarkerKind::TrackSelectPreview) { auto& data = *active_->data_; @@ -2121,6 +2132,10 @@ void dkr::runtime::F3DDKRRT64Bridge::ApplyPresentationMarkers(RT64::State* state auto& scope = data.hud_widgets[data.hud_widget_depth++]; scope.transform = data.online_view && data.online_view->focused_hud() ? hud::groups::Transform{} : marker.hud_transform; + scope.motion_identity = + marker.token != 0 ? presentation::normalise_identity(0x54544855U ^ + (presentation::task_scene_generation() * 0x9E3779B9U) ^ marker.token) + : presentation::kIgnoredIdentity; const auto& t = scope.transform; state->rdp->pushScissor(); auto& clip = state->rdp->scissorRectStack[state->rdp->scissorStackSize - 1]; @@ -2670,13 +2685,40 @@ void dkr::runtime::F3DDKRRT64Bridge::HudTextureRect(RT64::State* state, RT64::Di const auto rect = hud::groups::transform_rectangle(t, ulx, uly, lrx, lry, static_cast(command->p1(16, 16)), static_cast(command->p1(0, 16)), data.hud_rect_bias); - state->rdp->drawTexRect(rect.ulx, rect.uly, rect.lrx, rect.lry, tile, s, uv, rect.dsdx, rect.dtdy, flip); + auto& rdp = *state->rdp; + const auto& active_clip = rdp.scissorRectStack[rdp.scissorStackSize - 1]; + const bool expand_clip = time_trial::watching() && data.world_window_aspect > 4.F / 3.F && + active_clip.lry > active_clip.uly && + rdp.scissorStackSize < RDP_EXTENDED_STACK_SIZE && + !dkr::sdk2::hud_hidden.load(std::memory_order_relaxed); + if (expand_clip) { + // Widen the text rectangle's clip without changing the projection + // and clip used by the minimap, animated HUD sprites or scene. + const auto gutter = + static_cast(std::lround(4.F * hud::fullscreen_gutter_authored(data.world_window_aspect))); + rdp.pushScissor(); + const auto stack = rdp.scissorStackSize - 1; + auto& clip = rdp.scissorRectStack[stack]; + clip.ulx = -gutter; + clip.lrx = rdp.colorImage.width * 4 + gutter; + rdp.extended.scissorLeftOriginStack[stack] = G_EX_ORIGIN_NONE; + rdp.extended.scissorRightOriginStack[stack] = G_EX_ORIGIN_NONE; + state->updateDrawStatusAttribute(RT64::DrawAttribute::Scissor); + } + rdp.drawTexRect(rect.ulx, rect.uly, rect.lrx, rect.lry, tile, s, uv, rect.dsdx, rect.dtdy, flip); + if (expand_clip) { + rdp.popScissor(); + state->updateDrawStatusAttribute(RT64::DrawAttribute::Scissor); + } *display_list = command; } void dkr::runtime::F3DDKRRT64Bridge::TrackTextureRect(RT64::State* state, RT64::DisplayList** display_list) { auto* command = *display_list; - if (!active_->data_->track_ui_cover || command->w0 != 0xD5000001U || command->w1 != 0x54524354U) { + // The guest emits these signed rectangles in both presentation modes. + // The optional widescreen scope changes clipping, but Accurate mode and + // archived tasks can decode the packet with their current native scissor. + if (command->w0 != 0xD5000001U || command->w1 != 0x54524354U) { RejectTask(display_list); return; } @@ -2685,7 +2727,8 @@ void dkr::runtime::F3DDKRRT64Bridge::TrackTextureRect(RT64::State* state, RT64:: const auto lrx = std::int16_t(command->p1(16, 16)), lry = std::int16_t(command->p1(0, 16)); ++command; RT64::ExtendedAlignment alignment{}; - alignment.leftOrigin = alignment.rightOrigin = G_EX_ORIGIN_NONE; + if (active_->data_->track_ui_cover) + alignment.leftOrigin = alignment.rightOrigin = G_EX_ORIGIN_NONE; state->rdp->drawTexRect(ulx, uly, lrx, lry, 0, std::int16_t(command->p0(16, 16)), std::int16_t(command->p0(0, 16)), std::int16_t(command->p1(16, 16)), std::int16_t(command->p1(0, 16)), false, alignment); *display_list = command; @@ -2827,7 +2870,21 @@ void dkr::runtime::F3DDKRRT64Bridge::Vertex(RT64::State* state, RT64::DisplayLis !data.interpolation_groups.has_rejected_scope(), water::enhanced::requested_quality.load(std::memory_order_relaxed) == water::enhanced::Quality::Original); #endif - rsp.setVertex(kScratchVertexAddress, count, destination); + const auto hud_motion = data.hud_widget_depth ? data.hud_widgets[data.hud_widget_depth - 1].motion_identity + : presentation::kIgnoredIdentity; + if (hud_motion != presentation::kIgnoredIdentity) { + auto& extended = rsp.extended; + auto& group = extended.modelMatrixIdStack[extended.modelMatrixIdStackSize - 1]; + const auto previous_group = group; + SelectInterpolationGroup(rsp, hud_motion, true, false, false, + ActiveAspectMode(data.interpolation_groups, data.matrix_aspect_override_active, + data.matrix_aspect_override)); + rsp.setVertex(kScratchVertexAddress, count, destination); + group = previous_group; + extended.modelMatrixIdStackChanged = true; + } else { + rsp.setVertex(kScratchVertexAddress, count, destination); + } #if defined(DKR_ENHANCED_WATER) data.flow_loads += flow_scope.active(); for (unsigned i = 0; i < count; ++i) diff --git a/runtime-recomp/src/game/game_main.cpp b/runtime-recomp/src/game/game_main.cpp index a408f53a..74e1f384 100644 --- a/runtime-recomp/src/game/game_main.cpp +++ b/runtime-recomp/src/game/game_main.cpp @@ -28,6 +28,7 @@ #include "save_manager.hpp" #include "runtime_save_routing.hpp" #include "startup_performance.hpp" +#include "time_trial/session.hpp" #include "virtual_pak.hpp" #include "runtime_legacy_mods.hpp" #include "runtime_code_mods.hpp" @@ -433,6 +434,16 @@ struct LaunchOptions { std::filesystem::path rom_path; std::filesystem::path config_directory; unsigned timeout_seconds = 0; + dkr::runtime::time_trial::Mode time_trial = dkr::runtime::time_trial::Mode::None; + std::filesystem::path replay_path; + std::filesystem::path ghost_replay; + std::filesystem::path ghost_export; + std::string time_trial_track; + std::filesystem::path time_trial_map; + dkr::runtime::time_trial::Adventure adventure = dkr::runtime::time_trial::Adventure::None; + unsigned time_trial_racer = dkr::runtime::time_trial::kDiddy; + const dkr::runtime::time_trial::Course* time_trial_course = &dkr::runtime::time_trial::kCourses.front(); + dkr::runtime::time_trial::Vehicle time_trial_vehicle = dkr::runtime::time_trial::Vehicle::Car; #if defined(DKR_EXPERIMENTAL_RACE_TEST) std::filesystem::path bootstrap_output; std::filesystem::path owned_check_invite; @@ -491,6 +502,77 @@ bool ParseLaunchOptions(int argc, char** argv, LaunchOptions& options, std::stri } options.owned_check_players = unsigned(value[0] - '0'); #endif + } else if (argument == "--adventure-category") { + const char* value = require_value("--adventure-category"); + if (!value) + return false; + options.adventure = dkr::runtime::time_trial::adventure_for(value); + if (options.adventure == dkr::runtime::time_trial::Adventure::None) { + error = "Choose any-percent, 100-percent or all-trophy-races."; + return false; + } + } else if (argument == "--time-trial-track" || argument == "--time-trial-map") { + const char* value = require_value(argv[index]); + if (!value) + return false; + if (argument == "--time-trial-track") + options.time_trial_track = value; + else + options.time_trial_map = std::filesystem::u8path(value); + } else if (argument == "--time-trial-ghost") { + const char* value = require_value("--time-trial-ghost"); + if (!value) + return false; + options.ghost_replay = std::filesystem::u8path(value); + } else if (argument == "--export-time-trial-ghost") { + const char* value = require_value("--export-time-trial-ghost"); + if (!value) + return false; + options.ghost_export = std::filesystem::u8path(value); + } else if (argument == "--time-trial-course") { + const char* value = require_value("--time-trial-course"); + if (!value) + return false; + options.time_trial_course = dkr::runtime::time_trial::course_for(value); + if (!options.time_trial_course) { + error = "Choose a supported retail Time Trial course."; + return false; + } + } else if (argument == "--time-trial-vehicle") { + const char* value = require_value("--time-trial-vehicle"); + if (!value) + return false; + namespace trial = dkr::runtime::time_trial; + const auto found = std::find(trial::kVehicleIds.begin(), trial::kVehicleIds.end(), std::string_view(value)); + if (found == trial::kVehicleIds.end()) { + error = "Time Trial vehicle must be car, hovercraft or plane."; + return false; + } + options.time_trial_vehicle = static_cast(found - trial::kVehicleIds.begin()); + } else if (argument == "--time-trial-racer") { + const char* value = require_value("--time-trial-racer"); + if (!value) + return false; + if (value[0] < '0' || value[0] > '9' || value[1]) { + error = "Time Trial racer must be an ID from 0 to 9."; + return false; + } + options.time_trial_racer = unsigned(value[0] - '0'); + } else if (argument == "--record-time-trial" || argument == "--self-test-time-trial" || + argument == "--verify-time-trial" || argument == "--watch-time-trial") { + using dkr::runtime::time_trial::Mode; + const char* value = require_value(argv[index]); + if (!value) + return false; + if (options.time_trial != Mode::None) { + error = "Select one Time Trial action."; + return false; + } + options.time_trial = argument == "--record-time-trial" ? Mode::Record + : argument == "--self-test-time-trial" ? Mode::SelfTest + : argument == "--verify-time-trial" ? Mode::Verify + : Mode::Watch; + options.replay_path = std::filesystem::u8path(value); } else if (argument == "--timeout") { const char* value = require_value("--timeout"); if (value == nullptr) { @@ -830,9 +912,44 @@ int DkrMain(int argc, char** argv) { // and portable roots must not accidentally select another profile later. const std::filesystem::path config_directory = std::filesystem::weakly_canonical(launch.config_directory); const unsigned timeout_seconds = launch.timeout_seconds; + namespace time_trial = dkr::runtime::time_trial; + if (launch.adventure != time_trial::Adventure::None && launch.time_trial != time_trial::Mode::Record) { + std::fprintf(stderr, "[adventure] --adventure-category requires --record-time-trial.\n"); + return 2; + } + if (!launch.ghost_export.empty() && launch.time_trial != time_trial::Mode::Verify) { + std::fprintf(stderr, "[ghost] Export requires --verify-time-trial.\n"); + return 2; + } + if (!launch.ghost_replay.empty() && + ((launch.time_trial != time_trial::Mode::Record && launch.time_trial != time_trial::Mode::SelfTest) || + launch.adventure != time_trial::Adventure::None || !launch.time_trial_track.empty())) { + std::fprintf(stderr, "[ghost] Select a practice recording. The ghost replay supplies the course and vehicle.\n"); + return 2; + } + if (launch.time_trial != time_trial::Mode::None) { + const auto start_trial = [&] { + if (!launch.ghost_replay.empty()) + return time_trial::start_ghost(launch.ghost_replay, launch.replay_path, rom_error, + launch.time_trial_racer, launch.time_trial, launch.time_trial_map); + return time_trial::start(launch.time_trial, launch.replay_path, rom_error, nullptr, launch.time_trial_racer, + *launch.time_trial_course, launch.time_trial_vehicle, launch.adventure, + launch.time_trial_track, launch.time_trial_map, launch.ghost_export); + }; + if (rom_path.empty() || launch.config_directory.empty() || !config_directory.is_absolute() || + std::filesystem::exists(config_directory) || !start_trial()) { + std::fprintf(stderr, "[time-trial] Requires a ROM, new absolute profile and absolute replay path. %s\n", + rom_error.c_str()); + return 2; + } + } #if defined(DKR_EXPERIMENTAL_RACE_TEST) const bool rollback_bootstrap = !launch.bootstrap_output.empty(); const bool owned_check = !launch.owned_check_invite.empty(); + if (time_trial::active() && (rollback_bootstrap || owned_check)) { + std::fprintf(stderr, "[time-trial] Time Trial accepts only an offline session.\n"); + return 2; + } if (owned_check && (rollback_bootstrap || rom_path.empty() || !config_directory.is_absolute() || std::filesystem::exists(config_directory) || !launch.owned_check_invite.is_absolute() || timeout_seconds < 20 || timeout_seconds > 180)) { @@ -864,6 +981,11 @@ int DkrMain(int argc, char** argv) { } dkr::runtime::startup_performance::mark("persistent-log-ready"); dkr::crash_reports::start(config_directory, DKR_RELEASE_VERSION); + if (launch.time_trial != time_trial::Mode::None) { + // CLI trials require a disposable profile. Managed jobs have no user + // to answer this dialog, and render jobs must capture only the game. + dkr::crash_reports::choose(false, false); + } { dkr::runtime::startup_performance::ScopedPhase phase("rom-identity-cache-configure"); dkr::runtime::rom::configure_identity_cache(config_directory); @@ -902,7 +1024,8 @@ int DkrMain(int argc, char** argv) { dkr::runtime::startup_performance::ScopedPhase phase("pak-save-input-configure"); dkr::runtime::pak::configure(config_directory); dkr::runtime::saves::configure(config_directory); - dkr::runtime::saves::configure_recovery_locations(RecoverySaveLocations(argv[0])); + if (!time_trial::active()) + dkr::runtime::saves::configure_recovery_locations(RecoverySaveLocations(argv[0])); dkr::runtime::platform::configure_input(config_directory); #if DKR_RUNTIME_HAS_RT64 // Custom tracks are user content beside the other imported assets, so @@ -1249,7 +1372,13 @@ int DkrMain(int argc, char** argv) { .poll_input = dkr::runtime::platform::poll_input, .frame_boundary = dkr::runtime::netplay::on_frame_boundary, .physical_poll_allowed = []() { return dkr::runtime::netplay::physical_input_poll_allowed(); }, - .get_input = dkr::runtime::platform::get_input, + .get_input = +[](int port, std::uint16_t* buttons, float* x, float* y) { + if (!time_trial::replaying()) + return dkr::runtime::platform::get_input(port, buttons, x, y); + *buttons = 0; + *x = *y = 0.0F; + return port == 0; + }, .set_rumble = dkr::runtime::platform::set_rumble, .get_connected_device_info = dkr::runtime::platform::get_connected_device_info, }; @@ -1301,6 +1430,8 @@ int DkrMain(int argc, char** argv) { .events_callbacks = events_callbacks, .save_write_allowed_callback = []() { + if (dkr::runtime::time_trial::active()) + return false; #if defined(DKR_EXPERIMENTAL_RACE_TEST) if (dkr_experimental_bootstrap_active()) return false; @@ -1336,10 +1467,11 @@ int DkrMain(int argc, char** argv) { // A lobby's accepted manifest, not later overlay preferences, owns // the simulation selection on every peer. const bool online_content = dkr::runtime::netplay::session().active(); - const bool content_enabled = online_content && dkr::runtime::netplay::session().view().host - ? dkr::session_content::host_enabled.load() - : prepared_mods ? prepared_mods->content_enabled - : dkr::session_content::next_enabled.load(); + const bool content_enabled = + !time_trial::active() && + (online_content && dkr::runtime::netplay::session().view().host ? dkr::session_content::host_enabled.load() + : prepared_mods ? prepared_mods->content_enabled + : dkr::session_content::next_enabled.load()); dkr::crash_reports::Gameplay quiet_reports; dkr::session_content::Session content_session(content_enabled, online_content); dkr::session_content::Preparation content_preparation(content_enabled); @@ -1350,7 +1482,8 @@ int DkrMain(int argc, char** argv) { online_magic_codes = static_cast(dkr::runtime::netplay::session().view().room.manifest.magic_codes_hash); } - dkr::runtime::magic_codes::begin_game_session(online_magic_codes); + dkr::runtime::magic_codes::begin_game_session(time_trial::active() ? std::optional{0} + : online_magic_codes); dkr::runtime::netplay::reset_runtime_state(); dkr::runtime::rev_a_asset_mutex::reset_statistics(); dkr::runtime::legacy::begin_session(nullptr); @@ -1423,7 +1556,20 @@ int DkrMain(int argc, char** argv) { !dkr::runtime::saves::shared::prepare_development(config_directory, developer_folder, rom_error)) throw dkr::mods::Error(rom_error); selecting_save_owner = true; - if (dkr::runtime::spectators::party_enabled(&dkr::runtime::netplay::session())) { + if (time_trial::active()) { + using dkr::runtime::saves::ReplaySave; + const auto seed = time_trial::uses_completed_adventure_save() ? ReplaySave::CompletedAdventure + : time_trial::uses_uninitialised_adventure_save() ? ReplaySave::MissingAdventure + : ReplaySave::Blank; + if (!dkr::runtime::saves::prepare_time_trial_save_context(rom_error, seed)) + throw dkr::mods::Error(rom_error); + ultramodern::set_save_storage_callbacks({dkr::runtime::saves::runtime_save_path, + dkr::runtime::saves::load_runtime_save, + dkr::runtime::saves::commit_runtime_save}); + dkr::runtime::pak::begin_session_directory({}); + if (!dkr::runtime::saves::records::begin_memory({}, rom_error)) + throw dkr::mods::Error(rom_error); + } else if (dkr::runtime::spectators::party_enabled(&dkr::runtime::netplay::session())) { auto party = dkr::runtime::spectators::party_link(&dkr::runtime::netplay::session()); std::vector seed, shared_records; bool owns_save = false; @@ -1470,7 +1616,8 @@ int DkrMain(int argc, char** argv) { std::fprintf(stderr, "[save][selected] owner=%s path=%s progress=%s\n", online_save.active ? "online" : development_session ? "development" - : "personal", + : content_enabled ? "modded" + : "vanilla", std::string(utf8.begin(), utf8.end()).c_str(), dkr::runtime::saves::shared::describe(path).c_str()); } @@ -1478,15 +1625,18 @@ int DkrMain(int argc, char** argv) { dkr::runtime::saves::load_runtime_save, dkr::runtime::saves::commit_runtime_save}); dkr::runtime::pak::begin_session_directory(dkr::runtime::saves::runtime_pak_directory()); + const auto records_directory = online_save.active + ? dkr::runtime::saves::runtime_save_path().parent_path() + : config_directory / "saves"; if (!dkr::runtime::saves::records::begin( - development_session - ? std::filesystem::path{} - : dkr::runtime::saves::runtime_save_path().parent_path() / "custom-records-v1.bin", + development_session ? std::filesystem::path{} : records_directory / "custom-records-v1.bin", !development_session && (!online_save.active || online_save.host), rom_error)) throw dkr::mods::Error(rom_error); } } catch (const std::exception& error) { std::fprintf(stderr, "[legacy][launch] %s\n", error.what()); + if (time_trial::active()) + time_trial::retire(); #if DKR_RUNTIME_HAS_RT64 if (selecting_save_owner) { // No guest producer exists yet. A locked/invalid route is a @@ -1733,6 +1883,7 @@ int DkrMain(int argc, char** argv) { // X11 and Wayland compatibility while the recompiler owns its // worker. dkr::runtime::platform::pump_window_events(nullptr); + dkr::runtime::ui::show_run_return_cover(); dkr::runtime::service_online_wait_presentation(); #endif if (!timeout_requested && timeout_seconds != 0 && @@ -1748,6 +1899,10 @@ int DkrMain(int argc, char** argv) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } runtime_thread.join(); +#if DKR_RUNTIME_HAS_RT64 + if (time_trial::active() && !time_trial::preparing_ghost()) + dkr::runtime::ui::show_run_return_cover(true); +#endif dkr::runtime::modern_camera::reset_session(); #if defined(DKR_EXPERIMENTAL_RACE_TEST) if (owned_launch) { @@ -1853,6 +2008,23 @@ int DkrMain(int argc, char** argv) { } return 5; } + const bool return_from_time_trial = time_trial::active(); + if (time_trial::preparing_ghost() && time_trial::advance_ghost()) { + dkr::session_content::end(); + continue; + } + if (return_from_time_trial) + time_trial::finish_interrupted_recording(); + if (launch.time_trial == time_trial::Mode::Verify || launch.time_trial == time_trial::Mode::SelfTest || + time_trial::exporting_video() || + launch.adventure != time_trial::Adventure::None) { + const int status = time_trial::status(); + time_trial::retire(); + dkr::runtime::platform::shutdown(); + return status; + } + if (return_from_time_trial) + time_trial::retire(); #if DKR_RUNTIME_HAS_RT64 #if defined(DKR_EXPERIMENTAL_RACE_TEST) if (owned_check) { @@ -1860,8 +2032,8 @@ int DkrMain(int argc, char** argv) { return owned_failed ? 5 : 0; } #endif - if (lifecycle_request == dkr::runtime::ui::LifecycleRequest::StopGame || !mod_failure.empty() || - !save_failure.empty() || + if (return_from_time_trial || lifecycle_request == dkr::runtime::ui::LifecycleRequest::StopGame || + !mod_failure.empty() || !save_failure.empty() || (return_from_owned && lifecycle_request == dkr::runtime::ui::LifecycleRequest::None)) { if (!mod_failure.empty()) dkr::runtime::ui::report_mod_error("Custom content stopped safely: " + mod_failure); @@ -1874,8 +2046,10 @@ int DkrMain(int argc, char** argv) { ? std::string("The previous online game did not finish safely. Review its error before joining.") : std::string{}); dkr::runtime::ui::reset_lifecycle_request(); - const bool software_launcher_return = dkr::runtime::launcher_surface_recovery( - owned_failed, return_from_owned, !mod_failure.empty() || !save_failure.empty()); + const bool software_launcher_return = + return_from_time_trial || + dkr::runtime::launcher_surface_recovery(owned_failed, return_from_owned, + !mod_failure.empty() || !save_failure.empty()); dkr::session_content::end(); const auto startup = dkr::runtime::ui::run_startup_screen( static_cast(dkr::runtime::platform::sdl_window()), rom_path, software_launcher_return); diff --git a/runtime-recomp/src/game/hud_layout_editor.cpp b/runtime-recomp/src/game/hud_layout_editor.cpp index 9926b5dc..9a48f6b2 100644 --- a/runtime-recomp/src/game/hud_layout_editor.cpp +++ b/runtime-recomp/src/game/hud_layout_editor.cpp @@ -1,4 +1,5 @@ #include "hud_layout_editor.hpp" +#include "dialog_style.hpp" #include "runtime_hud_layout.hpp" #include "imgui.h" #include "imgui_internal.h" @@ -359,10 +360,9 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { ImGui::SetNextWindowPos( {viewport->WorkPos.x + viewport->WorkSize.x * .5F, viewport->WorkPos.y + viewport->WorkSize.y * .5F}, ImGuiCond_Always, {.5F, .5F}); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {16, 12}); - if (ImGui::BeginPopupModal("HUD WORKSHOP", nullptr, - ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoSavedSettings)) { + if (ui::begin_dialog_modal("HUD WORKSHOP", nullptr, + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings, + {16.0F, 12.0F})) { ImGui::TextWrapped( "Single / two-player HUD. This is a schematic preview; native visibility and animations stay controlled by the game."); ImGui::BeginDisabled(e.moving); @@ -461,7 +461,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { [&] { e.draft.scale = hg::safe_scale(std::round(global) / 100); }); if (button("SIZE ALL GROUPS", -1)) ImGui::OpenPopup("Use global size everywhere?"); - if (ImGui::BeginPopupModal("Use global size everywhere?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Use global size everywhere?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Clear every group size override? Positions stay unchanged."); if (button("CONFIRM")) { change([&] { @@ -531,7 +531,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { }); if (button("COPY TO OTHER SCENARIOS", -1)) ImGui::OpenPopup("Copy this group?"); - if (ImGui::BeginPopupModal("Copy this group?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Copy this group?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Copy this group's placement to compatible scenarios only?"); if (button("COPY")) { change([&] { @@ -560,7 +560,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { ImGui::EndDisabled(); if (button("RESET GROUP", -1)) ImGui::OpenPopup("Reset this group?"); - if (ImGui::BeginPopupModal("Reset this group?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Reset this group?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Restore native placement and inherited size for this group?"); if (button("RESET")) { change([&] { selected() = {}; }); @@ -573,7 +573,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { } if (button("RESET SCENARIO", -1)) ImGui::OpenPopup("Reset this scenario?"); - if (ImGui::BeginPopupModal("Reset this scenario?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Reset this scenario?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Reset all groups for the selected scenario, player and screen profile?"); if (button("RESET")) { change([&] { hg::reset_scenario(e.draft, aspect(), scenario(), target()); }); @@ -608,7 +608,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { if (button("DELETE PRESET", -1)) ImGui::OpenPopup("Delete this preset?"); ImGui::EndDisabled(); - if (ImGui::BeginPopupModal("Delete this preset?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Delete this preset?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Delete the selected saved preset? Applied settings stay unchanged."); if (button("DELETE") && !names.empty()) { delete_preset(names[e.preset]); @@ -626,7 +626,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { draw_keyboard(); if (!e.pending_preset.empty()) ImGui::OpenPopup("Replace saved preset?"); - if (ImGui::BeginPopupModal("Replace saved preset?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Replace saved preset?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextWrapped("Replace the saved preset %s?", e.pending_preset.c_str()); if (button("REPLACE")) { e.message = save_preset(e.pending_preset, e.draft) ? "Preset saved." : "Could not write preset."; @@ -668,7 +668,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { ImGui::OpenPopup("Custom layout starting point"); e.select_base = false; } - if (ImGui::BeginPopupModal("Custom layout starting point", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Custom layout starting point", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Choose a starting area. Existing group edits are retained."); if (button("START FROM ORIGINAL")) { change([] { e.draft.custom_fill = false; }); @@ -695,7 +695,7 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { ImGui::OpenPopup("HUD changes"); e.close_prompt = false; } - if (ImGui::BeginPopupModal("HUD changes", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("HUD changes", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Apply the preview, discard changes, or keep editing?"); if (button("APPLY")) { if (apply_layout(e.draft)) { @@ -723,7 +723,6 @@ void modal(void (*request_name)(), void (*draw_keyboard)()) { } else if (!ImGui::IsPopupOpen("HUD WORKSHOP")) { cancel(); } - ImGui::PopStyleVar(); } } // namespace @@ -858,7 +857,7 @@ bool draw_settings(bool modern, float width, void (*request_name)(), void (*draw } if (button("RESET HUD SETTINGS", std::min(width, ImGui::GetContentRegionAvail().x))) ImGui::OpenPopup("Reset HUD settings?"); - if (ImGui::BeginPopupModal("Reset HUD settings?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (ui::begin_dialog_modal("Reset HUD settings?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted("Restore Original layout and 100% group size? Saved presets are retained."); if (button("RESET")) { changed = apply_settings({}); diff --git a/runtime-recomp/src/game/invite_ui.inl b/runtime-recomp/src/game/invite_ui.inl index 100f97af..6db5dc63 100644 --- a/runtime-recomp/src/game/invite_ui.inl +++ b/runtime-recomp/src/game/invite_ui.inl @@ -389,9 +389,10 @@ void DrawInviteUi() { if (g_invite_intent.step == InviteStep::Stopping || g_invite_intent.step == InviteStep::Queued) { ImGui::SetNextWindowPos({ImGui::GetIO().DisplaySize.x * .5F, 20}, ImGuiCond_Always, {.5F, 0}); ImGui::SetNextWindowBgAlpha(.94F); - if (ImGui::Begin("##invite-progress", nullptr, - ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDecoration | - ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing)) { + if (dkr::runtime::ui::begin_dialog_window("##invite-progress", nullptr, + ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDecoration | + ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoFocusOnAppearing)) { ImGui::TextUnformatted(g_invite_intent.step == InviteStep::Stopping ? "Returning safely to the launcher..." : "Preparing to join your friend's lobby..."); diff --git a/runtime-recomp/src/game/library_ui/automatic_ui.inl b/runtime-recomp/src/game/library_ui/automatic_ui.inl index e1e3ef02..19845ada 100644 --- a/runtime-recomp/src/game/library_ui/automatic_ui.inl +++ b/runtime-recomp/src/game/library_ui/automatic_ui.inl @@ -29,13 +29,15 @@ bool AutomaticStartHasMods() { return dkr::runtime::magic_codes::selected_mask() != 0; } -bool DrawStartingContent(const dkr::mods::ModLaunchView& state, bool mods, bool syncing, double seconds) { +bool DrawStartingContent(const dkr::mods::ModLaunchView& state, bool mods, bool syncing, double seconds, + bool returning = false) { auto* draw = ImGui::GetWindowDrawList(); const auto at = ImGui::GetWindowPos(); const auto size = ImGui::GetWindowSize(); auto layout = dkr::library_ui::startup_layout(size.x, size.y, 0); const float scale = layout.scale, padding = 26.F * scale, inner = std::max(1.F, layout.panel - 2.F * padding); - const auto title = dkr::localisation::text(syncing ? "play.syncing_game" : "play.starting_game"); + const auto title = returning ? dkr::localisation::source("Returning to Launcher...") : + dkr::localisation::text(syncing ? "play.syncing_game" : "play.starting_game"); const auto loading = dkr::localisation::text(syncing ? "play.syncing_status" : "play.loading_mods"); const auto button = dkr::localisation::text("play.open_launcher"); const auto stage = @@ -52,7 +54,7 @@ bool DrawStartingContent(const dkr::mods::ModLaunchView& state, bool mods, bool const float mod_height = mods ? 14.F * scale + loading_height + 11.F * scale + 10.F * scale + (stage_height > 0 ? 11.F * scale + stage_height : 0) : 0; - const float caption = 20.F * scale + title_height + mod_height + 14.F * scale + button_height + 18.F * scale; + const float caption = 38.F * scale + title_height + mod_height + (returning ? 0.F : 14.F * scale + button_height); layout = dkr::library_ui::startup_layout(size.x, size.y, caption); ImGui::SetCursorPos({(size.x - layout.logo) * .5F, layout.top}); BrandBlock(layout.logo, layout.logo, false); @@ -69,6 +71,8 @@ bool DrawStartingContent(const dkr::mods::ModLaunchView& state, bool mods, bool y += height; }; line(heading, title, title_height); + if (returning) + return false; if (mods) { y += 14.F * scale; line(subheading, loading, loading_height); @@ -115,7 +119,8 @@ bool DrawStartingContent(const dkr::mods::ModLaunchView& state, bool mods, bool bool DrawAutomaticStart(dkr::library_ui::AutomaticStart& automatic, LauncherBackgroundTexture& background, SDL_Renderer* renderer, double scroll, bool software, dkr::launcher_themes::Theme theme, - double seconds, const dkr::mods::ModLaunchView* preview = nullptr, bool syncing = false) { + double seconds, const dkr::mods::ModLaunchView* preview = nullptr, bool syncing = false, + bool returning = false) { BeginMainWindow("DKR-R Starting", ImGuiWindowFlags_NoBackground); DrawLauncherBackdrop(background, renderer, scroll, software); dkr::launcher_themes::weather(ImGui::GetWindowDrawList(), ImGui::GetWindowPos(), ImGui::GetWindowSize(), theme, @@ -123,7 +128,8 @@ bool DrawAutomaticStart(dkr::library_ui::AutomaticStart& automatic, LauncherBack auto state = preview ? *preview : g_mod_launch.snapshot(); if (syncing) state.stage = "Getting everyone ready..."; - const bool pressed = DrawStartingContent(state, automatic.loading_mods() || syncing, syncing, seconds); + const bool pressed = + DrawStartingContent(state, !returning && (automatic.loading_mods() || syncing), syncing, seconds, returning); if (pressed && !syncing) { automatic.cancel(); g_mod_launch.cancel(); diff --git a/runtime-recomp/src/game/library_ui/handoff_ui.inl b/runtime-recomp/src/game/library_ui/handoff_ui.inl index 9995da97..198c00b7 100644 --- a/runtime-recomp/src/game/library_ui/handoff_ui.inl +++ b/runtime-recomp/src/game/library_ui/handoff_ui.inl @@ -140,3 +140,24 @@ bool DrawRuntimeStartingGame() { } return true; } + +bool DrawRuntimeReturningFromRun() { + const auto alpha = dkr::runtime::time_trial::launcher_return_opacity(); + if (alpha <= 0.F) + return false; + BeginMainWindow("DKR-R Returning", ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoInputs); + auto* draw = ImGui::GetWindowDrawList(); + const int first = draw->VtxBuffer.Size; + const double seconds = ImGui::GetTime(); + DrawRuntimeStartupClouds(seconds); + dkr::launcher_themes::weather(draw, ImGui::GetWindowPos(), ImGui::GetWindowSize(), dkr::launcher_themes::displayed, + seconds, dkr::launcher_themes::preferences.calendar); + DrawStartingContent({}, false, false, seconds, true); + for (int i = first; i < draw->VtxBuffer.Size; ++i) { + auto& colour = draw->VtxBuffer[i].col; + const unsigned opacity = (colour >> IM_COL32_A_SHIFT) & 255U; + colour = (colour & ~IM_COL32_A_MASK) | (unsigned(opacity * alpha) << IM_COL32_A_SHIFT); + } + ImGui::End(); + return true; +} diff --git a/runtime-recomp/src/game/library_ui/leaderboard_rankings.inl b/runtime-recomp/src/game/library_ui/leaderboard_rankings.inl new file mode 100644 index 00000000..484bc311 --- /dev/null +++ b/runtime-recomp/src/game/library_ui/leaderboard_rankings.inl @@ -0,0 +1,523 @@ +std::string LeaderboardPoints(std::int64_t milli) { + char formatted[32]; + std::snprintf(formatted, sizeof(formatted), "%.3f", static_cast(milli) / 1000.0); + std::string result(formatted); + while (result.ends_with('0')) + result.pop_back(); + if (result.ends_with('.')) + result.pop_back(); + return result; +} + +std::string RecordDate(std::int64_t seconds) { + const auto stamp = static_cast(seconds); + std::tm date{}; +#ifdef _WIN32 + if (gmtime_s(&date, &stamp)) + return {}; +#else + if (!gmtime_r(&stamp, &date)) + return {}; +#endif + char label[28]{}; + std::strftime(label, sizeof(label), "%d %b %Y", &date); + return label; +} + +std::int64_t RecordUnix(const dkr::store::Json& data, const char* key) { + const auto value = data.find(key); + if (value == data.end() || !value->is_number_integer()) + return 0; + return std::clamp(value->get(), 0, 253402300799); +} + +std::string RecordDuration(std::int64_t seconds) { + if (seconds >= 86400) { + const auto days = seconds / 86400; + return std::to_string(days) + (days == 1 ? " day" : " days"); + } + if (seconds >= 3600) { + const auto hours = seconds / 3600; + return std::to_string(hours) + (hours == 1 ? " hour" : " hours"); + } + if (seconds >= 60) { + const auto minutes = seconds / 60; + return std::to_string(minutes) + (minutes == 1 ? " minute" : " minutes"); + } + return std::to_string(std::max(seconds, 0)) + " sec"; +} + +void DrawTrackRecordHistory(float width, const dkr::store::Json& history, const std::string& board) { + if (!history.is_object()) + return; + const auto changes = history.find("changes"); + if (changes == history.end() || !changes->is_array()) + return; + const bool complete = history.value("complete", false); + OlHeading("World record history", 21.F, kOlCream, width); + if (changes->empty()) { + OlParagraph(complete ? "Record history appears after the first published run." + : "Publication dates are unavailable for these results.", 15.F, kOlSoft, width); + return; + } + static std::string selected_board; + static std::int64_t selected_at = 0; + if (selected_board != board) { + selected_board = board; + selected_at = 0; + } + const auto at = [&](std::size_t index) { return RecordUnix((*changes)[index], "at"); }; + const auto ticks = [&](std::size_t index) { return LeaderboardNumber((*changes)[index], "ticks"); }; + const auto last = changes->size() - 1; + const auto latest = std::max(at(last), RecordUnix(history, "asOf")); + std::size_t selected = last; + for (std::size_t index = 0; index < changes->size(); ++index) + if (selected_at == at(index)) + selected = index; + + const auto chart_origin = ImGui::GetCursorScreenPos(); + constexpr float height = 150.F; + const float left = std::min(100.F, width * .40F); + const float right = std::max(left + 1.F, width - 11.F); + const auto font = OlRead(14.F); + const auto end = complete ? latest : at(last); + const double time_span = static_cast(std::max(end - at(0), 1)); + const double pace_span = static_cast(std::max(ticks(0) - ticks(last), 1)); + const auto chart_x = [&](std::int64_t stamp) { + return chart_origin.x + left + (right - left) * static_cast((stamp - at(0)) / time_span); + }; + const auto chart_y = [&](std::int64_t pace) { + return chart_origin.y + 18.F + 96.F * static_cast((ticks(0) - pace) / pace_span); + }; + + ImGui::Dummy({width, height}); + auto* draw = ImGui::GetWindowDrawList(); + const auto x0 = chart_origin.x + left; + const auto x1 = chart_origin.x + right; + const auto caption = [&](const std::string& label, ImVec2 pos) { + draw->AddText(font.font, font.size, pos, PaddockCol(kOlSoft), label.c_str()); + }; + for (const auto tick : std::array{ticks(0), ticks(last)}) { + const auto y = chart_y(tick); + draw->AddLine({x0, y}, {x1, y}, PaddockCol(kOlRing)); + caption(LeaderboardTime(tick), {chart_origin.x, y - 8.F}); + if (ticks(0) == ticks(last)) + break; + } + const float date_y = chart_origin.y + 129.F; + caption(RecordDate(at(0)), {x0, date_y}); + if (end != at(0) && x1 - x0 > 212.F) { + const auto label = RecordDate(end); + const auto span = font.font->CalcTextSizeA(font.size, FLT_MAX, 0.F, label.c_str()); + caption(label, {x1 - span.x, date_y}); + } + + float nearest = 16.F; + const auto pointer = ImGui::GetMousePos(); + const bool clicked = ImGui::IsItemHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Left); + for (std::size_t index = 0; index < changes->size(); ++index) { + const float x = chart_x(at(index)), y = chart_y(ticks(index)); + const float next_x = index != last ? chart_x(at(index + 1)) : chart_x(end); + draw->AddLine({x, y}, {next_x, y}, PaddockCol(kOlAmber), 2.F); + if (index != last) + draw->AddLine({next_x, y}, {next_x, chart_y(ticks(index + 1))}, PaddockCol(kOlAmber), 2.F); + draw->AddCircleFilled({x, y}, index == selected ? 5.5F : 3.F, PaddockCol(kOlAmber)); + if (clicked) { + const float distance = std::abs(pointer.x - x) + std::abs(pointer.y - y); + if (distance < nearest) { + nearest = distance; + selected = index; + selected_at = at(index); + } + } + } + { + const OlDisabled unavailable(selected == 0); + if (OlButton("Earlier record")) { + --selected; + selected_at = at(selected); + } + } + ImGui::SameLine(); + { + const OlDisabled unavailable(selected == last); + if (OlButton("Later record")) { + ++selected; + selected_at = at(selected); + } + } + const auto& event = (*changes)[selected]; + const auto expired = RecordUnix(event, "until"); + std::string detail = LeaderboardTime(ticks(selected)) + " | " + RecordDate(at(selected)); + if (expired || complete) + detail += " | " + std::string(expired ? "Stood for " : "Unbeaten for ") + + RecordDuration((expired ? expired : latest) - at(selected)); + OlParagraph(detail, 16.F, kOlCream, width, true); + if (const auto holders = event.find("holders"); holders != event.end() && holders->is_array()) { + for (const auto& holder : *holders) { + auto line = StoreText(holder, "name", 96); + const auto until = RecordUnix(holder, "until"); + if (until || complete) + line += " | " + std::string(until ? "Held for " : "Holding for ") + + RecordDuration((until ? until : latest) - RecordUnix(holder, "from")); + OlParagraph(line, 15.F, kOlSoft, width); + } + } + if (!complete || LeaderboardNumber(history, "earlierChanges")) + OlParagraph(complete ? "Showing the latest record changes." : "Some publication dates are unavailable.", + 14.F, kOlSoft, width); +} + +enum class OverallPlayerTab { Score, Runs }; + +dkr::store::Json g_overall_standings, g_overall_profile; +std::string g_overall_player, g_overall_focus; +OverallPlayerTab g_overall_tab = OverallPlayerTab::Score; +bool g_overall_runs_requested = false; +bool g_overall_show_custom = false; + +void SelectOverallPlayer(std::string id) { + g_overall_player = std::move(id); + g_overall_profile = nullptr; + g_overall_runs_requested = false; + g_overall_show_custom = false; +} + +void RefreshOverallRankings() { + RankedJob([] { + auto data = dkr::store::service().overall_rankings(); + return [data = std::move(data)]() mutable { + g_overall_standings = std::move(data); + g_overall_profile = nullptr; + g_overall_runs_requested = false; + }; + }); +} + +void RefreshOverallPlayer(const std::string& id, unsigned offset = 0) { + g_overall_runs_requested = true; + RankedJob([id, offset] { + auto data = dkr::store::service().overall_rankings(id, offset); + return [id, offset, data = std::move(data)]() mutable { + if (id != g_overall_player) + return; + if (offset && g_overall_profile.is_object()) { + for (auto& entry : data["events"]) + g_overall_profile["events"].push_back(std::move(entry)); + g_overall_profile["nextOffset"] = data["nextOffset"]; + } else { + g_overall_profile = std::move(data); + } + }; + }); +} + +std::string OverallPersonalBests(const dkr::store::Json& player) { + const auto count = player.find("personalBests"); + return count != player.end() && count->is_number_integer() ? std::to_string(LeaderboardNumber(player, "personalBests")) + : "—"; +} + +void DrawOverallStandings(float width, const dkr::store::Json& players) { + DrawOlCard(width, OlPanelLook{}, [&](float inner) { + OlHeading("Top Players", 24.F, kOlCream, inner); + PaddockGap(4.F); + const bool compact = inner < 300.F; + constexpr auto flags = ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_NoSavedSettings | + ImGuiTableFlags_NoPadOuterX; + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, {compact ? 3.F : 5.F, 4.F}); + if (ImGui::BeginTable("top-player-standings", 5, flags, {inner, 0.F})) { + ImGui::TableSetupColumn("Rank", ImGuiTableColumnFlags_WidthFixed, compact ? 34.F : 46.F); + ImGui::TableSetupColumn("Player", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("PBs", ImGuiTableColumnFlags_WidthFixed, compact ? 29.F : 34.F); + ImGui::TableSetupColumn("WRs", ImGuiTableColumnFlags_WidthFixed, compact ? 29.F : 38.F); + ImGui::TableSetupColumn("Points", ImGuiTableColumnFlags_WidthFixed, compact ? 58.F : 67.F); + + const auto cell = [](std::string_view text, float height, unsigned colour, bool right = false) { + const float width = ImGui::GetContentRegionAvail().x; + const auto type = OlRead(14.F, true, 1.2F); + const std::string label = PaddockEllipsize(type, text, width); + auto at = ImGui::GetCursorScreenPos(); + if (right) + at.x += std::max(0.F, width - PaddockMeasure(type, label)); + at.y += (height - type.line) * .5F; + PaddockDrawRun(ImGui::GetWindowDrawList(), type, at, PaddockCol(colour), label.data(), label.data() + label.size()); + ImGui::Dummy({width, height}); + }; + + ImGui::TableNextRow(); + int column = 0; + for (const auto* header : {compact ? "#" : "Rank", "Player", "PBs", "WRs", "Points"}) { + ImGui::TableNextColumn(); + cell(dkr::localisation::source(header), 22.F, kOlSoft, column >= 2); + ++column; + } + constexpr float row_height = 34.F; + for (const auto& player : players) { + const auto id = StoreText(player, "id", 96); + if (id.empty()) + continue; + const auto name = StoreText(player, "name", 96); + const auto place = LeaderboardNumber(player, "place"); + const bool selected = g_overall_player == id; + ImGui::PushID(id.c_str()); + ImGui::TableNextRow(); + ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, PaddockCol(selected ? 0x194650U : 0x123345U)); + ImGui::TableNextColumn(); + const auto at = ImGui::GetCursorScreenPos(); + const unsigned badge = place == 1 ? 0x644C26U : place == 2 ? 0x40576BU : + place == 3 ? 0x67482FU : 0x23495CU; + PaddockFill(ImGui::GetWindowDrawList(), {at.x + 2.F, at.y + 4.F}, {at.x + 30.F, at.y + 30.F}, + PaddockRound(5.F), PaddockCol(badge)); + const auto rank = std::to_string(place); + const auto digit = OlRead(14.F, true, 1.2F); + PaddockDrawRun(ImGui::GetWindowDrawList(), digit, + {at.x + 16.F - PaddockMeasure(digit, rank) * .5F, at.y + (row_height - digit.line) * .5F}, + PaddockCol(place == 1 ? kOlCream : kOlInk), rank.data(), rank.data() + rank.size()); + ImGui::Dummy({32.F, row_height}); + + ImGui::TableNextColumn(); + const float name_width = ImGui::GetContentRegionAvail().x; + const auto caption = PaddockEllipsize(OlRead(14.F, true, 1.2F), name, std::max(1.F, name_width - 14.F)); + if (g_overall_focus == id) { + ImGui::SetKeyboardFocusHere(); + g_overall_focus.clear(); + } + if (OlButton((caption + "###player").c_str(), OlTone::Plain, name_width, + caption != name ? name.c_str() : nullptr, row_height) && !selected) + SelectOverallPlayer(id); + StoreControlFocus(); + + ImGui::TableNextColumn(); + cell(OverallPersonalBests(player), row_height, kOlInk, true); + ImGui::TableNextColumn(); + cell(std::to_string(LeaderboardNumber(player, "records")), row_height, kOlInk, true); + ImGui::TableNextColumn(); + cell(LeaderboardPoints(LeaderboardNumber(player, "total")), row_height, kOlCream, true); + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::PopStyleVar(); + if (g_overall_standings.value("tiedCutoff", false)) + OlParagraph("More players share the final rank shown.", 14.F, kOlSoft, inner); + }, 13.F); +} + +void DrawOverallScoreBreakdown(float width, const dkr::store::Json& player) { + const auto points = player.find("points"); + const auto draw_category = [&](const char* label, const char* key, int cap) { + const auto earned = points == player.end() ? 0 : LeaderboardNumber(*points, key); + const std::string score = LeaderboardPoints(earned) + " / " + std::to_string(cap) + " pts"; + const auto caption = LocalisedUi::copy(label); + const auto value_type = OlRead(14.F, false, 1.25F); + const float value_width = PaddockMeasure(value_type, score) + 2.F; + const bool side_by_side = width >= PaddockMeasure(OlRead(15.F, true, 1.25F), caption) + value_width + 10.F; + OlParagraph(caption, 15.F, kOlInk, side_by_side ? width - value_width - 8.F : width, true, 1.25F); + if (side_by_side) + ImGui::SameLine(0.F, 8.F); + OlParagraph(score, 14.F, kOlSoft, side_by_side ? value_width : width, false, 1.25F); + const auto at = ImGui::GetCursorScreenPos(); + auto* draw = ImGui::GetWindowDrawList(); + const float fraction = std::clamp(static_cast(earned) / (1000.F * cap), 0.F, 1.F); + PaddockFill(draw, at, {at.x + width, at.y + 6.F}, PaddockRound(3.F), PaddockCol(0x254658U)); + if (fraction > 0.F) + PaddockFill(draw, at, {at.x + width * fraction, at.y + 6.F}, PaddockRound(3.F), PaddockCol(kOlGo)); + ImGui::Dummy({width, 6.F}); + }; + draw_category("Vanilla Tracks", "vanilla", 500); + draw_category("Custom Tracks", "custom", 250); + draw_category("Full Game", "fullGame", 250); + OlParagraph(std::to_string(LeaderboardNumber(player, "podiums")) + " podiums · " + + std::to_string(LeaderboardNumber(player, "coverage")) + " ranked events", + 14.F, kOlSoft, width); +} + +std::optional DrawOverallPlayerRuns(float width) { + if (!g_overall_profile.is_object()) { + if (!g_overall_runs_requested && !DialogJobRunning()) + RefreshOverallPlayer(g_overall_player); + OlParagraph(DialogJobRunning() ? "Loading ranked runs..." : "Ranked runs are unavailable.", 15.F, kOlSoft, width); + if (!DialogJobRunning() && OlButton("Try again")) + RefreshOverallPlayer(g_overall_player); + return {}; + } + + std::optional next; + const auto events = g_overall_profile.find("events"); + if (events == g_overall_profile.end() || !events->is_array() || events->empty()) { + OlParagraph("No ranked runs to show.", 15.F, kOlSoft, width); + return {}; + } + for (const auto& event : *events) { + const auto kind = StoreText(event, "kind", 16); + const auto id = StoreText(event, "id", 96); + const auto vehicle = StoreText(event, "vehicle", 24); + const bool full = kind == "full-game"; + const auto& race = event["race"]; + ImGui::PushID((kind + "/" + id + "/" + vehicle).c_str()); + const auto at = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddLine(at, {at.x + width, at.y}, PaddockCol(kOlRing)); + ImGui::Dummy({width, 1.F}); + auto title = StoreText(event, "title", 120); + if (!full) + title += " · " + LeaderboardVehicle(vehicle); + OlParagraph(title, 16.F, kOlCream, width, true, 1.2F); + auto times = LeaderboardTime(LeaderboardNumber(race, "ticks")) + " | #" + + std::to_string(LeaderboardNumber(race, "place")); + if (const auto lap = event.find("lap"); lap != event.end()) + times += " | Best lap " + LeaderboardTime(LeaderboardNumber(*lap, "ticks")) + " | #" + + std::to_string(LeaderboardNumber(*lap, "place")); + OlParagraph(times, 14.F, kOlSoft, width, false, 1.2F); + if (OlButton("View Times", OlTone::Plain, 0.F, nullptr, 32.F)) + next = TrackQuery{id, full ? "" : vehicle, "", kind == "custom", false, 0, full}; + StoreControlFocus(); + if (const auto run = StoreText(race, "runId", 96); !run.empty()) { + const OlDisabled launch(DialogJobRunning() || !CanLaunchLeaderboardReplay()); + float used_width = OlButtonWidth("View Times"); + const auto action = [&](const char* label, LeaderboardReplayAction action_type) { + const float button_width = OlButtonWidth(label); + if (used_width + 6.F + button_width <= width) { + ImGui::SameLine(0.F, 6.F); + used_width += 6.F + button_width; + } else { + used_width = button_width; + } + if (OlButton(label, OlTone::Plain, std::min(width, button_width), nullptr, 32.F)) + WatchLeaderboardReplay(run, false, action_type, + action_type == LeaderboardReplayAction::RaceGhost + ? StoreText(g_overall_profile["player"], "name", 60) + : std::string{}); + StoreControlFocus(); + }; + action("Watch", LeaderboardReplayAction::Watch); + if (!full) + action("Race Ghost", LeaderboardReplayAction::RaceGhost); + } + ImGui::PopID(); + } + { + const OlDisabled busy(DialogJobRunning()); + if (const auto offset = LeaderboardNumber(g_overall_profile, "nextOffset"); offset && OlButton("More results")) + RefreshOverallPlayer(g_overall_player, static_cast(offset)); + } + if (const auto custom = g_overall_profile.find("customTracks"); + custom != g_overall_profile.end() && custom->is_array() && !custom->empty()) { + if (OlButton(g_overall_show_custom ? "Hide scoring tracks" : "Custom scoring tracks")) + g_overall_show_custom = !g_overall_show_custom; + if (g_overall_show_custom) { + for (const auto& track : *custom) { + const auto title = StoreText(track, "title", 120); + OlParagraph((title.empty() ? StoreText(track, "id", 96) : title) + " | " + + LeaderboardPoints(LeaderboardNumber(track, "points")) + " pts", + 14.F, kOlSoft, width); + } + } + } + return next; +} + +std::optional DrawOverallPlayerPanel(float width, const dkr::store::Json& player) { + std::optional next; + DrawOlCard(width, OlPanelLook{}, [&](float inner) { + const auto total = LeaderboardPoints(LeaderboardNumber(player, "total")) + " pts"; + const float total_width = std::ceil(PaddockMeasure(OlSignType(23.F, 1.3F), total)) + 4.F; + const bool inline_total = inner >= total_width + 148.F; + ImGui::BeginGroup(); + const float name_width = inline_total ? inner - total_width - 10.F : inner; + OlParagraph("#" + std::to_string(LeaderboardNumber(player, "place")) + " overall", 14.F, kOlSoft, + name_width, false, 1.2F); + OlHeading(StoreText(player, "name", 96), 23.F, kOlCream, name_width, 1.3F); + ImGui::EndGroup(); + if (inline_total) + ImGui::SameLine(0.F, 10.F); + OlHeading(total, 23.F, kOlAmber, inline_total ? total_width : inner, 1.3F); + + const auto tab = [&](const char* label, OverallPlayerTab target) { + if (OlButton(label, target == g_overall_tab ? OlTone::PlateStrong : OlTone::Plain, + std::min(inner, OlButtonWidth(label)), nullptr, 34.F)) + g_overall_tab = target; + StoreControlFocus(); + }; + tab("Score breakdown", OverallPlayerTab::Score); + if (OlButtonWidth("Score breakdown") + OlButtonWidth("Ranked runs") + 6.F <= inner) + ImGui::SameLine(0.F, 6.F); + tab("Ranked runs", OverallPlayerTab::Runs); + + OlPanelLook count_look; + count_look.fill = 0x123648; + const auto stat = [&](float available, const char* label, const std::string& value) { + DrawOlCard(available, count_look, [&](float inside) { + OlParagraph(label, 14.F, kOlSoft, inside, false, 1.2F); + OlHeading(value, 24.F, kOlCream, inside, 1.2F); + }, 8.F); + }; + const bool pair_stats = inner >= 230.F; + const float stat_width = pair_stats ? (inner - 8.F) * .5F : inner; + stat(stat_width, "Posted PBs", OverallPersonalBests(player)); + if (pair_stats) + ImGui::SameLine(0.F, 8.F); + stat(stat_width, "World Records", std::to_string(LeaderboardNumber(player, "records"))); + PaddockGap(3.F); + + if (g_overall_tab == OverallPlayerTab::Score) + DrawOverallScoreBreakdown(inner, player); + else + next = DrawOverallPlayerRuns(inner); + }, 13.F); + return next; +} + +std::optional DrawOverallRankings(float width) { + static bool show_points = false; + if (OlButton(show_points ? "Hide points explanation" : "How points work")) + show_points = !show_points; + StoreControlFocus(); + if (show_points) { + DrawOlFeature(width, "How points work", nullptr, [&](float inner) { + OlParagraph("Verified finishes earn points for placement (70%) and pace against the record (30%). " + "Solo boards count for 35%. Board weight grows to 100% at eight competitors.", + 15.F, kOlSoft, inner); + OlParagraph("Vanilla Tracks 500 | Custom Tracks 250 | Full Game 250", 16.F, kOlAmber, inner, true); + OlParagraph("Track scores use 75% full race and 25% best lap. Your best 10 custom tracks earn up to " + "200 points, and the next 20 earn up to 50. Adding a track keeps your existing points.", + 15.F, kOlSoft, inner); + }); + } + const auto players = g_overall_standings.find("players"); + if (players == g_overall_standings.end() || !players->is_array() || players->empty()) { + OlParagraph(DialogJobRunning() ? "Loading top players..." : players == g_overall_standings.end() + ? "Refresh to load the overall rankings." : "Top players appear after the first published run.", + 15.F, kOlSoft, width); + return {}; + } + + const auto selected = [&] { + return std::ranges::find_if(*players, [](const auto& player) { + return StoreText(player, "id", 96) == g_overall_player; + }); + }; + if (selected() == players->end()) + SelectOverallPlayer(StoreText(players->front(), "id", 96)); + + constexpr float gap = 12.F; + const bool columns = width >= 732.F; + const float standings_width = columns ? std::floor((width - gap) * .48F) : width; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {ImGui::GetStyle().ItemSpacing.x, 6.F}); + ImGui::BeginGroup(); + DrawOverallStandings(standings_width, *players); + ImGui::EndGroup(); + if (columns) + ImGui::SameLine(0.F, gap); + else + PaddockGap(8.F); + + std::optional next; + if (const auto player = selected(); player != players->end()) { + ImGui::BeginGroup(); + next = DrawOverallPlayerPanel(columns ? width - standings_width - gap : width, *player); + ImGui::EndGroup(); + } + ImGui::PopStyleVar(); + return next; +} diff --git a/runtime-recomp/src/game/library_ui/leaderboards_page.inl b/runtime-recomp/src/game/library_ui/leaderboards_page.inl index ab0cdf51..716750ee 100644 --- a/runtime-recomp/src/game/library_ui/leaderboards_page.inl +++ b/runtime-recomp/src/game/library_ui/leaderboards_page.inl @@ -1,11 +1,11 @@ constexpr const char* kLeaderboardWebsite = "https://positron-portal.com/dkr-r/#leaderboards"; -constexpr const char* kLeaderboardPost = "https://positron-portal.com/dkr-r/#post-run"; std::int64_t LeaderboardNumber(const dkr::store::Json& data, const char* key) { const auto value = data.find(key); if (value == data.end() || !value->is_number_integer()) return 0; - return std::clamp(value->get(), std::int64_t(0), std::int64_t(216000)); + return std::clamp(value->get(), std::int64_t(0), + std::int64_t(dkr::runtime::time_trial::kAdventureMaxUpdates * 2)); } std::string LeaderboardTime(std::int64_t ticks) { @@ -16,44 +16,1960 @@ std::string LeaderboardTime(std::int64_t ticks) { return clock; } -void DrawLeaderboardRanking(float width, const dkr::store::Json& board) { - const auto& event = board["board"]; +namespace trial = dkr::runtime::time_trial; +#include "speedrunning_options.inl" + +struct LapReference { + std::array personal{}, best_segments{}; + unsigned world_best_lap = 0; +}; + +using AdventureReference = std::map>; +using AdventureSegments = std::map, std::int64_t>; + +struct TimeTrialRequest { + trial::Mode mode; + std::filesystem::path replay; + std::optional attempt = std::nullopt; + unsigned racer = trial::kDiddy; + const trial::Course* course = &trial::kCourses.front(); + trial::Vehicle vehicle = trial::Vehicle::Car; + trial::Adventure adventure = trial::Adventure::None; + std::string track; + std::filesystem::path ghost; + std::string ghost_name; + LapReference lap_reference; + unsigned prior_best = 0; + AdventureReference adventure_pb, adventure_record; + AdventureSegments adventure_segments; +}; +std::optional g_time_trial_request; +std::optional g_previous_time_trial_request; +std::optional g_local_run_confirmation; +std::filesystem::path g_ranked_playback_file; +unsigned g_run_prior_best = 0; +bool g_open_speedrunning_result = false; +LapReference g_run_lap_reference; +AdventureReference g_adventure_pb_splits, g_adventure_record_splits; +AdventureSegments g_adventure_segments; + +void DeleteRankedPlayback(const std::filesystem::path& file) { + if (file.empty()) + return; + std::error_code error; + std::filesystem::remove(file, error); + std::filesystem::remove(trial::portable_ghost_file(file), error); +} + +void QueueTimeTrialRequest(TimeTrialRequest request, bool signed_in) { + if (signed_in && request.mode == trial::Mode::Record && !request.attempt) + g_local_run_confirmation = std::move(request); + else + g_time_trial_request = std::move(request); +} + +void DrawLocalRunConfirmation() { + if (!g_local_run_confirmation) + return; + constexpr const char* title = "Start a local run?"; + if (!ImGui::IsPopupOpen(title)) + ImGui::OpenPopup(title); + if (!BeginPaddedModal(title, ImGuiWindowFlags_AlwaysAutoResize)) + return; + const auto catalogue = dkr::store::service().view()->speedrun_catalogue; + OlParagraph(catalogue && catalogue->value("canClaimLocal", false) + ? "This run will be saved locally. You can link an eligible run to your Discord account later." + : "This run will be saved locally. Sign in before starting a run to post it to the leaderboard.", + 15.F, kOlInk, 350.F); + if (OlButton("Cancel")) { + if (!g_ranked_playback_file.empty() && g_local_run_confirmation->ghost == g_ranked_playback_file) + DeleteRankedPlayback(std::exchange(g_ranked_playback_file, {})); + g_local_run_confirmation.reset(); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (OlButton("Start local run", OlTone::Go)) { + g_time_trial_request = std::exchange(g_local_run_confirmation, std::nullopt); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +std::string g_time_trial_message; +dkr::store::Json g_ranked_runs = nullptr; +std::string g_ranked_runs_owner; +bool g_ranked_runs_review = false; +std::chrono::steady_clock::time_point g_ranked_runs_received; + +bool LaunchTimeTrial(TimeTrialRequest& request) { + const auto start = [&] { + if (!request.ghost.empty()) + return trial::start_ghost(request.ghost, request.replay, g_time_trial_message, request.racer, + request.mode, {}, request.attempt ? &*request.attempt : nullptr, request.ghost_name); + return trial::start(request.mode, request.replay, g_time_trial_message, + request.attempt ? &*request.attempt : nullptr, request.racer, *request.course, + request.vehicle, request.adventure, request.track); + }; + if (!start()) { + if (!request.ghost.empty() || request.mode != trial::Mode::Record || request.track.empty() || !request.attempt) + return false; + // An installed custom track can differ from the version listed online. + request.attempt.reset(); + if (!start()) + return false; + } + g_run_lap_reference = request.lap_reference; + g_run_prior_best = request.prior_best; + g_adventure_pb_splits = request.adventure_pb; + g_adventure_record_splits = request.adventure_record; + g_adventure_segments = request.adventure_segments; + trial::set_finish_personal_best(request.prior_best); + return true; +} + +std::string RankedRunsOwner() { + const auto file = g_config_directory / "ranked-local.json"; + static std::mutex local_owner_mutex; + std::scoped_lock lock(local_owner_mutex); + static std::filesystem::path prior_file; + static std::string local_owner; + if (file != prior_file) { + prior_file = file; + local_owner.clear(); + try { + const auto local = dkr::store::Json::parse(dkr::updates::read_text(file, 4096)); + const auto port = LeaderboardNumber(local, "port"); + if (port > 1023 && port <= 65535 && StoreText(local, "token", 43).size() == 43) + local_owner = "local-ranked-" + std::to_string(port); + } catch (const std::exception&) { + // Ordinary profiles use the signed-in Mod Library account. + } + } + return local_owner.empty() ? StoreText(dkr::store::service().view()->user, "id", 96) : local_owner; +} + +std::filesystem::path NewTimeTrialFile(const std::filesystem::path& config, const std::string& prefix) { + auto directory = config / "speedruns"; + std::filesystem::create_directories(directory); + const auto stamp = std::chrono::system_clock::now().time_since_epoch().count(); + return directory / (prefix + "-" + std::to_string(stamp) + ".dkrreplay"); +} + +void RankedJob(std::function()> job) { + g_time_trial_message.clear(); + StartDialogJob([job = std::move(job)]() -> std::function { + try { + return job(); + } catch (const std::exception& failure) { + return [message = std::string(failure.what())] { g_time_trial_message = message; }; + } + }); +} + +#include "replay_library.inl" + +void ApplyReplayRetention(const trial::Result& result) { + const auto library = g_config_directory / "speedruns"; + if (!RunPreference(RunOption::Retention) || !result.complete || result.replay || + result.file.parent_path() != library) + return; + try { + const auto replays = ReadLocalReplayLibrary(library); + const auto saved = std::ranges::find(replays, result.file, &LocalReplay::file); + if (saved != replays.end() && saved->local_capture && !saved->personal_best && !saved->beat_ghost && + saved->posted_owner.empty() && !dkr::library_ui::can_post_replay_attempt(saved->has_attempt, saved->practice, false)) + RemoveLocalReplay(saved->file); + } catch (const std::exception&) { + // Keep the recording when the library cannot classify it. + } +} + +std::filesystem::path TimeTrialRom(const TimeTrialRequest& request, const std::filesystem::path& selected, + const std::vector& catalogue) { + namespace rom = dkr::runtime::rom; + const auto& evidence = request.ghost.empty() ? request.replay : request.ghost; + if (request.mode == trial::Mode::Record && request.ghost.empty()) + return selected; + try { + const unsigned revision = ReadReplaySummary(evidence).at("rom").get(); + const auto required = revision == 77 ? rom::Revision::UsV77 : rom::Revision::UsV80; + if (rom::inspect(selected).revision == required) + return selected; + const auto found = std::ranges::find_if(catalogue, [&](const auto& entry) { + return rom::inspect(entry.path).revision == required; + }); + if (found != catalogue.end()) + return found->path; + g_time_trial_message = revision == 77 ? "Add your US v1.0 ROM in Play to watch this replay." + : "Add your US v1.1 ROM in Play to watch this replay."; + } catch (const std::exception& error) { + g_time_trial_message = error.what(); + } + return {}; +} + +bool CanLaunchLeaderboardReplay(); + +double g_ranked_podium_started = -1; + +void DrawRankedPodium() { + const auto state = trial::progress(); + if (!state.finish_update || state.replay || !state.clock || !g_previous_time_trial_request || + g_previous_time_trial_request->mode != trial::Mode::Record) + return; + const auto& attempt = g_previous_time_trial_request->attempt; + const bool pb = !g_run_prior_best || state.clock < g_run_prior_best; + const bool celebration = speed::celebrates(state.podium_place, pb); + if (!celebration && !RunPreference(RunOption::FinishSummary)) + return; + const double now = ImGui::GetTime(); + if (g_ranked_podium_started < 0) { + g_ranked_podium_started = now; + if (celebration) + AchievementChime(RunPreference(RunOption::CueVolume) * .01F); + } + if (now - g_ranked_podium_started >= (celebration ? 4.5 : 2.7)) + return; + + const auto* view = ImGui::GetMainViewport(); + const bool record = state.podium_place == 1; + const std::string heading = !celebration ? "FINISH" : record ? "WORLD RECORD RUN!" : + state.podium_place ? "PODIUM FINISH #" + std::to_string(state.podium_place) : "PERSONAL BEST!"; + const auto art = record || !state.podium_place ? 0xFFCE6C : state.podium_place == 2 ? 0xCED9E9 : 0xF0A477; + const auto ink = PaddockCol(art); + const std::string time = RunClock(state.clock); + const std::string detail = attempt && attempt->finish_targets ? attempt->finish_targets->title + " | " + time : time; + constexpr const char* basis = "Compared with the leaderboard at the start of this run"; + const auto flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoInputs | + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoFocusOnAppearing; + if (!celebration || RunPreference(RunOption::Celebration) == 1) { + const float width = std::min(view->WorkSize.x - 32.F, 350.F); + ImGui::SetNextWindowPos({view->WorkPos.x + view->WorkSize.x * .5F, view->WorkPos.y + 24.F}, 0, {.5F, 0.F}); + ImGui::SetNextWindowSize({width, 0.F}); + ImGui::SetNextWindowBgAlpha(.89F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 12.F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {14.F, 10.F}); + if (ImGui::Begin("##speedrunning-finish", nullptr, flags | ImGuiWindowFlags_AlwaysAutoResize)) { + OlHeading(heading, 22.F, art, width - 28.F); + OlParagraph(detail, 16.F, kOlInk, width - 28.F); + if (celebration && state.podium_place) + OlParagraph(basis, 13.F, kOlSoft, width - 28.F); + } + ImGui::End(); + ImGui::PopStyleVar(2); + return; + } + ImGui::SetNextWindowPos(view->Pos); + ImGui::SetNextWindowSize(view->Size); + ImGui::SetNextWindowBgAlpha(.93F); + ImGui::Begin("##ranked-podium", nullptr, flags); + const auto size = ImGui::GetWindowSize(); + const auto offset = ImGui::GetWindowPos(); + auto* draw = ImGui::GetWindowDrawList(); + const bool motion = !RunPreference(RunOption::ReducedMotion) && + !dkr::runtime::achievements::view()->preferences.reduced_motion; + for (unsigned i = 0; i < (record ? 65U : 32U); ++i) { + const auto x = float((i * 37U) % 97U) / 97.F; + const auto phase = float((i * 23U) % 113U) / 113.F; + const float y = motion ? std::fmod(phase + float(now) * .18F, 1.F) : phase; + draw->AddCircleFilled({offset.x + x * size.x, offset.y + y * size.y}, 1.6F + float(i % 4), ink, 4); + } + const auto title = PaddockSign(std::min(62.F, size.x * .074F)); + const auto ext = title.font->CalcTextSizeA(title.size, FLT_MAX, 0.F, heading.c_str()); + draw->AddText(title.font, title.size, {offset.x + (size.x - ext.x) * .5F, offset.y + size.y * .28F}, + ink, heading.c_str()); + ImGui::SetCursorPos({std::max(14.F, (size.x - ImGui::CalcTextSize(detail.c_str()).x) * .5F), size.y * .46F}); + ImGui::TextUnformatted(detail.c_str()); + if (state.podium_place) { + ImGui::SetCursorPos({std::max(14.F, (size.x - ImGui::CalcTextSize(basis).x) * .5F), size.y * .62F}); + ImGui::TextDisabled("%s", basis); + } + ImGui::End(); +} + +std::optional ReadFinishTargets(const dkr::store::Json& reply) { + const auto found = reply.find("finishTargets"); + if (found == reply.end() || !found->is_object()) + return {}; + trial::FinishTargets targets{StoreText(*found, "title", 120), unsigned(LeaderboardNumber(*found, "personal"))}; + const auto times = found->find("rivals"); + if (targets.title.empty() || times == found->end() || !times->is_array() || times->size() > targets.rivals.size()) + return {}; + for (std::size_t index = 0; index < times->size(); ++index) { + const auto& time = (*times)[index]; + if (!time.is_number_integer()) + return {}; + const auto ticks = time.get(); + if (ticks <= 0 || ticks > trial::kAdventureMaxUpdates * 2) + return {}; + targets.rivals[index] = unsigned(ticks); + } + return targets; +} + +std::string TrackAttemptBoard(const dkr::store::Json* catalogue, std::string_view id, const trial::Course* course, + trial::Vehicle vehicle, unsigned racer) { + if (course) + return trial::board_for(*course, vehicle, racer); + if (!catalogue || !catalogue->contains("boards") || !catalogue->value("canSubmitCustom", false)) + return {}; + for (const auto& entry : catalogue->at("boards")) { + if (!entry.value("ranked", false)) + continue; + if (StoreText(entry, "trackId", 96) == id && + StoreText(entry, "vehicle", 24) == trial::kVehicleIds[static_cast(vehicle)] && + StoreText(entry, "racer", 32) == trial::kRacers[racer].name) + return StoreText(entry, "id", 96); + } + return {}; +} + +std::optional RequestTrackAttempt(const std::string& board, std::string_view id, + const trial::Course* course, trial::Vehicle vehicle, unsigned racer) { + if (board.empty()) + return {}; + try { + const auto reply = dkr::store::service().ranked_attempt(board); + const auto board_id = StoreText(reply, "board", 96); + const auto engine = StoreText(reply, "engine", 64); + const auto ticket = StoreText(reply, "ticket", 160); + if (board_id != board) + return {}; + auto attempt = course ? trial::parse_attempt(board_id, engine, ticket, *course, vehicle, racer) + : trial::parse_custom_attempt(board_id, engine, ticket, StoreText(reply, "releaseId", 96), + StoreText(reply, "releaseHash", 64), + StoreText(reply, "trackId", 96), + StoreText(reply, "trackHash", 64), vehicle, racer); + if (!attempt || (!course && attempt->track_id != id)) + return {}; + attempt->finish_targets = ReadFinishTargets(reply); + return attempt; + } catch (const std::exception&) { + // The player can still race locally when the service is unavailable. + return {}; + } +} + +std::pair ReadRunReference(const std::filesystem::path& directory, const std::string& id, + const trial::Course* course, trial::Vehicle vehicle, unsigned racer, + std::string_view track_hash); + +TimeTrialRequest PrepareGhostRun(const std::filesystem::path& file, const std::filesystem::path& config, + std::optional local_racer, bool signed_in) { + const auto manifest = ReadReplaySummary(file); + const auto racer = local_racer ? *local_racer : manifest.value("racer", trial::kDiddy); + if (racer >= trial::kRacers.size()) + throw std::runtime_error("The replay racer is unsupported."); + TimeTrialRequest request{trial::Mode::Record, NewTimeTrialFile(config, "Ghost-Practice")}; + request.racer = racer; + request.ghost = file; + const auto rules = StoreText(manifest, "ruleset", 48); + const bool custom = rules == trial::kCustomRules || rules == trial::kCustomVariableLapsRules; + const auto id = StoreText(manifest, custom ? "trackId" : "course", 96); + const auto* course = custom ? nullptr : rules == trial::kLegacyRules ? &trial::kCourses.front() + : trial::course_for(id); + if (!custom && !course) + return request; + const auto vehicle_id = rules == trial::kLegacyRules ? "car" : StoreText(manifest, "vehicle", 16); + const auto vehicle = std::ranges::find(trial::kVehicleIds, vehicle_id); + if (vehicle == trial::kVehicleIds.end()) + return request; + const auto chosen = static_cast(vehicle - trial::kVehicleIds.begin()); + const auto snapshot = dkr::store::service().view(); + const auto board = signed_in ? TrackAttemptBoard(snapshot->speedrun_catalogue.get(), id, course, chosen, racer) + : std::string{}; + request.attempt = RequestTrackAttempt(board, id, course, chosen, racer); + if (custom && request.attempt && request.attempt->track_hash != StoreText(manifest, "trackHash", 64)) + request.attempt.reset(); + std::tie(request.lap_reference, request.prior_best) = + ReadRunReference(config / "speedruns", course ? std::string(course->id) : id, course, chosen, racer, + StoreText(manifest, "trackHash", 64)); + return request; +} + +void RaceReplayGhost(const std::filesystem::path& file) { + RankedJob([file, config = g_config_directory, signed_in = !RankedRunsOwner().empty()] { + auto request = PrepareGhostRun(file, config, std::nullopt, signed_in); + return [request = std::move(request), signed_in]() mutable { + QueueTimeTrialRequest(std::move(request), signed_in); + }; + }); +} + +struct PublishedReplayTimes { + std::filesystem::path profile; + std::string owner; + std::optional> scores; + std::chrono::steady_clock::time_point refresh_at{}; + bool unavailable = false; +}; +PublishedReplayTimes g_published_replay_times; + +void SavePublishedReplayTimes(const std::filesystem::path& profile, const std::string& owner, + std::optional> scores) { + if (profile == g_config_directory && owner == RankedRunsOwner()) { + const bool unavailable = !scores; + g_published_replay_times = {profile, owner, std::move(scores), + std::chrono::steady_clock::now() + std::chrono::seconds(30), unavailable}; + } +} + +void RefreshPublishedReplayTimes(const std::string& owner) { + auto& status = g_published_replay_times; + if (status.profile != g_config_directory || status.owner != owner) + status = {g_config_directory, owner}; + const auto now = std::chrono::steady_clock::now(); + if (now < status.refresh_at || DialogJobRunning()) + return; + status.refresh_at = now + std::chrono::seconds(30); + StartDialogJob([profile = status.profile, owner]() -> std::function { + std::optional> scores; + try { + scores = dkr::store::service().published_replay_times(); + } catch (const std::exception&) { + // Keep the posting decision pending until the signed-in player's times are known. + } + return [profile, owner, scores = std::move(scores)]() mutable { + SavePublishedReplayTimes(profile, owner, std::move(scores)); + }; + }); +} + +std::function SubmitRankedReplay(const std::filesystem::path& file, const std::filesystem::path& profile, + bool personal_best, bool link_local = false, std::string expected_owner = {}) { + const auto owner = RankedRunsOwner(); + if (link_local && owner != expected_owner) + throw std::runtime_error("Your signed-in account changed. Confirm the Discord account again."); + auto metadata = ReadReplaySidecar(file); + if (owner.empty() || file.parent_path() != profile / "speedruns" || !OwnReplayFile(file, metadata)) + throw std::runtime_error("Sign in and select one of your eligible recordings to post it."); + const auto manifest = ReadReplaySummary(file); + if (link_local ? !IsLocalReplayCapture(manifest) : !ReplayHasRankedAttempt(manifest)) + throw std::runtime_error("Sign in and select one of your eligible recordings to post it."); + if (personal_best && !link_local) { + auto scores = dkr::store::service().published_replay_times(); + if (std::ranges::binary_search(scores, dkr::store::PublishedReplayTime{ + StoreText(manifest, "board", 96), + LeaderboardNumber(manifest, "clockTicks")})) { + return [profile, owner, scores = std::move(scores)]() mutable { + SavePublishedReplayTimes(profile, owner, std::move(scores)); + }; + } + } + const auto reply = dkr::store::service().submit_ranked_replay(file, link_local); + const auto state = StoreText(reply.at("run"), "state", 32); + try { + metadata["postedOwner"] = owner; + WriteReplaySidecar(file, metadata); + } catch (const std::exception&) { + // The service has accepted the replay even if the local receipt could not be written. + } + return [file, profile, state, owner] { + if (profile == g_config_directory && owner == RankedRunsOwner()) { + g_time_trial_message = "Run submitted | " + state; + g_ranked_runs = nullptr; + for (auto& replay : g_local_replays) + if (replay.file == file) + replay.posted_owner = owner; + } + }; +} + +void DrawReplayResult(const LocalReplay& replay) { + if (replay.personal_best) + DrawRaceBadge("PERSONAL BEST", {.36F, .245F, .09F, 1.F}); + if (replay.beat_ghost) + DrawRaceBadge("GHOST BEATEN", {.11F, .29F, .24F, 1.F}); +} + +std::string LocalClaimBoard(const LocalReplay& replay, const dkr::store::Json& catalogue) { + if (replay.track_id.empty()) + return replay.board; + const auto vehicle = std::ranges::find(trial::kVehicleNames, replay.vehicle); + if (vehicle == trial::kVehicleNames.end() || !catalogue.contains("boards")) + return {}; + std::string board; + for (const auto& entry : catalogue.at("boards")) { + if (entry.value("ranked", false) && StoreText(entry, "trackId", 96) == replay.track_id && + StoreText(entry, "trackHash", 64) == replay.track_hash && + StoreText(entry, "vehicle", 24) == trial::kVehicleIds[vehicle - trial::kVehicleNames.begin()] && + StoreText(entry, "racer", 32) == replay.racer) { + if (!board.empty()) + return {}; + board = StoreText(entry, "id", 96); + } + } + return board; +} + +void DrawLocalReplayPosting(const LocalReplay& replay, float width, const dkr::store::Json* catalogue) { + const auto snapshot = dkr::store::service().view(); + const auto owner = RankedRunsOwner(); + if (!replay.posted_owner.empty()) { + OlParagraph(owner == replay.posted_owner ? "Submitted · View status in My Submitted Runs" + : "This run has already been linked to a Discord account.", + 14.F, kOlSoft, width); + return; + } + constexpr const char* popup = "Link this local run?"; + const bool confirming = ImGui::IsPopupOpen(popup); + if (!confirming && catalogue) { + if (const auto board = LocalClaimBoard(replay, *catalogue); !board.empty() && !owner.empty()) { + RefreshPublishedReplayTimes(owner); + const auto& scores = g_published_replay_times.scores; + if (scores && std::ranges::binary_search(*scores, dkr::store::PublishedReplayTime{board, replay.time})) { + OlParagraph("Already on the leaderboard", 14.F, kOlSoft, width); + return; + } + } + } + + const OlDisabled busy(DialogJobRunning()); + if (owner.empty() && !confirming) { + if (OlButton("Sign in with Discord to link", OlTone::Go)) + dkr::store::service().login(); + return; + } + + static std::string confirmed_owner; + if (OlButton("Link & Post to Leaderboard", OlTone::Go)) { + confirmed_owner = owner; + ImGui::OpenPopup(popup); + } + constexpr ImGuiWindowFlags flags = ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; + if (!BeginPaddedModal(popup, flags)) + return; + const auto name = StoreText(snapshot->user, "displayName", 100); + const auto credit = name.empty() ? std::string("your signed-in Discord account") : name; + const auto text_width = std::min(435.F, ImGui::GetMainViewport()->WorkSize.x * .7F); + OlParagraph("Link " + replay.title + " to " + credit + + " and send it for verification? The recording can only be linked once.", + 16.F, kOlInk, text_width); + PaddockGap(10.F); + const bool cancel = OlButton("Cancel") || ImGui::IsKeyPressed(ImGuiKey_Escape, false) || + ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false) || confirmed_owner != owner; + ImGui::SameLine(); + if (OlButton("Link & Post", OlTone::Go) && !cancel) { + RankedJob([file = replay.file, profile = g_config_directory, owner] { + return SubmitRankedReplay(file, profile, false, true, owner); + }); + ImGui::CloseCurrentPopup(); + } else if (cancel) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +void DrawReplayPosting(const LocalReplay& replay, float width, bool explain = false) { + const bool merit = replay.personal_best || replay.beat_ghost; + if (replay.local_capture && (merit || !replay.posted_owner.empty())) { + const auto catalogue = dkr::store::service().view()->speedrun_catalogue; + if (!replay.posted_owner.empty() || (catalogue && catalogue->value("canClaimLocal", false))) { + DrawLocalReplayPosting(replay, width, catalogue.get()); + return; + } + } + if (!dkr::library_ui::can_post_replay_attempt(replay.has_attempt, replay.practice, merit)) { + if (!replay.has_attempt && (merit || explain)) + OlParagraph("Linking this local run is unavailable.", 14.F, kOlSoft, + width); + else if (explain) + OlParagraph("You can post this run if it's your personal best.", 14.F, kOlSoft, width); + return; + } + const auto owner = RankedRunsOwner(); + if (owner.empty()) { + OlParagraph("Sign in to post this run.", 14.F, kOlSoft, width); + } else if (owner == replay.posted_owner) { + OlParagraph("Submitted · View status in My Submitted Runs", 14.F, kOlSoft, width); + } else { + if (merit) { + RefreshPublishedReplayTimes(owner); + const auto& status = g_published_replay_times; + if (!status.scores) { + if (explain || status.unavailable) + OlParagraph(status.unavailable ? "Could not check your published times." + : "Checking your published times...", + 14.F, kOlSoft, width); + return; + } + if (std::ranges::binary_search(*status.scores, dkr::store::PublishedReplayTime{replay.board, replay.time})) { + OlParagraph("Already on the leaderboard", 14.F, kOlSoft, width); + return; + } + } + const OlDisabled busy(DialogJobRunning()); + if (OlButton("Post to Leaderboard", OlTone::Go)) + RankedJob([file = replay.file, profile = g_config_directory, best = merit] { + return SubmitRankedReplay(file, profile, best); + }); + } +} + +std::optional g_split_bounds; + +std::array ReplayLaps(const dkr::store::Json& manifest) { + std::array laps{}; + const auto splits = manifest.find("splits"); + if (splits == manifest.end() || !splits->is_array() || splits->size() > laps.size()) + return laps; + unsigned previous = 0; + for (std::size_t i = 0; i < splits->size(); ++i) { + if (!(*splits)[i].is_number_unsigned()) + return {}; + const auto time = (*splits)[i].get(); + if (time <= previous) + return {}; + laps[i] = time - previous; + previous = time; + } + return laps; +} + +std::pair ReadRunReference(const std::filesystem::path& directory, const std::string& id, + const trial::Course* course, trial::Vehicle vehicle, unsigned racer, + std::string_view track_hash) { + LapReference result; + unsigned best = 0; + try { + for (const auto& replay : ReadLocalReplayLibrary(directory)) { + if (!replay.valid || replay.racer != trial::kRacers[racer].name || + replay.vehicle != trial::kVehicleNames[static_cast(vehicle)] || + (course ? replay.course != course->name || !replay.track_id.empty() : replay.track_id != id) || + (!track_hash.empty() && !course && replay.track_hash != track_hash)) + continue; + const auto laps = ReplayLaps(ReadReplaySummary(replay.file)); + for (std::size_t i = 0; i < laps.size(); ++i) + if (laps[i] && (!result.best_segments[i] || laps[i] < result.best_segments[i])) + result.best_segments[i] = laps[i]; + if (replay.time > 0 && (!best || replay.time < best)) { + best = unsigned(replay.time); + result.personal = laps; + } + } + } catch (const std::exception&) { + // An unavailable reference should leave a run playable. + } + const auto catalogue = dkr::store::service().view()->speedrun_catalogue; + if (catalogue) { + const auto rows = catalogue->find(course ? "vanillaTracks" : "customTracks"); + if (rows != catalogue->end() && rows->is_array()) { + const auto row = std::ranges::find_if(*rows, [&](const auto& item) { return StoreText(item, "id", 96) == id; }); + if (row != rows->end()) { + const auto leaders = row->find("leaders"); + if (leaders != row->end() && leaders->is_object()) { + const auto standings = leaders->find(trial::kVehicleIds[static_cast(vehicle)]); + if (standings != leaders->end() && standings->is_object()) { + const auto lap = standings->find("lap"); + if (lap != standings->end()) + result.world_best_lap = unsigned(LeaderboardNumber(*lap, "ticks")); + } + } + } + } + } + return {result, best}; +} + +AdventureReference ReadAdventureReference(const dkr::store::Json& run) { + AdventureReference reference; + const auto splits = run.find("splits"); + if (splits == run.end() || !splits->is_array() || splits->size() > 64) + return reference; + for (const auto& split : *splits) { + if (split.is_array() && split.size() == 2 && split[0].is_string() && split[1].is_number_integer()) { + const auto label = split[0].get(); + const auto ticks = split[1].get(); + if (label.size() <= 64 && ticks > 0 && ticks <= trial::kAdventureMaxUpdates * 2) + reference.try_emplace(label, ticks); + } + } + return reference; +} + +void DrawRunDelta(const char* label, std::int64_t actual, std::int64_t reference) { + if (!reference) + return; + const auto delta = actual - reference; + ImGui::SameLine(); + const auto colour = delta < 0 ? kOlGoText : delta > 0 ? kOlAmber : kOlSoft; + const bool words = RunPreference(RunOption::DeltaWords); + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(PaddockCol(colour)), "%s %s%s%s", label, + words ? "" : delta < 0 ? "-" : delta > 0 ? "+" : "", RunClock(std::abs(delta)).c_str(), + words ? delta < 0 ? " ahead" : delta > 0 ? " behind" : " even" : ""); +} + +void DrawAdventureDelta(std::span splits) { + if (splits.empty()) + return; + const auto& split = splits.back(); + const auto comparison = RunPreference(RunOption::Comparison); + if (comparison < 2) { + const auto& reference = comparison == 0 ? g_adventure_pb_splits : g_adventure_record_splits; + if (const auto match = reference.find(split.label); match != reference.end()) + DrawRunDelta(comparison == 0 ? "PB" : "WR", split.clock, match->second); + } else if (comparison == 2) { + std::int64_t total = 0; + std::string previous; + for (const auto& stage : splits) { + const auto segment = g_adventure_segments.find({previous, std::string(stage.label)}); + if (segment == g_adventure_segments.end()) + return; + total += segment->second; + previous = stage.label; + } + DrawRunDelta("Best segments", split.clock, total); + } +} + +void DrawTimeTrialHud(bool video = false) { + g_split_bounds.reset(); + const auto state = trial::progress(); + const bool preparing = trial::preparing_ghost(); + if (!state.lap && !preparing && state.adventure == trial::Adventure::None) + return; + const bool splits = video || (RunPreference(RunOption::Splits) && + (!state.replay || RunPreference(RunOption::ReplaySplits))); + const bool gap = !video && state.ghost && RunPreference(RunOption::GhostGap) && state.ghost_gap.has_value(); + if (!preparing && !splits && !gap) + return; + const auto* viewport = ImGui::GetMainViewport(); + if (preparing) { + auto* draw = ImGui::GetBackgroundDrawList(); + draw->AddRectFilled(viewport->Pos, + {viewport->Pos.x + viewport->Size.x, viewport->Pos.y + viewport->Size.y}, + IM_COL32(6, 18, 28, 240)); + } + const auto corner = RunOverlayCorner(*viewport, RunPreference(RunOption::SplitPosition)); + ImGui::SetNextWindowPos(video ? ImVec2{viewport->WorkPos.x + 16.F, viewport->WorkPos.y + 16.F} : corner.position, + ImGuiCond_Always, video ? ImVec2{} : corner.pivot); + if (video) + ImGui::SetNextWindowSizeConstraints({0.F, 0.F}, {viewport->WorkSize.x * .47F, viewport->WorkSize.y * .48F}); + const bool contrast = !video && RunPreference(RunOption::Contrast); + ImGui::SetNextWindowBgAlpha(video ? .78F : contrast ? 1.F : RunPreference(RunOption::Background) * .01F); + if (contrast) + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(.025F, .055F, .085F, 1.F)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 9.F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(12.F, 9.F)); + constexpr auto flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoSavedSettings; + if (ImGui::Begin("Time Trial HUD", nullptr, flags)) { + ImGui::SetWindowFontScale(video ? 1.F : std::array{.85F, 1.F, 1.24F}[RunPreference(RunOption::HudSize)]); + if (preparing) { + ImGui::TextUnformatted("Preparing ghost"); + if (state.finish_update) + ImGui::ProgressBar(float(state.updates) / float(state.finish_update), {205.F, 8.F}, ""); + ImGui::End(); + ImGui::PopStyleVar(2); + if (contrast) + ImGui::PopStyleColor(); + return; + } + if (gap) { + const auto delta = *state.ghost_gap; + const bool words = RunPreference(RunOption::DeltaWords); + ImGui::Text("Ghost %s%s%s", words ? "" : delta < 0 ? "-" : delta > 0 ? "+" : "", + RunClock(std::abs(delta)).c_str(), words ? delta < 0 ? " ahead" : delta > 0 ? " behind" : " even" : ""); + } + if (splits) { + const int detail = video ? 0 : RunPreference(RunOption::SplitDetail); + if (state.adventure != trial::Adventure::None) { + for (const auto& category : trial::kAdventureCategories) + if (category.goal == state.adventure) + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(PaddockCol(kOlAmber)), "%s", + category.title.data()); + } else { + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(PaddockCol(kOlAmber)), "%s | Lap %u / %u", + state.replay ? "Replay" + : state.ghost ? "Ghost Race" + : "Time Trial", + state.lap, state.lap_count); + } + const auto elapsed = state.started ? (video ? LeaderboardTime(state.clock) : RunClock(state.clock)) : std::string("Ready"); + ImGui::TextUnformatted(elapsed.c_str()); + if (detail != 2 && state.adventure != trial::Adventure::None) { + const auto splits = trial::adventure_splits(); + if (!splits.empty()) + ImGui::Separator(); + if (video) { + for (const auto& split : std::span(splits).last(std::min(4, splits.size()))) { + const auto time = LeaderboardTime(split.clock); + ImGui::Text("%.*s %s", static_cast(split.label.size()), split.label.data(), time.c_str()); + } + } else { + const auto upcoming = trial::AdventureSplits::upcoming(state.adventure, splits); + const auto capacity = static_cast( + std::clamp((viewport->WorkSize.y * .40F - 74.F) / ImGui::GetTextLineHeightWithSpacing(), 3.F, 30.F)); + const auto reserve = std::min({upcoming.size(), capacity - std::min(splits.size(), std::size_t{2}), + std::size_t(RunPreference(RunOption::Upcoming))}); + const auto recent = std::min(splits.size(), detail == 1 ? std::size_t{1} : capacity - reserve); + for (const auto& split : std::span(splits).last(recent)) { + const auto time = RunClock(split.clock); + ImGui::Text("%.*s %s", static_cast(split.label.size()), split.label.data(), time.c_str()); + if (!state.replay && &split == &splits.back()) + DrawAdventureDelta(splits); + } + if (reserve) { + ImGui::Separator(); + for (std::size_t row = 0; row < reserve; ++row) { + const auto stage = upcoming[row]; + if (row == 0) + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(PaddockCol(kOlAmber)), "Next %.*s", + int(stage.size()), stage.data()); + else + ImGui::TextDisabled("%.*s", int(stage.size()), stage.data()); + } + } + } + } + if (detail != 2 && state.recent_split && (video || RunPreference(RunOption::LapDelta))) { + ImGui::Text("Last lap %s", (video ? LeaderboardTime(state.recent_split) : RunClock(state.recent_split)).c_str()); + if (!state.replay && state.completed_laps) { + const auto lap = state.completed_laps - 1; + switch (RunPreference(RunOption::Comparison)) { + case 0: DrawRunDelta("PB", state.recent_split, g_run_lap_reference.personal[lap]); break; + case 1: DrawRunDelta("WR lap", state.recent_split, g_run_lap_reference.world_best_lap); break; + case 2: DrawRunDelta("Best lap", state.recent_split, g_run_lap_reference.best_segments[lap]); break; + } + } + } + if (!video && detail != 2 && !state.finish_update && state.adventure == trial::Adventure::None && + state.lap <= state.lap_count) { + const auto next = std::max(1U, state.lap); + const auto rows = std::min(unsigned(RunPreference(RunOption::Upcoming)), state.lap_count + 1 - next); + for (unsigned step = 0; step < rows; ++step) + ImGui::TextDisabled("%s %s", step ? "Then" : "Next", + next + step == state.lap_count ? "Finish" : + ("Lap " + std::to_string(next + step + 1)).c_str()); + } + if (state.finish_update && !state.replay && state.adventure == trial::Adventure::None) + ImGui::TextUnformatted("Recording the finish"); + if (!video && state.total_updates) + ImGui::ProgressBar(float(state.updates) / float(state.total_updates), {152.F, 8.F}, ""); + } + const auto pos = ImGui::GetWindowPos(), size = ImGui::GetWindowSize(); + g_split_bounds = ImVec4{pos.x, pos.y, pos.x + size.x, pos.y + size.y}; + } + ImGui::End(); + ImGui::PopStyleVar(2); + if (contrast) + ImGui::PopStyleColor(); +} + +bool g_theatre_controls = true; +bool g_theatre_inputs = false; +int g_theatre_controller_corner = -1; +std::atomic g_theatre_activity{}; + +void SeekReplaySeconds(int direction) { + const auto state = trial::progress(); + const auto transport = trial::theatre(); + const auto frame = transport.seeking ? transport.seek_to : state.updates; + const int step = speed::seek_seconds[RunPreference(RunOption::SeekStep)] * 30; + if (state.total_updates) + trial::theatre_seek(unsigned(std::clamp(int(frame) + direction * step, 1, int(state.total_updates)))); +} + +bool HandleTheatreInput(const SDL_Event& event) { + g_theatre_activity = SDL_GetTicks64(); + if (event.type == SDL_CONTROLLERBUTTONDOWN && event.cbutton.button == SDL_CONTROLLER_BUTTON_START) { + trial::theatre_play_pause(); + return true; + } + if (event.type != SDL_KEYDOWN || event.key.repeat) + return false; + switch (event.key.keysym.scancode) { + case SDL_SCANCODE_ESCAPE: + case SDL_SCANCODE_SPACE: + trial::theatre_play_pause(); + return true; + case SDL_SCANCODE_F8: + g_theatre_controls = !g_theatre_controls; + return true; + case SDL_SCANCODE_COMMA: + trial::theatre_step(-1); + return true; + case SDL_SCANCODE_PERIOD: + trial::theatre_step(1); + return true; + case SDL_SCANCODE_LEFT: + case SDL_SCANCODE_RIGHT: + if (event.key.keysym.mod & KMOD_CTRL) { + SeekReplaySeconds(event.key.keysym.scancode == SDL_SCANCODE_LEFT ? -1 : 1); + return true; + } + return false; + default: + return false; + } +} + +void PaintReplayController(ImDrawList* draw, ImVec2 base, const trial::Progress& state, float scale) { + const auto point = [&](float x, float y) { return ImVec2{base.x + x * scale, base.y + y * scale}; }; + const auto shell = PaddockCol(0xA2B0C7); + draw->AddRectFilled(point(9, 15), point(223, 76), shell, 29.F * scale); + draw->AddQuadFilled(point(12, 43), point(63, 57), point(48, 121), point(19, 116), shell); + draw->AddQuadFilled(point(91, 57), point(141, 57), point(134, 136), point(98, 136), shell); + draw->AddQuadFilled(point(172, 57), point(221, 43), point(213, 117), point(185, 120), shell); + const auto button = [&](const char* label, float x, float y, float radius, unsigned bit, unsigned color) { + const bool pressed = (state.buttons & bit) != 0; + draw->AddCircleFilled(point(x, y), radius * scale, PaddockCol(color)); + if (pressed) + draw->AddCircle(point(x, y), (radius + 2.F) * scale, PaddockCol(0xFFF0B0), 20, 2.6F * scale); + const auto size = ImGui::CalcTextSize(label); + draw->AddText(ImGui::GetFont(), ImGui::GetFontSize() * scale, point(x - size.x * .5F, y - size.y * .5F), + PaddockCol(0x102033), label); + }; + button("L", 40, 17, 10, 0x0020, 0xC4CFDD); + button("R", 187, 17, 10, 0x0010, 0xC4CFDD); + button("Z", 202, 101, 10, 0x2000, 0xC4CFDD); + button("A", 155, 60, 12, 0x8000, 0x5191F4); + button("B", 142, 41, 10, 0x4000, 0x5CD693); + button("", 115, 31, 6, 0x1000, 0xED6462); + button("", 184, 33, 6, 0x0008, 0xFFCD57); + button("", 173, 44, 6, 0x0002, 0xFFCD57); + button("", 195, 44, 6, 0x0001, 0xFFCD57); + button("", 184, 55, 6, 0x0004, 0xFFCD57); + const auto dpad = PaddockCol(0x344459); + draw->AddRectFilled(point(32, 53), point(63, 63), dpad); + draw->AddRectFilled(point(42, 43), point(53, 74), dpad); + const auto active = PaddockCol(0xFFF0B0); + if (state.buttons & 0x0800) draw->AddRectFilled(point(42, 43), point(53, 53), active); + if (state.buttons & 0x0400) draw->AddRectFilled(point(42, 63), point(53, 74), active); + if (state.buttons & 0x0200) draw->AddRectFilled(point(32, 53), point(42, 63), active); + if (state.buttons & 0x0100) draw->AddRectFilled(point(53, 53), point(63, 63), active); + draw->AddCircleFilled(point(115, 68), 20.F * scale, PaddockCol(0x64758E), 8); + const float x = 115.F + 12.F * std::clamp(float(state.stick_x) / 80.F, -1.F, 1.F); + const float y = 68.F - 12.F * std::clamp(float(state.stick_y) / 80.F, -1.F, 1.F); + draw->AddCircleFilled(point(x, y), 8.F * scale, PaddockCol(0xCED9E9)); + draw->AddCircle(point(x, y), 4.F * scale, PaddockCol(0x8999AF)); +} + +void DrawReplayController(const trial::Progress& state, float scale) { + PaintReplayController(ImGui::GetWindowDrawList(), ImGui::GetCursorScreenPos(), state, scale); + ImGui::Dummy({232.F * scale, 140.F * scale}); +} + +void DrawReplayInputViewer(const trial::Progress& state, bool video = false) { + if (!video && !g_theatre_inputs) + return; + const auto* view = ImGui::GetMainViewport(); + ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse; + if (video) { + if (state.adventure != trial::Adventure::None) { + // Full Game splits own the upper-left of the picture. Anchor the + // controls in the opposite corner with a bounded footprint. + ImGui::SetNextWindowPos({view->WorkPos.x + view->WorkSize.x - 16.F, + view->WorkPos.y + view->WorkSize.y - 16.F}, + ImGuiCond_Always, {1.F, 1.F}); + ImGui::SetNextWindowSizeConstraints({0.F, 0.F}, {view->WorkSize.x * .47F, view->WorkSize.y * .43F}); + } else { + ImGui::SetNextWindowPos({view->WorkPos.x + 16.F, view->WorkPos.y + view->WorkSize.y * .43F}, + ImGuiCond_Always); + } + flags |= ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoSavedSettings; + } else { + const auto corner = RunPreference(RunOption::InputPosition); + auto anchor = RunOverlayCorner(*view, corner); + const auto scale = std::array{.78F, 1.F, 1.18F}[RunPreference(RunOption::InputSize)]; + const float height = 140.F * scale + 54.F; + const auto* existing = ImGui::FindWindowByName("Replay Controller"); + const auto intersects = [&](ImVec2 point, ImVec2 size) { + return g_split_bounds && point.x < g_split_bounds->z && point.x + size.x > g_split_bounds->x && + point.y < g_split_bounds->w && point.y + size.y > g_split_bounds->y; + }; + const auto space = ImVec2{232.F * scale + 28.F, height}; + const auto proposed = ImVec2{anchor.position.x - anchor.pivot.x * space.x, + anchor.position.y - anchor.pivot.y * space.y}; + const bool conflict = intersects(proposed, space); + if (conflict) { + anchor.position.y = anchor.pivot.y == 0.F ? g_split_bounds->w + 8.F : g_split_bounds->y - 8.F; + if (anchor.position.y - anchor.pivot.y * height < view->WorkPos.y || + anchor.position.y + (1.F - anchor.pivot.y) * height > view->WorkPos.y + view->WorkSize.y) + anchor = RunOverlayCorner(*view, corner ^ 1); + } + const bool reposition = corner != g_theatre_controller_corner || + (existing && intersects(existing->Pos, existing->Size)); + ImGui::SetNextWindowPos(anchor.position, reposition ? ImGuiCond_Always : ImGuiCond_FirstUseEver, anchor.pivot); + g_theatre_controller_corner = corner; + } + ImGui::SetNextWindowBgAlpha(!video && RunPreference(RunOption::Contrast) ? 1.F : .84F); + if (ImGui::Begin("Replay Controller", video ? nullptr : &g_theatre_inputs, flags)) + DrawReplayController(state, video ? .78F : std::array{.78F, 1.F, 1.18F}[RunPreference(RunOption::InputSize)]); + ImGui::End(); +} + +void DrawReplayTheatre() { + const auto state = trial::progress(); + if (!state.total_updates) + return; + auto transport = trial::theatre(); + // Let RT64 present through the launcher handoff before holding frame one. + if (transport.pause_on_open && !transport.buffering && state.updates) { + trial::theatre_complete_intro(); + transport = trial::theatre(); + } + const auto file = trial::watched_replay(); + const bool local = file.parent_path() == g_config_directory / "speedruns"; + if (local && g_refresh_replay_library && !DialogJobRunning()) + RefreshReplayLibrary(); + const auto* view = ImGui::GetMainViewport(); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 13.F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {14.F, 13.F}); + if (transport.buffering) { + ImGui::SetNextWindowPos(view->GetCenter(), ImGuiCond_Always, {.5F, .5F}); + ImGui::SetNextWindowBgAlpha(.94F); + if (ImGui::Begin("Preparing replay", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize)) { + const auto at = ImGui::GetCursorScreenPos(); + auto* draw = ImGui::GetWindowDrawList(); + const float phase = RunPreference(RunOption::ReducedMotion) ? 0.F : float(ImGui::GetTime() * 5.5); + draw->PathArcTo({at.x + 12.F, at.y + 12.F}, 9.F, phase, phase + 4.7F, 18); + draw->PathStroke(PaddockCol(kOlAmber), 0, 2.4F); + ImGui::Dummy({27.F, 24.F}); + ImGui::SameLine(); + ImGui::TextUnformatted("Preparing replay..."); + if (OlButton("Cancel", OlTone::Plain, 0.F, nullptr, 28.F)) + trial::theatre_exit(); + } + ImGui::End(); + ImGui::PopStyleVar(2); + return; + } + DrawReplayInputViewer(state); + constexpr const char* theatre_window = "Replay Theatre · F8 to show or hide"; + if (const auto* previous = ImGui::FindWindowByName(theatre_window)) { + const auto far_corner = ImVec2{previous->Pos.x + previous->Size.x, previous->Pos.y + previous->Size.y}; + if (ImGui::IsMouseHoveringRect(previous->Pos, far_corner)) + g_theatre_activity = SDL_GetTicks64(); + } + const bool auto_hidden = RunPreference(RunOption::PlaybackControls) && !transport.paused && !transport.seeking && + !transport.finished && SDL_GetTicks64() - g_theatre_activity.load() > 3000; + if (!g_theatre_controls || auto_hidden) { + ImGui::PopStyleVar(2); + return; + } + const float width = std::min(730.F, view->WorkSize.x - 24.F); + ImGui::SetNextWindowPos({view->WorkPos.x + view->WorkSize.x / 2.F, view->WorkPos.y + view->WorkSize.y - 14.F}, + ImGuiCond_FirstUseEver, {0.5F, 1.F}); + ImGui::SetNextWindowSize({width, 0.F}); + ImGui::SetNextWindowBgAlpha(.86F); + constexpr auto flags = ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize; + if (ImGui::Begin(theatre_window, &g_theatre_controls, flags)) { + static std::optional drag_target; + if (ImGui::IsWindowAppearing()) { + drag_target.reset(); + ImGui::SetWindowFocus(); + } + const auto time = RunClock(state.clock); + ImGui::Text("REPLAY THEATRE | %s", trial::kRacers[state.racer].name.data()); + ImGui::SameLine(); + ImGui::Text("%s | Frame %u / %u%s", time.c_str(), state.updates, state.total_updates, + transport.finished && !transport.seeking ? " | Finished" : ""); + if (local) { + const auto* replay = FindLocalReplay(file); + if (replay) { + DrawReplayResult(*replay); + DrawReplayPosting(*replay, ImGui::GetContentRegionAvail().x, true); + } + const bool posted = replay && !replay->posted_owner.empty() && replay->posted_owner == RankedRunsOwner(); + if (!posted && !g_time_trial_message.empty()) + OlParagraph(g_time_trial_message, 14.F, kOlSoft, ImGui::GetContentRegionAvail().x); + } + if (transport.seeking) { + ImGui::Text("Preparing frame %u | %s on arrival", transport.seek_to, + transport.paused ? "Pause" : "Play"); + ImGui::SameLine(); + if (OlButton("Cancel seek", OlTone::Plain, 0.F, nullptr, 28.F)) + trial::theatre_cancel_seek(); + } else if (transport.buffered < state.total_updates) { + ImGui::Text("Preparing replay %u / %u", transport.buffered, state.total_updates); + } else { + ImGui::TextUnformatted("Ready to seek"); + } + const unsigned first = 1, last = state.total_updates; + const unsigned destination = transport.seeking ? transport.seek_to : std::max(first, state.updates); + unsigned cursor = drag_target.value_or(destination); + ImGui::SetNextItemWidth(-1.F); + const bool changed = ImGui::SliderScalar("##replay-timeline", ImGuiDataType_U32, &cursor, &first, &last, "", + ImGuiSliderFlags_NoInput); + if (changed) { + drag_target = cursor; + trial::theatre_scrub(cursor); + } + if (!ImGui::IsItemActive() && drag_target) { + trial::theatre_seek(*drag_target); + drag_target.reset(); + } + const auto left = ImGui::GetItemRectMin(); + const auto right = ImGui::GetItemRectMax(); + if (transport.buffered > first && last > first) { + const auto x = left.x + (right.x - left.x) * float(transport.buffered - first) / float(last - first); + ImGui::GetWindowDrawList()->AddLine({left.x, right.y - 2.F}, {x, right.y - 2.F}, PaddockCol(kOlSoft), 2.F); + } + if (RunPreference(RunOption::LapMarkers) && last > 1) { + const auto marker = [&](unsigned frame) { + if (!frame || frame > last) + return; + const auto x = left.x + (right.x - left.x) * float(frame - 1) / float(last - 1); + ImGui::GetWindowDrawList()->AddLine({x, right.y - 3.F}, {x, right.y}, PaddockCol(kOlAmber), 2.F); + }; + if (state.adventure == trial::Adventure::None) { + for (const auto lap : std::span(state.lap_updates).first(state.lap_count)) + marker(lap); + } else { + for (const auto frame : trial::adventure_timeline_markers()) + marker(frame); + } + } + if (ImGui::IsItemActive() && drag_target) + ImGui::SetTooltip("Seek to frame %u", *drag_target); + { + if (OlButton("Start", OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_seek(1); + for (unsigned lap = 0; lap < state.lap_count && state.lap_updates[lap]; ++lap) { + ImGui::SameLine(); + const auto label = "Lap " + std::to_string(lap + 1); + if (OlButton(label.c_str(), OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_seek(state.lap_updates[lap]); + } + ImGui::SameLine(); + if (OlButton("Finish", OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_seek(state.finish_update); + const auto seconds = std::to_string(speed::seek_seconds[RunPreference(RunOption::SeekStep)]) + "s"; + ImGui::SameLine(); + if (OlButton(("-" + seconds).c_str(), OlTone::Plain, 0.F, nullptr, 32.F)) + SeekReplaySeconds(-1); + ImGui::SameLine(); + if (OlButton(("+" + seconds).c_str(), OlTone::Plain, 0.F, nullptr, 32.F)) + SeekReplaySeconds(1); + } + { + const char* action = transport.finished && !transport.seeking ? "Replay" + : transport.paused ? "Play" + : "Pause"; + if (OlButton(action, OlTone::Go, 0.F, nullptr, 32.F)) + trial::theatre_play_pause(); + const auto frame = transport.seeking ? transport.seek_to : state.updates; + ImGui::SameLine(); + { + const OlDisabled at_start(frame <= 1); + if (OlButton("-1 frame", OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_step(-1); + } + ImGui::SameLine(); + { + const OlDisabled at_end(!frame || frame == state.total_updates); + if (OlButton("+1 frame", OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_step(1); + } + } + if (width >= 630.F) + ImGui::SameLine(); + static const std::vector speeds{"0.5x", "1x", "1.5x", "2x"}; + const auto current = std::ranges::find(speed::playback_speeds, transport.speed); + int chosen = current == speed::playback_speeds.end() ? 1 : int(current - speed::playback_speeds.begin()); + if (SettingsDropdown("theatre-speed", {}, &chosen, speeds, 100.F, false, {}, 32.F)) + trial::theatre_speed(speed::playback_speeds[chosen]); + ImGui::SameLine(); + ImGui::Checkbox("Controller", &g_theatre_inputs); + ImGui::SameLine(); + if (OlButton("Exit", OlTone::Plain, 0.F, nullptr, 32.F)) + trial::theatre_exit(); + } + ImGui::End(); + ImGui::PopStyleVar(2); +} + +void DrawSpeedrunningRestartConfirmation() { + constexpr const char* title = "Restart this run?"; + if (!trial::restart_confirmation_pending() && !ImGui::IsPopupOpen(title)) + return; + if (trial::restart_confirmation_pending() && !ImGui::IsPopupOpen(title)) + ImGui::OpenPopup(title); + if (!BeginPaddedModal(title, ImGuiWindowFlags_AlwaysAutoResize)) + return; + if (!trial::restart_confirmation_pending()) { + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + return; + } + OlParagraph("The current attempt will be replaced.", 15.F, kOlInk, 330.F); + if (ImGui::IsWindowAppearing()) + ImGui::SetKeyboardFocusHere(); + if (OlButton("Keep racing")) { + trial::confirm_restart(false); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (OlButton("Restart Run", OlTone::Go)) { + trial::confirm_restart(true); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +enum class LeaderboardReplayAction { Watch, RaceGhost }; + +void WatchLeaderboardReplay(const std::string& id, bool own_run, + LeaderboardReplayAction action = LeaderboardReplayAction::Watch, std::string ghost_name = {}) { + RankedJob([id, own_run, action, ghost_name = std::move(ghost_name), config = g_config_directory, + signed_in = !RankedRunsOwner().empty()] { + const auto directory = config / "speedrun-playback"; + CheckManagedReplayDirectory(directory); + std::filesystem::create_directories(directory); + const auto stamp = std::chrono::system_clock::now().time_since_epoch().count(); + const auto file = directory / (std::to_string(stamp) + ".dkrreplay"); + try { + dkr::store::service().save_ranked_replay(id, file, own_run); + auto request = action == LeaderboardReplayAction::RaceGhost + ? PrepareGhostRun(file, config, std::nullopt, signed_in) + : TimeTrialRequest{trial::Mode::Watch, file}; + request.ghost_name = ghost_name; + return [file, request = std::move(request), signed_in]() mutable { + DeleteRankedPlayback(std::exchange(g_ranked_playback_file, file)); + QueueTimeTrialRequest(std::move(request), signed_in); + }; + } catch (...) { + DeleteRankedPlayback(file); + throw; + } + }); +} + +void DrawSubmissionLimit(float width, const dkr::store::Json* catalogue) { + if (!catalogue) + return; + const auto limit = catalogue->find("submissionLimit"); + if (limit == catalogue->end() || !limit->is_object()) + return; + const auto runs = LeaderboardNumber(*limit, "maxRuns"); + const auto hours = LeaderboardNumber(*limit, "windowHours"); + if (runs > 0 && hours > 0) + OlParagraph("You can post up to " + std::to_string(runs) + " runs. Each submission counts for " + + std::to_string(hours) + " hours, including after approval.", + 15.F, kOlSoft, width); +} + +void DrawLocalReplays(float width, const dkr::store::Json* catalogue) { + static char search[121]{}; + static char title[121]{}; + static int filter = 0; + static std::filesystem::path selected; + static std::string selected_title; + static bool purge_bests = false; + static bool purge_unsubmitted = false; + const bool can_watch = CanLaunchLeaderboardReplay(); + if (g_replay_library_profile != g_config_directory) + g_local_replays.clear(); + if (g_refresh_replay_library && !DialogJobRunning()) + RefreshReplayLibrary(); + + DrawOlFeature(width, "My Replays", nullptr, [&](float inner) { + DrawSubmissionLimit(inner, catalogue); + if (OlButton("Refresh replays")) { + g_refresh_replay_library = true; + g_published_replay_times = {}; + } + ImGui::SameLine(); + { + const OlDisabled busy(g_local_replays.empty() || DialogJobRunning()); + if (OlButton("Purge replays")) { + purge_bests = false; + purge_unsubmitted = false; + ImGui::OpenPopup("Purge stored replays?"); + } + } + if (ImGui::BeginPopupModal("Purge stored replays?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + OlParagraph("Permanently remove local copies from this device. Leaderboard submissions stay online.", 15.F, + kOlInk, 340.F); + ImGui::Checkbox("Include personal bests", &purge_bests); + ImGui::Checkbox("Include runs I haven't posted", &purge_unsubmitted); + const auto count = std::ranges::count_if(g_local_replays, [&](const auto& replay) { + return dkr::library_ui::can_purge_replay(replay.personal_best, !replay.posted_owner.empty(), purge_bests, + purge_unsubmitted); + }); + OlParagraph(count ? std::to_string(count) + (count == 1 ? " replay will be removed." : " replays will be removed.") + : "No replays match these choices.", 15.F, kOlSoft, 340.F); + if (OlButton("Cancel")) + ImGui::CloseCurrentPopup(); + ImGui::SetItemDefaultFocus(); + ImGui::SameLine(); + { + const OlDisabled unavailable(count == 0 || DialogJobRunning()); + if (OlButton("Purge selected replays", OlTone::Danger)) { + RankedJob([profile = g_config_directory, + chosen = SelectReplayPurge(g_local_replays, purge_bests, purge_unsubmitted), + bests = purge_bests, unsubmitted = purge_unsubmitted] { + const auto [removed, skipped] = PurgeLocalReplays(profile / "speedruns", chosen, bests, unsubmitted); + return [profile, removed, skipped] { + if (profile != g_config_directory) + return; + g_refresh_replay_library = true; + g_time_trial_message = "Removed " + std::to_string(removed) + + (removed == 1 ? " replay." : " replays."); + if (skipped) + g_time_trial_message += " Skipped " + std::to_string(skipped) + " changed or unavailable."; + }; + }); + ImGui::CloseCurrentPopup(); + } + } + ImGui::EndPopup(); + } + PaddockGap(8.F); + ImGui::BeginGroup(); + const float search_width = std::min(300.F, inner); + SettingsLabel("Search replays", search_width); + OlInputOptions options; + options.hint = "Track, racer or title"; + options.height = kSettingsDropdownHeight; + if (OlInput("##find-replay", nullptr, search, sizeof(search), search_width, options) == OlInputResult::Gamepad) { + RequestCustomTextKeyboard("Search replays", search, sizeof(search), + [](const std::string& text) { + std::snprintf(search, sizeof(search), "%s", text.c_str()); + }, true); + } + ImGui::EndGroup(); + if (inner >= 540.F) + ImGui::SameLine(); + ImGui::BeginGroup(); + SettingsDropdown("replay-type", "Replay type", &filter, {"All replays", "Local runs", "Leaderboard runs"}, + std::min(226.F, inner)); + ImGui::EndGroup(); + + const auto needle = dkr::runtime::texture_browser::lower_ascii(search); + bool rename = false, remove = false; + unsigned matches = 0; + std::vector ordered; + ordered.reserve(g_local_replays.size()); + for (const auto& replay : g_local_replays) + ordered.push_back(&replay); + switch (RunPreference(RunOption::ReplaySort)) { + case 1: + std::ranges::stable_sort(ordered, std::greater{}, &LocalReplay::personal_best); + break; + case 2: + std::ranges::stable_sort(ordered, {}, &LocalReplay::course); + break; + } + for (const auto* record : ordered) { + const auto& replay = *record; + const std::string kind = replay.has_attempt ? "Leaderboard run" : "Local run"; + if ((filter == 1 && replay.has_attempt) || (filter == 2 && !replay.has_attempt)) + continue; + const auto haystack = replay.title + " " + replay.course + " " + replay.racer + " " + replay.vehicle + + " " + PathUtf8(replay.file.filename()); + if (dkr::runtime::texture_browser::lower_ascii(haystack).find(needle) == std::string::npos) + continue; + ++matches; + const auto id = PathUtf8(replay.file.filename()); + ImGui::PushID(id.c_str()); + const ImVec2 divider = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled( + divider, {divider.x + inner, divider.y + 1.F}, ImGui::GetColorU32(ImGuiCol_Separator)); + ImGui::Dummy({inner, 1.F}); + const bool side_by_side = inner >= 755.F; + ImGui::BeginGroup(); + const float details_width = side_by_side ? inner - 415.F : inner; + OlParagraph(replay.title, 19.F, kOlInk, details_width); + if (replay.valid) { + std::string details; + const auto append = [&](const std::string& part) { + if (!part.empty()) { + if (!details.empty()) + details += " | "; + details += part; + } + }; + if (replay.title != replay.course) + append(replay.course); + append(replay.vehicle); + append(replay.racer); + append(kind); + const auto saved = ReplayDate(replay.saved); + if (!saved.empty()) + append("Saved " + saved); + OlParagraph(details, 15.F, kOlSoft, details_width); + OlParagraph("Finish " + LeaderboardTime(replay.time) + + (replay.best_lap ? " | Best lap " + LeaderboardTime(replay.best_lap) : ""), + 15.F, kOlInk, details_width); + DrawReplayResult(replay); + DrawReplayPosting(replay, details_width); + } else { + OlParagraph("Unsupported or incomplete replay", 15.F, kOlSoft, details_width); + } + ImGui::EndGroup(); + if (side_by_side) + ImGui::SameLine(inner - 392.F); + { + const OlDisabled busy(!replay.valid || !can_watch || DialogJobRunning()); + if (OlButton("Watch")) + g_time_trial_request = TimeTrialRequest{trial::Mode::Watch, replay.file}; + } + if (replay.can_ghost) { + ImGui::SameLine(); + const OlDisabled busy(!can_watch || DialogJobRunning()); + if (OlButton("Race Ghost")) + RaceReplayGhost(replay.file); + } + ImGui::SameLine(); + const OlDisabled busy(DialogJobRunning()); + if (OlButton("Rename")) { + selected = replay.file; + selected_title = replay.title; + std::snprintf(title, sizeof(title), "%s", replay.title.c_str()); + rename = true; + } + ImGui::SameLine(); + if (OlButton("Remove")) { + selected = replay.file; + selected_title = replay.title; + remove = true; + } + ImGui::PopID(); + } + if (!matches) + OlParagraph(g_local_replays.empty() ? "Recorded runs and downloaded replays will appear here." + : "No replays match your filters.", + 15.F, kOlSoft, inner); + if (rename) + ImGui::OpenPopup("Rename replay"); + if (remove) + ImGui::OpenPopup("Remove local copy?"); + if (ImGui::BeginPopupModal("Rename replay", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + if (OlInput("##replay-name", "Display title", title, sizeof(title), 310.F, {}) == + OlInputResult::Gamepad) + RequestCustomTextKeyboard("Display title", title, sizeof(title), + [](const std::string& text) { + std::snprintf(title, sizeof(title), "%s", text.c_str()); + }, true); + const std::string name = title; + { + const OlDisabled disabled(name.find_first_not_of(" \t\r\n") == std::string::npos); + if (OlButton("Save name", OlTone::Go)) { + RankedJob([file = selected, name] { + RenameLocalReplay(file, name); + return [] { g_refresh_replay_library = true; }; + }); + ImGui::CloseCurrentPopup(); + } + } + ImGui::SameLine(); + if (OlButton("Cancel")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + if (ImGui::BeginPopupModal("Remove local copy?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + OlParagraph(selected_title, 17.F, kOlInk, 320.F); + if (OlButton("Cancel")) + ImGui::CloseCurrentPopup(); + ImGui::SetItemDefaultFocus(); + ImGui::SameLine(); + if (OlButton("Remove local copy")) { + RankedJob([file = selected] { + RemoveLocalReplay(file); + return [] { g_refresh_replay_library = true; }; + }); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + } + }); +} + +using TrackQuery = dkr::store::LeaderboardTrackQuery; +std::string g_track_return_focus; + +void DrawAdventureBoards(float width, const dkr::store::Json* catalogue, TrackQuery& query); +std::function DrawPracticeAdventure(float width, const dkr::store::Json* catalogue, bool signed_in); + +void DrawLatestRecording(float width) { + const auto result = trial::last_result(); + if (result.replay || result.message.empty()) + return; + DrawOlFeature(width, "Last run", nullptr, [&](float inner) { + OlParagraph(result.message, 15.F, kOlSoft, inner); + if (!result.complete) + return; + if (RunPreference(RunOption::FinishSummary)) + OlParagraph("Finish " + LeaderboardTime(result.clock) + + (result.best_lap ? " | Best lap " + LeaderboardTime(result.best_lap) : ""), + 16.F, kOlInk, inner); + if (const auto* replay = FindLocalReplay(result.file)) { + DrawReplayResult(*replay); + if (RunPreference(RunOption::PostPrompt)) + DrawReplayPosting(*replay, inner, true); + const OlDisabled busy(!CanLaunchLeaderboardReplay() || DialogJobRunning()); + if (OlButton("Watch Replay")) + g_time_trial_request = TimeTrialRequest{trial::Mode::Watch, result.file}; + } + }); + PaddockGap(8.F); +} + +void StartTrackRun(std::string id, const trial::Course* course, trial::Vehicle vehicle, unsigned racer, + std::string board, bool signed_in) { + RankedJob([id = std::move(id), course, vehicle, racer, board = std::move(board), signed_in, + config = g_config_directory] { + auto request = TimeTrialRequest{trial::Mode::Record, NewTimeTrialFile(config, id + "-Practice")}; + request.attempt = RequestTrackAttempt(board, id, course, vehicle, racer); + request.racer = racer; + request.vehicle = vehicle; + if (course) + request.course = course; + else + request.track = id; + std::tie(request.lap_reference, request.prior_best) = + ReadRunReference(config / "speedruns", id, course, vehicle, racer, + request.attempt ? std::string_view(request.attempt->track_hash) : std::string_view{}); + return [request = std::move(request), signed_in]() mutable { + QueueTimeTrialRequest(std::move(request), signed_in); + }; + }); +} + +struct SpeedrunningSetup { + std::array courses; + std::array vehicles{}; + unsigned racer = trial::kDiddy; + int challenge = 0; +}; +SpeedrunningSetup g_run_setup; +std::filesystem::path g_run_setup_profile; + +void LoadSpeedrunningSetup() { + if (g_run_setup_profile == g_config_directory) + return; + g_run_setup_profile = g_config_directory; + g_run_setup = {}; + if (!RunPreference(RunOption::RememberSetup)) + return; + try { + const auto file = g_config_directory / "speedrunning-setup.json"; + const auto saved = dkr::store::Json::parse(dkr::updates::read_text(file, 4096)); + for (unsigned i = 0; i < 2; ++i) { + g_run_setup.courses[i] = StoreText(saved, i ? "custom" : "vanilla", 128); + g_run_setup.vehicles[i] = std::min(2U, unsigned(LeaderboardNumber(saved, i ? "customVehicle" : "vanillaVehicle"))); + } + if (saved.contains("racer")) + g_run_setup.racer = std::min(unsigned(trial::kRacers.size() - 1), unsigned(LeaderboardNumber(saved, "racer"))); + g_run_setup.challenge = int(LeaderboardNumber(saved, "challenge")); + } catch (const std::exception&) { + // Older profiles start with the existing default selections. + } +} + +void SaveSpeedrunningSetup() { + if (!RunPreference(RunOption::RememberSetup)) + return; + const dkr::store::Json setup{ + {"vanilla", g_run_setup.courses[0]}, {"custom", g_run_setup.courses[1]}, + {"vanillaVehicle", g_run_setup.vehicles[0]}, {"customVehicle", g_run_setup.vehicles[1]}, + {"racer", g_run_setup.racer}, {"challenge", g_run_setup.challenge}}; + try { + dkr::updates::durable_write(g_config_directory / "speedrunning-setup.json", setup.dump()); + } catch (const std::exception&) { + std::fprintf(stderr, "[speedrunning] Could not save run setup.\n"); + } +} + +std::function DrawPracticeTracks(float width, const dkr::store::Json* catalogue, bool custom, bool signed_in) { + using dkr::runtime::custom_tracks::ReplayTrack; + static const auto vanilla = [] { + std::vector choices; + for (const auto& course : trial::kCourses) + choices.push_back({std::string(course.id), std::string(course.name), course.vehicles}); + return choices; + }(); + OlHeading(custom ? "Custom Tracks" : "Vanilla Tracks", width < 275.F ? 19.F : 24.F, kOlCream, width); + const auto installed = custom ? dkr::runtime::custom_tracks::installed_replay_tracks() : std::vector{}; + const auto& tracks = custom ? installed : vanilla; + if (tracks.empty()) { + OlParagraph("Install a compatible .dkrmap track to practise here.", 15.F, kOlSoft, width); + return {}; + } + auto& selected = g_run_setup.courses; + auto& vehicle = g_run_setup.vehicles[custom]; + auto& racer = g_run_setup.racer; + const auto current = std::ranges::find(tracks, selected[custom], &ReplayTrack::id); + int course_index = current == tracks.end() ? 0 : static_cast(current - tracks.begin()); + std::vector courses; + courses.reserve(tracks.size()); + for (const auto& track : tracks) + courses.emplace_back(track.name); + SettingsDropdown("run-course", "Course", &course_index, courses, std::min(360.F, width)); + const auto* track = &tracks[static_cast(course_index)]; + selected[custom] = track->id; + + std::vector vehicle_names; + std::vector available_vehicles; + int vehicle_index = 0; + for (unsigned i = 0; i < trial::kVehicleNames.size(); ++i) { + if (!(track->vehicles & (1U << i))) + continue; + if (i == vehicle) + vehicle_index = static_cast(available_vehicles.size()); + available_vehicles.push_back(i); + vehicle_names.emplace_back(std::string(dkr::localisation::source(trial::kVehicleNames[i]))); + } + SettingsDropdown("run-vehicle", "Vehicle", &vehicle_index, vehicle_names, std::min(360.F, width)); + vehicle = available_vehicles[static_cast(vehicle_index)]; + + static const auto racers = [] { + std::vector choices; + choices.reserve(trial::kRacers.size()); + for (const auto& entry : trial::kRacers) + choices.emplace_back(std::string(entry.name)); + return choices; + }(); + int racer_index = static_cast(racer); + SettingsDropdown("run-racer", "Racer", &racer_index, racers, std::min(360.F, width)); + racer = static_cast(racer_index); + const auto choice = static_cast(vehicle); + const auto* course = custom ? nullptr : trial::course_for(track->id); + auto board = signed_in ? TrackAttemptBoard(catalogue, track->id, course, choice, racer) : std::string{}; + return [id = track->id, course, choice, racer, board = std::move(board), signed_in] { + StartTrackRun(id, course, choice, racer, board, signed_in); + }; +} + +void DrawLeaderboardPractice(float width, const dkr::store::Json* catalogue) { + LoadSpeedrunningSetup(); + if (g_refresh_replay_library && !DialogJobRunning()) + RefreshReplayLibrary(); + DrawLatestRecording(width); + const bool ready = CanLaunchLeaderboardReplay(); + const bool can_launch = ready && !g_leaderboard_layout_check; + const bool signed_in = !RankedRunsOwner().empty(); + if (!ready) + OlParagraph("Select a US v1.0 or US v1.1 ROM in Play and leave any active lobby.", 15.F, kOlSoft, width); + constexpr float gap = 12.F; + constexpr float minimum_card = 242.F; + const bool row = width >= 3.F * minimum_card + 2.F * gap; + const float card = row ? std::floor((width - 2.F * gap) / 3.F) : width; + const auto draw_card = [&](int section) { + ImGui::PushID(section); + DrawOlCard(card, OlPanelLook{}, [&](float inner) { + const auto start = section == 2 ? DrawPracticeAdventure(inner, catalogue, signed_in) + : DrawPracticeTracks(inner, catalogue, section == 1, signed_in); + if (start) { + PaddockGap(6.F); + const OlDisabled busy(!can_launch || DialogJobRunning()); + if (OlButton("Start Run", OlTone::Go)) { + SaveSpeedrunningSetup(); + start(); + } + } + }, 14.F); + ImGui::PopID(); + }; + if (row) { + const auto origin = ImGui::GetCursorScreenPos(); + float bottom = origin.y; + { + OlEqualProfileRow equal; + for (int section = 0; section < 3; ++section) { + ImGui::SetCursorScreenPos({origin.x + section * (card + gap), origin.y}); + equal.capture_next = true; + draw_card(section); + bottom = std::max(bottom, ImGui::GetItemRectMax().y); + } + } + ImGui::SetCursorScreenPos(origin); + ImGui::Dummy({width, bottom - origin.y}); + } else { + for (int section = 0; section < 3; ++section) { + if (section) + PaddockGap(gap); + draw_card(section); + } + } +} + +using LeaderboardChoices = std::vector>; + +std::string LeaderboardVehicle(std::string_view id) { + const auto vehicle = std::find(trial::kVehicleIds.begin(), trial::kVehicleIds.end(), id); + return vehicle == trial::kVehicleIds.end() + ? std::string(id) + : std::string(trial::kVehicleNames[vehicle - trial::kVehicleIds.begin()]); +} + +bool LeaderboardFilter(const char* label, const LeaderboardChoices& choices, std::string& value, float width) { + const auto selected = + std::find_if(choices.begin(), choices.end(), [&](const auto& entry) { return entry.first == value; }); + if (choices.empty()) + return false; + std::vector names; + names.reserve(choices.size()); + for (const auto& entry : choices) + names.emplace_back(std::string(dkr::localisation::source(entry.second))); + int index = selected == choices.end() ? 0 : static_cast(selected - choices.begin()); + ImGui::BeginGroup(); + const bool changed = SettingsDropdown(label, label, &index, names, width); + ImGui::EndGroup(); + if (changed) + value = choices[static_cast(index)].first; + return changed; +} + +bool CanLaunchLeaderboardReplay() { + return g_launcher_rom && !dkr::runtime::netplay::session().active() && !g_time_trial_request; +} + +void DrawLeaderboardRankRow(float width, const dkr::store::Json& entry, bool full_game) { + const auto place = LeaderboardNumber(entry, "place"); + const auto id = StoreText(entry, "id", 96); + const auto time = LeaderboardTime(LeaderboardNumber(entry, "ticks")); + const auto name = StoreText(entry, "name", 60); + const auto racer = StoreText(entry, "racer", 50); + constexpr float gap = 8.F; + constexpr float rank_width = 56.F; + constexpr float time_width = 97.F; + const float watch_width = OlButtonWidth("Watch"); + const float ghost_width = full_game ? 0.F : OlButtonWidth("Race Ghost", OlTone::Go); + const float actions_width = watch_width + (full_game ? 0.F : ghost_width + gap); + OlPanelLook look; + look.fill = place == 1 ? 0x143446 : 0x102D3E; + look.ring = place == 1 ? 0x947445 : kOlRing; + look.ring_width = 1.F; + look.radii = PaddockRound(9.F); + + ImGui::PushID(id.c_str()); + DrawOlCard(width, look, [&](float inner) { + const bool inline_actions = !id.empty() && inner >= rank_width + time_width + actions_width + 168.F; + const float time_right = inline_actions ? inner - actions_width - 20.F : inner; + const float time_left = time_right - time_width; + const ImVec2 start = ImGui::GetCursorScreenPos(); + const float badge_width = rank_width - gap; + PaddockFill(ImGui::GetWindowDrawList(), {start.x, start.y + 5.F}, + {start.x + badge_width, start.y + 33.F}, PaddockRound(6.F), + PaddockCol(place == 1 ? 0x45371D : 0x1A4054)); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 7.F); + OlParagraph("#" + std::to_string(place), 15.F, place == 1 ? kOlAmber : kOlInk, badge_width, true, 1.4F, + true); + + ImGui::SameLine(0.F, gap); + ImGui::SetCursorScreenPos({start.x + rank_width, start.y}); + ImGui::BeginGroup(); + const float name_width = std::max(1.F, time_left - rank_width - gap); + OlParagraph(name, 16.F, kOlInk, name_width, true, 1.3F); + if (!racer.empty()) + OlParagraph(racer, 14.F, kOlSoft, name_width, false, 1.25F); + ImGui::EndGroup(); + + ImGui::SameLine(); + ImGui::SetCursorScreenPos({start.x + time_left, start.y + 7.F}); + OlParagraph(time, 18.F, kOlCream, time_width, true, 1.3F); + if (id.empty()) + return; + + if (inline_actions) { + ImGui::SameLine(); + ImGui::SetCursorScreenPos({start.x + inner - actions_width, start.y + 7.F}); + } else { + PaddockGap(3.F); + } + const OlDisabled launch(DialogJobRunning() || !CanLaunchLeaderboardReplay()); + if (!full_game) { + if (OlButton("Race Ghost", OlTone::Go)) + WatchLeaderboardReplay(id, false, LeaderboardReplayAction::RaceGhost, name); + if (inner >= actions_width) + ImGui::SameLine(0.F, gap); + } + if (OlButton("Watch")) + WatchLeaderboardReplay(id, false); + }, 11.F); + ImGui::PopID(); +} + +#include "leaderboard_rankings.inl" + +void DrawLeaderboardRanking(float width, const dkr::store::Json& ranking, TrackQuery& query) { + const auto& event = ranking["track"]; DrawOlFeature(width, StoreText(event, "title", 120).c_str(), nullptr, [&](float inner) { - PaddockGap(6.F); - OlParagraph(StoreText(event, "category", 80) + " · " + StoreText(event, "vehicle", 24), 15.F, kOlSoft, inner); - PaddockGap(12.F); - const auto& entries = board["entries"]; + const auto detail = StoreText(event, query.custom ? "version" : "world", 80); + if (!detail.empty()) + OlParagraph(detail, 15.F, kOlSoft, inner); + PaddockGap(8.F); + auto& service = dkr::store::service(); + const OlDisabled loading(service.view()->speedrun_loading); + auto next = query; + next.offset = 0; + next.vehicle = StoreText(ranking, "vehicle", 24); + next.racer = StoreText(ranking, "racer", 96); + next.best_lap = StoreText(ranking, "score", 6) == "lap"; + LeaderboardChoices vehicles, racers{{"", "All racers"}}; + for (const auto& vehicle : ranking["vehicles"]) { + const auto id = vehicle.get(); + vehicles.emplace_back(id, LeaderboardVehicle(id)); + } + for (const auto& racer : ranking["racers"]) + racers.emplace_back(StoreText(racer, "id", 96), StoreText(racer, "name", 40)); + bool filters_changed = false; + if (!query.full_game) { + const float filter_width = std::min(220.F, inner); + filters_changed = LeaderboardFilter("Racer", racers, next.racer, filter_width); + if (!vehicles.empty()) { + if (2 * filter_width + ImGui::GetStyle().ItemSpacing.x <= inner) + ImGui::SameLine(); + if (LeaderboardFilter("Vehicle", vehicles, next.vehicle, filter_width)) { + next.racer.clear(); + filters_changed = true; + } + } + PaddockGap(8.F); + for (const bool lap : {false, true}) { + if (lap) + ImGui::SameLine(); + if (OlButton(lap ? "Best lap" : "Full race", next.best_lap == lap ? OlTone::Go : OlTone::Plain) && + next.best_lap != lap) { + next.best_lap = lap; + filters_changed = true; + } + } + } + if (filters_changed) { + query = next; + service.load_leaderboards({}, query); + return; + } + PaddockGap(8.F); + const auto& entries = ranking["entries"]; if (entries.empty()) { - OlParagraph("No verified runs have been published yet.", 15.F, kOlSoft, inner); + OlParagraph(ranking.value("ranked", false) ? "No verified runs have been published for this selection." + : "This track and vehicle are awaiting replay qualification.", + 15.F, kOlSoft, inner); + } else { + for (const auto& entry : entries) { + DrawLeaderboardRankRow(inner, entry, query.full_game); + PaddockGap(6.F); + } + } + if (const auto offset = LeaderboardNumber(ranking, "nextOffset"); offset && OlButton("More times")) { + next.offset = static_cast(offset); + service.load_leaderboards({}, next); + } + if (const auto history = ranking.find("history"); history != ranking.end() && history->is_object()) { + PaddockGap(10.F); + DrawTrackRecordHistory(inner, *history, query.id + "/" + next.vehicle + "/" + next.racer + + (next.best_lap ? "/lap" : "/race")); + } + }); + PaddockGap(12.F); +} + +void RefreshLeaderboardRuns(bool review) { + RankedJob([review, owner = RankedRunsOwner()] { + auto reply = dkr::store::service().ranked_runs(review); + const auto received = std::chrono::steady_clock::now(); + return [reply = std::move(reply), owner, received, review] { + if (owner == RankedRunsOwner()) { + g_ranked_runs_owner = owner; + g_ranked_runs_review = review; + g_ranked_runs = std::move(reply); + g_ranked_runs_received = received; + } + }; + }); +} + +#include "submitted_runs.inl" + +void DrawLeaderboardRuns(float width, bool review) { + if (!review) { + DrawSubmittedRuns(width); + return; + } + static std::string selected; + static char reason[601]{}; + DrawOlFeature(width, "Review Runs", nullptr, [&](float inner) { + const auto owner = RankedRunsOwner(); + const OlDisabled busy(DialogJobRunning()); + if (owner.empty()) { + OlParagraph("Sign in with Discord to see your submitted runs.", 15.F, kOlSoft, inner); + if (OlButton("Sign in with Discord", OlTone::Go)) + dkr::store::service().login(); return; } - if (!ImGui::BeginTable("ranked-runs", 4, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH, {inner, 0.F})) + const bool loaded = g_ranked_runs_owner == owner && g_ranked_runs_review && + g_ranked_runs.contains("runs"); + if (!loaded) { + OlParagraph("Use Refresh to check for runs.", 15.F, kOlSoft, inner); return; - ImGui::TableSetupColumn("Rank", ImGuiTableColumnFlags_WidthFixed, 70.F); - ImGui::TableSetupColumn("Racer", ImGuiTableColumnFlags_WidthStretch); - ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_WidthFixed, 82.F); - ImGui::TableSetupColumn("Replay", ImGuiTableColumnFlags_WidthFixed, 86.F); - ImGui::TableHeadersRow(); - for (const auto& entry : entries) { - ImGui::TableNextRow(); - ImGui::TableNextColumn(); - ImGui::TextUnformatted(std::to_string(LeaderboardNumber(entry, "place")).c_str()); - ImGui::TableNextColumn(); - OlParagraph(StoreText(entry, "name", 60), 15.F, kOlInk, ImGui::GetContentRegionAvail().x); - ImGui::TableNextColumn(); - ImGui::TextUnformatted(LeaderboardTime(LeaderboardNumber(entry, "ticks")).c_str()); - ImGui::TableNextColumn(); - const auto id = StoreText(entry, "id", 96); - if (!id.empty() && - id.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == - std::string::npos) { - ImGui::PushID(id.c_str()); - if (OlButton("Download", OlTone::Plain, ImGui::GetContentRegionAvail().x, nullptr, 32.F)) - SDL_OpenURL((std::string(dkr::online::Api) + "/v1/speedruns/runs/" + id + "/replay").c_str()); - ImGui::PopID(); + } + if (g_ranked_runs["runs"].empty()) + OlParagraph("No verified runs are awaiting review.", 15.F, kOlSoft, inner); + for (const auto& run : g_ranked_runs["runs"]) { + const auto id = StoreText(run, "id", 96); + const auto state = StoreText(run, "state", 24); + const auto ticks = LeaderboardNumber(run, "ticks"); + if (id.empty()) + continue; + ImGui::PushID(id.c_str()); + PaddockGap(8.F); + OlParagraph(StoreText(run, "title", 100) + " | " + StoreText(run, "name", 60) + " | " + state + + (ticks ? " | " + LeaderboardTime(ticks) : ""), + 16.F, kOlInk, inner); + if (run.value("linkedLocal", false)) + OlParagraph("Linked local run", 14.F, kOlSoft, inner); + for (const char* field : {"notes", "reason"}) + if (const auto value = StoreText(run, field, 600); !value.empty()) + OlParagraph(value, 14.F, kOlSoft, inner); + if (state != "uploading") { + { + const OlDisabled launch(!CanLaunchLeaderboardReplay()); + if (OlButton("Watch replay")) + WatchLeaderboardReplay(id, true); + } + } + if (state == "verified") { + ImGui::SameLine(); + if (OlButton("Review") && selected != id) { + selected = id; + reason[0] = '\0'; + } + if (selected == id) { + if (run.value("videoRequired", false) && StoreText(run, "videoState", 24) != "ready") + OlParagraph("You can review the replay here while the website video is being prepared.", 14.F, + kOlSoft, inner); + OlInputOptions options; + options.hint = "Review note"; + if (OlInput("##review-note", nullptr, reason, sizeof(reason), std::min(430.F, inner), options) == + OlInputResult::Gamepad) { + RequestCustomTextKeyboard( + "Review note", reason, sizeof(reason), + [id](const std::string& text) { + if (selected == id) + std::snprintf(reason, sizeof(reason), "%s", text.c_str()); + }, + true); + } + const auto submit = [&](bool publish) { + RankedJob([id, publish, note = std::string(reason), owner = RankedRunsOwner()] { + dkr::store::service().review_ranked_run(id, publish, note); + auto rows = dkr::store::service().ranked_runs(true); + return [owner, rows = std::move(rows)] { + if (owner == RankedRunsOwner()) { + g_ranked_runs_review = true; + g_ranked_runs = std::move(rows); + g_time_trial_message = "Review saved."; + } + }; + }); + selected.clear(); + }; + if (OlButton("Publish", OlTone::Go)) + submit(true); + ImGui::SameLine(); + const OlDisabled no_note(reason[0] == '\0'); + if (OlButton("Reject")) + submit(false); + } } + ImGui::PopID(); } - ImGui::EndTable(); }); } @@ -62,145 +1978,545 @@ const dkr::store::Snapshot& LeaderboardLayoutFixture() { static const auto fixture = [] { dkr::store::Snapshot value; value.speedrun_catalogue = std::make_shared(Json::parse(R"json({ - "boards": [ - {"id":"ancient-lake-car","kind":"vanilla","title":"Ancient Lake","category":"Time Trial","vehicle":"car"}, - {"id":"crescent-island-car","kind":"vanilla","title":"Crescent Island","category":"Time Trial","vehicle":"car"}, - {"id":"frosty-village-car","kind":"vanilla","title":"Frosty Village","category":"Time Trial","vehicle":"car"} + "vanillaTracks":[ + {"id":"ancient-lake","title":"Ancient Lake","world":"Dino Domain","vehicles":["car","hovercraft","plane"]}, + {"id":"crescent-island","title":"Crescent Island","world":"Sherbet Island","vehicles":["car","hovercraft"]}, + {"id":"frosty-village","title":"Frosty Village","world":"Snowflake Mountain","vehicles":["car","plane"]} ], - "customTracks": [ + "boards":[{"id":"ancient-lake-car","kind":"vanilla","title":"Ancient Lake","vehicle":"car","ranked":true}], + "customTracks":[ {"id":"splashdown","title":"Splashdown Pass","version":"1.0","qualified":false}, {"id":"sherbet-land","title":"Sherbet Land","version":"1.0","qualified":false} ], "nextCursor":"" })json")); value.speedrun_board = std::make_shared(Json::parse(R"json({ - "board":{"id":"ancient-lake-car","title":"Ancient Lake","category":"Time Trial","vehicle":"car"}, - "entries":[{"place":1,"name":"Example Racer","ticks":5300,"id":"fixture-one"}, - {"place":2,"name":"Deck Racer","ticks":5350,"id":"fixture-two"}] + "track":{"id":"ancient-lake","title":"Ancient Lake","world":"Dino Domain"}, + "vehicle":"car", "vehicles":["car","hovercraft","plane"], "racers":[{"id":"ancient-lake-car","name":"Diddy"}], + "score":"race", "ranked":true, + "entries":[{"place":1,"name":"Example Racer","racer":"Diddy","ticks":5300,"id":"fixture-one"}, + {"place":2,"name":"Deck Racer","racer":"Diddy","ticks":5350,"id":"fixture-two"}] })json")); return value; }(); return fixture; } -void DrawLeaderboardsPage(float width, bool entered) { - static const std::vector labels{"Vanilla Tracks", "Custom Tracks", "Full Game"}; - constexpr std::array kinds{"vanilla", "custom", "full-game"}; - static int category = 0; - static std::string selected_board; +void DrawCatalogueLeaders(const dkr::store::Json& track, float width, bool full_game) { + const auto data = track.find("leaders"); + if (data == track.end() || !data->is_object()) + return; + const auto draw_score = [&](const char* label, const dkr::store::Json& vehicle, const char* kind, float available) { + const auto score = vehicle.find(kind); + if (score == vehicle.end() || !score->is_object() || LeaderboardNumber(*score, "ticks") <= 0) { + OlParagraph(std::string(label) + " —", 14.F, kOlSoft, available); + return; + } + const auto line = std::string(label) + " " + StoreText(*score, "name", 80) + " · " + + LeaderboardTime(LeaderboardNumber(*score, "ticks")); + const auto type = OlRead(14.F); + const auto badge_type = OlRead(12.F, true); + const auto place = LocalisedUi::copy("1st"); + const float spacing = 7.F; + const float icon_width = 14.F; + const float badge_width = spacing + icon_width + 4.F + PaddockMeasure(badge_type, place); + const auto lines = OlWrap(type, line, std::max(1.F, available - badge_width)); + const ImVec2 start = ImGui::GetCursorScreenPos(); + auto* draw = ImGui::GetWindowDrawList(); + PaddockTextStyle style; + style.colour = PaddockCol(kOlSoft); + PaddockDrawLines(draw, type, start, available, lines, style); + const float x = start.x + lines.back().width + spacing; + const float y = start.y + type.line * static_cast(lines.size() - 1); + const float top = y + (type.line - 11.F) * .5F; + const std::array crown{{ + {x, top + 2.F}, {x + 4.F, top + 5.F}, {x + 7.F, top}, {x + 10.F, top + 5.F}, + {x + icon_width, top + 2.F}, {x + 12.F, top + 10.F}, {x + 2.F, top + 10.F}, + }}; + const auto gold = PaddockCol(kOlAmber); + draw->AddPolyline(crown.data(), static_cast(crown.size()), gold, ImDrawFlags_Closed, 1.4F); + PaddockDrawRun(draw, badge_type, {x + icon_width + 4.F, y + (type.line - badge_type.line) * .5F}, gold, + place.data(), place.data() + place.size()); + ImGui::Dummy({available, type.line * static_cast(lines.size())}); + }; + if (full_game) { + draw_score("Finish time", data->value("mixed", dkr::store::Json::object()), "race", width); + return; + } + const auto vehicles = track.value("vehicles", dkr::store::Json::array()); + if (vehicles.empty()) + return; + const auto columns = std::min(static_cast(vehicles.size()), + std::max(1U, static_cast(width / 185.F))); + if (!ImGui::BeginTable("TrackRecords", columns, ImGuiTableFlags_SizingStretchSame, {width, 0.F})) + return; + for (const auto& vehicle : vehicles) { + const auto& id = vehicle.get_ref(); + ImGui::TableNextColumn(); + const float available = ImGui::GetContentRegionAvail().x; + OlParagraph(LeaderboardVehicle(id), 14.F, kOlAmber, available, true); + const auto scores = data->value(id, dkr::store::Json::object()); + draw_score("Full race", scores, "race", available); + draw_score("Best lap", scores, "lap", available); + } + ImGui::EndTable(); +} + +template +void DrawLeaderboardTrackRow(float width, const std::string& title, const std::string& detail, + DrawActions draw_actions, const dkr::store::Json* records = nullptr, + bool full_game = false) { + DrawOlCard(width, OlPanelLook{}, [&](float inner) { + const auto draw_details = [&](float available) { + OlParagraph(title, 18.F, kOlInk, available, true); + if (!detail.empty()) + OlParagraph(detail, 14.F, kOlSoft, available); + PaddockGap(4.F); + draw_actions(available); + }; + if (!records || inner < 440.F) { + draw_details(inner); + if (records) { + PaddockGap(8.F); + DrawCatalogueLeaders(*records, inner, full_game); + } + return; + } + if (!ImGui::BeginTable("TrackRow", 2, ImGuiTableFlags_SizingStretchProp, {inner, 0.F})) + return; + ImGui::TableSetupColumn("Track", ImGuiTableColumnFlags_WidthFixed, std::clamp(inner * .22F, 160.F, 300.F)); + ImGui::TableSetupColumn("Leaders", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableNextColumn(); + draw_details(ImGui::GetContentRegionAvail().x); + ImGui::TableNextColumn(); + DrawCatalogueLeaders(*records, ImGui::GetContentRegionAvail().x, full_game); + ImGui::EndTable(); + }); + PaddockGap(6.F); +} + +void StartAdventureRun(trial::Adventure goal, std::string board, bool signed_in, bool qualified) { + RankedJob([goal, board = std::move(board), signed_in, qualified, config = g_config_directory] { + std::optional attempt; + if (signed_in) { + try { + const auto reply = dkr::store::service().ranked_attempt(board); + attempt = trial::parse_adventure_attempt(StoreText(reply, "board", 96), StoreText(reply, "engine", 64), + StoreText(reply, "ticket", 160), goal); + if (attempt) + attempt->finish_targets = ReadFinishTargets(reply); + } catch (const std::exception&) { + attempt.reset(); + } + } + auto request = TimeTrialRequest{trial::Mode::Record, NewTimeTrialFile(config, board + "-Practice")}; + request.adventure = goal; + const bool load_record = attempt.has_value() || (qualified && !signed_in); + request.attempt = std::move(attempt); + try { + for (const auto& replay : ReadLocalReplayLibrary(request.replay.parent_path())) { + if (!replay.valid || replay.time <= 0 || replay.adventure_category != trial::adventure_id(goal) || + replay.ruleset != trial::kAdventureRules) + continue; + const auto manifest = ReadReplaySummary(replay.file); + const auto reference = ReadAdventureReference(manifest); + if (!request.prior_best || replay.time < request.prior_best) { + request.prior_best = unsigned(replay.time); + request.adventure_pb = reference; + } + const auto splits = manifest.find("splits"); + if (splits == manifest.end() || !splits->is_array() || reference.size() != splits->size()) + continue; + std::string previous; + std::int64_t previous_ticks = 0; + for (const auto& entry : *splits) { + const auto label = entry[0].get(); + const auto ticks = reference.at(label); + if (ticks <= previous_ticks) + break; + const auto segment = ticks - previous_ticks; + auto [slot, inserted] = request.adventure_segments.try_emplace({previous, label}, segment); + if (!inserted) + slot->second = std::min(slot->second, segment); + previous = label; + previous_ticks = ticks; + } + } + } catch (const std::exception&) { + // The comparison is optional when the local replay folder is unavailable. + } + if (load_record) { + try { + const auto standings = dkr::store::service().adventure_record(std::string(trial::adventure_id(goal))); + const auto& entries = standings.at("entries"); + if (entries.is_array() && !entries.empty()) + request.adventure_record = ReadAdventureReference(entries.front()); + } catch (const std::exception&) { + // A network outage should never prevent practising a route. + } + } + return [request = std::move(request), signed_in]() mutable { + QueueTimeTrialRequest(std::move(request), signed_in); + }; + }); +} + +struct AdventureBoardRow { + trial::Adventure goal; + std::string_view id, title, description; +}; +constexpr std::array kAdventureBoardRows{ + AdventureBoardRow{trial::Adventure::AnyPercent, "any-percent", "Any%", "Beat Wizpig in Future Fun Land."}, + AdventureBoardRow{trial::Adventure::HundredPercent, "100-percent", "100%", "Complete the Adventure checklist and beat Wizpig."}, + AdventureBoardRow{trial::Adventure::AnyPercentGlitchless, "any-percent-glitchless", "Any% Glitchless", "Defeat each boss without banned glitches."}, + AdventureBoardRow{trial::Adventure::AllTrophyRaces, "all-trophy-races", "All Trophy Races", + "Finish all five Trophy sets in Tracks Mode."}, + AdventureBoardRow{trial::Adventure::AllBosses, "all-bosses", "All Bosses", + "Win all six boss rematches from the completed Adventure slot."}, + AdventureBoardRow{trial::Adventure::AllMinigames, "all-minigames", "All Minigames", "Win all four minigames in Tracks Mode."}, + AdventureBoardRow{trial::Adventure::TrophyDinoFirst, "all-trophy-races-dino-first", "All Trophy Races - Dino Domain First", + "In Tracks Mode, race all five Trophy sets beginning in Dino Domain."}, + AdventureBoardRow{trial::Adventure::TrophyFutureFirst, "all-trophy-races-ffl-first", "All Trophy Races - Future Fun Land First", + "In Tracks Mode, race all five Trophy sets beginning in Future Fun Land."}, + AdventureBoardRow{trial::Adventure::CarPercent, "car-percent", "Car%", "Win each available car course in Tracks Mode."}, + AdventureBoardRow{trial::Adventure::HoverPercent, "hover-percent", "Hover%", "Win each available hovercraft course in Tracks Mode."}, + AdventureBoardRow{trial::Adventure::PlanePercent, "plane-percent", "Plane%", "Win each available plane course in Tracks Mode."}, + AdventureBoardRow{trial::Adventure::TTAmulet, "tt-amulet-no-wrong-warp", "T.T. Amulet - No Wrong Warp", + "Earn the four T.T. Amulet pieces through normal progression."}, +}; + +bool QualifiedAdventureBoard(const dkr::store::Json* catalogue, const std::string& board) { + return catalogue && catalogue->contains("boards") && + std::ranges::any_of(catalogue->at("boards"), [&](const auto& entry) { + return StoreText(entry, "id", 96) == board && entry.value("ranked", false); + }); +} + +std::function DrawPracticeAdventure(float width, const dkr::store::Json* catalogue, bool signed_in) { + OlHeading("Challenge Runs", width < 275.F ? 19.F : 24.F, kOlCream, width); + auto& selected = g_run_setup.challenge; + static const auto categories = [] { + std::vector choices; + choices.reserve(kAdventureBoardRows.size()); + for (const auto& row : kAdventureBoardRows) + choices.emplace_back(std::string(row.title)); + return choices; + }(); + selected = std::clamp(selected, 0, int(categories.size()) - 1); + SettingsDropdown("run-category", "Category", &selected, categories, std::min(360.F, width)); + const auto& category = kAdventureBoardRows[static_cast(selected)]; + PaddockGap(8.F); + OlParagraph(category.description, 15.F, kOlSoft, width); + const auto board = "adventure-" + std::string(category.id); + const bool qualified = QualifiedAdventureBoard(catalogue, board); + return [goal = category.goal, board, signed_in, qualified] { + StartAdventureRun(goal, board, signed_in, qualified); + }; +} + +void DrawAdventureBoards(float width, const dkr::store::Json* catalogue, TrackQuery& query) { + const auto* catalogue_categories = + catalogue && catalogue->contains("adventureCatalogue") ? &catalogue->at("adventureCatalogue") : nullptr; + for (const auto& category : kAdventureBoardRows) { + const std::string board = "adventure-" + std::string(category.id); + const dkr::store::Json* records = nullptr; + if (catalogue_categories) { + const auto entry = std::ranges::find_if(*catalogue_categories, [&](const auto& row) { + return StoreText(row, "id", 96) == category.id; + }); + if (entry != catalogue_categories->end()) + records = &*entry; + } + const bool qualified = QualifiedAdventureBoard(catalogue, board); + ImGui::PushID(category.id.data()); + DrawLeaderboardTrackRow(width, std::string(category.title), std::string(category.description), [&](float inner) { + if (!qualified) { + OlParagraph("Awaiting qualification", 14.F, kOlAmber, inner); + return; + } + if (g_track_return_focus == category.id) { + ImGui::SetKeyboardFocusHere(); + g_track_return_focus.clear(); + } + if (OlButton("View Times")) { + query = {}; + query.id = category.id; + query.full_game = true; + dkr::store::service().load_leaderboards({}, query); + } + }, records, true); + ImGui::PopID(); + } +} + +#include "speedrunning_welcome.inl" + +void DrawLeaderboardsPage(float width, bool entered, bool live) { + enum Category { TopPlayers, Vanilla, Custom, FullGame, Runs }; + enum RunTab { NewRun, Replays, MySubmittedRuns, ReviewRuns, Options }; + static const std::vector labels{"Top Players", "Vanilla Tracks", "Custom Tracks", "Full Game", "Runs"}; + static int category = TopPlayers; + static RunTab run_tab = NewRun; + static std::string last_requested_owner; + static RunTab last_requested_tab = NewRun; + static std::string world, vehicle; + static char search[121]{}; + static TrackQuery query; + static bool back_to_profile = false; auto& service = dkr::store::service(); const auto published = service.view(); const auto* snapshot = published.get(); if (g_leaderboard_layout_check) { snapshot = &LeaderboardLayoutFixture(); - category = g_launcher_layout_step == 3 ? 1 : 0; - selected_board = g_launcher_layout_step == 2 ? "ancient-lake-car" : ""; - } else if (entered && !snapshot->speedrun_catalogue) { - service.load_leaderboards(); - } - DrawPageHeading("LEADERBOARDS"); - PaddockGap(8.F); - OlParagraph("Race for a personal best and see how other players set theirs.", 16.F, kOlSoft, width); - PaddockGap(12.F); - if (OlButton("Post a run", OlTone::Go)) - SDL_OpenURL(kLeaderboardPost); - ImGui::SameLine(); - if (OlButton("Website")) - SDL_OpenURL(kLeaderboardWebsite); - ImGui::SameLine(); - { - const OlDisabled busy(snapshot->speedrun_loading); - if (OlButton("Refresh")) - service.load_leaderboards(selected_board); + category = g_launcher_layout_step == 3 ? Custom + : g_launcher_layout_step == 4 ? FullGame + : g_launcher_layout_step == 2 ? Vanilla + : Runs; + query = {g_launcher_layout_step == 2 ? "ancient-lake" : ""}; + run_tab = NewRun; + } else if (entered) { + const bool after_run = std::exchange(g_open_speedrunning_result, false); + category = after_run ? Runs : TopPlayers; + query = {}; + back_to_profile = false; + g_track_return_focus.clear(); + run_tab = after_run && RunPreference(RunOption::ReturnTo) ? Replays : NewRun; + last_requested_tab = NewRun; + SelectOverallPlayer({}); + g_overall_focus.clear(); + g_overall_tab = OverallPlayerTab::Score; + if (!DialogJobRunning()) + RefreshOverallRankings(); + g_refresh_replay_library = true; + g_published_replay_times = {}; + if (!snapshot->speedrun_catalogue) + service.load_leaderboards(); } - ImGui::SameLine(); - if (OlButton("Back to Play")) - g_page_navigation_request = kPagePlay; - PaddockGap(12.F); - const int next = StoreTabLine(labels, category, width, "speedrun-category"); + const auto role = StoreText(snapshot->user, "role", 20); + const bool staff = role == "moderator" || role == "admin"; + const auto owner = RankedRunsOwner(); + const bool can_review = staff && !owner.empty(); + if (run_tab == ReviewRuns && !can_review) + run_tab = NewRun; + const bool showing_submissions = category == Runs && (run_tab == MySubmittedRuns || run_tab == ReviewRuns); + const float refresh = PaddockImportButtonWidth("Refreshing..."); + const float website = PaddockImportButtonWidth("Website"); + const float actions = refresh + website + 12.F; + DrawSharedPageHeader(width, live ? "LEADERBOARDS" : "SPEEDRUNNING", + "Race for a personal best and watch how other players set theirs.", actions, [&] { + { + const OlDisabled loading(snapshot->speedrun_loading || DialogJobRunning() || + (showing_submissions && owner.empty())); + if (PaddockImportButton(snapshot->speedrun_loading ? "Refreshing...###speedrun-refresh" + : "Refresh###speedrun-refresh", + std::min(width, refresh), true)) { + if (showing_submissions) { + RefreshLeaderboardRuns(run_tab == ReviewRuns); + } else if (category == TopPlayers) { + RefreshOverallRankings(); + } else if (category == Runs && run_tab == Replays) { + g_refresh_replay_library = true; + service.load_leaderboards(); + } else { + service.load_leaderboards({}, query.id.empty() ? std::nullopt : std::optional(query)); + } + } + } + if (width >= actions) + ImGui::SameLine(0.F, 12.F); + else + PaddockGap(12.F); + if (PaddockImportButton("Website###speedrun-website", std::min(width, website), false, true)) + SDL_OpenURL(kLeaderboardWebsite); + }); + DrawLocalRunConfirmation(); + if (!live && !g_leaderboard_layout_check) + DrawSpeedrunningWelcome(entered, !owner.empty(), staff, snapshot->speedrun_catalogue.get()); + const int next = StoreTabLine(labels, category, width, "speedrun-category", true); if (next != category) { category = next; - selected_board.clear(); + query = {}; + back_to_profile = false; + g_track_return_focus.clear(); + run_tab = NewRun; + last_requested_tab = NewRun; + if (category == TopPlayers && g_overall_standings.is_null() && !DialogJobRunning()) + RefreshOverallRankings(); + world.clear(); + vehicle.clear(); + search[0] = '\0'; } - PaddockGap(12.F); - if (!snapshot->speedrun_error.empty()) + if ((category != Runs || (run_tab != NewRun && run_tab != Options)) && !snapshot->speedrun_error.empty()) OlParagraph(snapshot->speedrun_error, 15.F, kOlError, width); - if (!selected_board.empty()) { - if (OlButton("All tracks") || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) - selected_board.clear(); - else if (snapshot->speedrun_board && - StoreText((*snapshot->speedrun_board)["board"], "id", 96) == selected_board) { - DrawLeaderboardRanking(width, *snapshot->speedrun_board); - return; + if (!g_time_trial_message.empty()) + OlParagraph(g_time_trial_message, 15.F, kOlSoft, width); + PaddockGap(8.F); + if (category == TopPlayers) { + if (const auto selected = DrawOverallRankings(width)) { + query = *selected; + category = query.full_game ? FullGame : query.custom ? Custom : Vanilla; + back_to_profile = true; + service.load_leaderboards({}, query); + } + return; + } + if (category == Runs) { + std::vector run_tabs{"Run", "Replays", "My Submitted Runs"}; + if (can_review) + run_tabs.emplace_back("Review Runs"); + const int options_index = static_cast(run_tabs.size()); + run_tabs.emplace_back("Options"); + const int selected = StoreTabLine(run_tabs, run_tab == Options ? options_index : run_tab, width, + "speedrun-runs", true); + const auto next_tab = selected == options_index ? Options : static_cast(selected); + if (next_tab == Replays && run_tab != Replays) + g_refresh_replay_library = true; + run_tab = next_tab; + if (owner.empty() || (run_tab != MySubmittedRuns && run_tab != ReviewRuns)) { + last_requested_owner.clear(); + last_requested_tab = NewRun; + } else if (!DialogJobRunning() && (last_requested_tab != run_tab || last_requested_owner != owner)) { + last_requested_tab = run_tab; + last_requested_owner = owner; + RefreshLeaderboardRuns(run_tab == ReviewRuns); + } + PaddockGap(8.F); + if (run_tab == NewRun) + DrawLeaderboardPractice(width, snapshot->speedrun_catalogue.get()); + else if (run_tab == Replays) + DrawLocalReplays(width, snapshot->speedrun_catalogue.get()); + else if (run_tab == Options) + DrawSpeedrunningOptions(width); + else + DrawLeaderboardRuns(width, run_tab == ReviewRuns); + return; + } + if (!query.id.empty()) { + if (OlButton(back_to_profile ? "Back to player stats" : category == FullGame ? "All categories" : "All tracks") || + ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) { + if (!back_to_profile) + g_track_return_focus = query.id; + query = {}; + if (std::exchange(back_to_profile, false)) { + g_overall_focus = g_overall_player; + category = TopPlayers; + return; + } } else { if (snapshot->speedrun_loading) - OlParagraph("Loading times…", 15.F, kOlSoft, width); + OlParagraph("Loading times...", 15.F, kOlSoft, width); + else if (snapshot->speedrun_board && StoreText(snapshot->speedrun_board->at("track"), "id", 96) == query.id) + DrawLeaderboardRanking(width, *snapshot->speedrun_board, query); return; } } + if (category == FullGame) { + DrawAdventureBoards(width, snapshot->speedrun_catalogue.get(), query); + return; + } if (!snapshot->speedrun_catalogue) { if (snapshot->speedrun_loading) - OlParagraph("Loading leaderboards…", 15.F, kOlSoft, width); + OlParagraph("Loading leaderboards...", 15.F, kOlSoft, width); return; } - const auto& catalogue = *snapshot->speedrun_catalogue; - std::vector events; - for (const auto& event : catalogue["boards"]) - if (StoreText(event, "kind", 16) == kinds[category]) - events.push_back(&event); - if (events.empty()) { - DrawOlCard(width, OlPanelLook{}, [&](float inner) { - OlParagraph(category == 2 ? "Planned categories include Any%, 100% and All Trophy Races." - : "Times will appear here once the first tracks pass replay qualification.", - 15.F, kOlSoft, inner); - }); - PaddockGap(12.F); - } else { - const int columns = std::clamp(int(width / 320.F), 1, 4); - ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, {5.F, 5.F}); - if (ImGui::BeginTable("leaderboard-events", columns, ImGuiTableFlags_SizingStretchSame, {width, 0.F})) { - for (const auto* event : events) { - ImGui::TableNextColumn(); - const auto id = StoreText(*event, "id", 96); - ImGui::PushID(id.c_str()); - DrawOlFeature(ImGui::GetContentRegionAvail().x, StoreText(*event, "title", 120).c_str(), nullptr, - [&](float inner) { - PaddockGap(6.F); - OlParagraph(StoreText(*event, "category", 80) + " · " + - StoreText(*event, "vehicle", 24), - 15.F, kOlSoft, inner); - PaddockGap(8.F); - const OlDisabled busy(snapshot->speedrun_loading); - if (OlButton("View times")) { - service.load_leaderboards(id); - selected_board = id; - } - }); - ImGui::PopID(); - } - ImGui::EndTable(); - } - ImGui::PopStyleVar(); - PaddockGap(12.F); - } - if (category != 1) - return; - - DrawOlFeature(width, "Tracks in the Mod Library", nullptr, [&](float inner) { - for (const auto& track : catalogue["customTracks"]) { - PaddockGap(8.F); - OlParagraph(StoreText(track, "title", 120), 16.F, kOlInk, inner, true); - const bool qualified = track.contains("qualified") && track["qualified"] == true; - OlParagraph(StoreText(track, "version", 80) + (qualified ? " · Ranked" : " · Awaiting qualification"), 14.F, - kOlSoft, inner); + const auto tracks = catalogue.value(category == Vanilla ? "vanillaTracks" : "customTracks", dkr::store::Json::array()); + constexpr float world_width = 224.F, vehicle_width = 160.F; + const float gap = ImGui::GetStyle().ItemSpacing.x; + const float filters_width = category == Vanilla ? world_width + vehicle_width + 2.F * gap : 0.F; + const float search_width = std::min(category == Vanilla ? 300.F : 360.F, + width >= filters_width + 176.F ? width - filters_width : width); + OlInputOptions options; + options.hint = "Track name"; + options.height = kSettingsDropdownHeight; + ImGui::BeginGroup(); + SettingsLabel("Search tracks", search_width); + if (OlInput("##find-track", nullptr, search, sizeof(search), search_width, options) == OlInputResult::Gamepad) { + RequestCustomTextKeyboard( + "Search tracks", search, sizeof(search), + [](const std::string& text) { std::snprintf(search, sizeof(search), "%s", text.c_str()); }, true); + } + ImGui::EndGroup(); + float row_width = search_width; + const auto draw_filter = [&](const char* label, const LeaderboardChoices& choices, std::string& value, float preferred) { + const float field_width = std::min(preferred, width); + if (row_width > 0.F && row_width + gap + field_width <= width + 0.1F) { + ImGui::SameLine(); + row_width += gap; + } else { + row_width = 0.F; + } + LeaderboardFilter(label, choices, value, field_width); + row_width += field_width; + }; + if (category == Vanilla) { + LeaderboardChoices worlds{{"", "All worlds"}}; + for (const auto& track : tracks) { + auto name = StoreText(track, "world", 80); + if (!name.empty() && + std::none_of(worlds.begin(), worlds.end(), [&](const auto& entry) { return entry.first == name; })) + worlds.emplace_back(name, name); } - if (catalogue["customTracks"].empty()) - OlParagraph("No custom tracks are listed yet.", 15.F, kOlSoft, inner); + draw_filter("World", worlds, world, world_width); + static const LeaderboardChoices vehicles{ + {"", "All vehicles"}, {"car", "Car"}, {"hovercraft", "Hovercraft"}, {"plane", "Plane"}}; + draw_filter("Vehicle", vehicles, vehicle, vehicle_width); + } + PaddockGap(8.F); + const auto needle = dkr::runtime::texture_browser::lower_ascii(search); + std::vector> matching; + for (const auto& track : tracks) { + const auto title = StoreText(track, "title", 120); + if (dkr::runtime::texture_browser::lower_ascii(title).find(needle) == std::string::npos) + continue; + const auto track_world = StoreText(track, "world", 80); + const auto supported = track.value("vehicles", dkr::store::Json::array()); + if (category == Vanilla && + ((!world.empty() && track_world != world) || + (!vehicle.empty() && std::find(supported.begin(), supported.end(), vehicle) == supported.end()))) + continue; + const auto& boards = catalogue["boards"]; + const bool qualified = + category == Custom ? track.value("qualified", false) + : std::any_of(boards.begin(), boards.end(), [&](const auto& board) { + return StoreText(board, "kind", 20) == "vanilla" && + StoreText(board, "title", 120) == title && board.value("ranked", false) && + (vehicle.empty() || StoreText(board, "vehicle", 24) == vehicle); + }); + matching.emplace_back(&track, qualified); + } + OlParagraph(matching.empty() ? "No tracks match these filters." + : std::to_string(matching.size()) + " of " + std::to_string(tracks.size()) + " tracks", + 14.F, kOlSoft, width); + for (const auto& [track, qualified] : matching) { + const auto id = StoreText(*track, "id", 96); + const auto title = StoreText(*track, "title", 120); + std::string detail = + category == Custom ? "Version " + StoreText(*track, "version", 40) : StoreText(*track, "world", 80); + for (const auto& choice : track->value("vehicles", dkr::store::Json::array())) + detail += " | " + LeaderboardVehicle(choice.get()); + ImGui::PushID(id.c_str()); + DrawLeaderboardTrackRow(width, title, detail, [&](float inner) { + if (!qualified) { + OlParagraph("Awaiting qualification", 14.F, kOlAmber, inner); + return; + } + const OlDisabled loading(snapshot->speedrun_loading); + if (g_track_return_focus == id) { + ImGui::SetKeyboardFocusHere(); + g_track_return_focus.clear(); + } + if (OlButton("View Times")) { + query = {id, category == Vanilla ? vehicle : std::string{}, {}, category == Custom}; + service.load_leaderboards({}, query); + } + }, track->contains("leaders") ? track : nullptr); + ImGui::PopID(); + } + if (category == Custom) { if (const auto cursor = StoreText(catalogue, "nextCursor", 96); !cursor.empty()) { - PaddockGap(8.F); const OlDisabled busy(snapshot->speedrun_loading); if (OlButton("More tracks")) - service.load_leaderboards({}, cursor); + service.load_leaderboards(cursor); } - }); + } } diff --git a/runtime-recomp/src/game/library_ui/navigation_check.inl b/runtime-recomp/src/game/library_ui/navigation_check.inl index 80f59341..dbe8cab0 100644 --- a/runtime-recomp/src/game/library_ui/navigation_check.inl +++ b/runtime-recomp/src/game/library_ui/navigation_check.inl @@ -10,6 +10,7 @@ int g_launcher_layout_step = 0; bool g_launcher_layout_sized = false; bool g_localisation_cycle_check = false; bool g_leaderboard_layout_check = false; +bool g_leaderboard_navigation_requested = false; double g_launcher_layout_at = 0; constexpr std::array kLauncherLayoutPages{0, 6, 6, 6, 6, 6, 10, 1, 2, 3, 4, 5, 8, 9, 7, 10, 10, 10, 10, 10, 10, 10, 10, 3, 3, 3, 3, 6, 6, 6, @@ -20,19 +21,24 @@ bool g_surface_scroll_bottom = false; #include "handoff_check.inl" bool PlayLaunchLayoutCheck(); bool SaveDraftLayoutCheck(); +bool ModdedSaveDraftLayoutCheck(); void PlayLaunchCaptureCheck(); void SaveDraftCaptureCheck(); void LibrarySelectCheckView(int step, int& page) { if (g_leaderboard_layout_check) { - page = step == 0 ? kPagePlay : dkr::library_ui::LeaderboardsPage; + if (step == 1 && !g_leaderboard_navigation_requested) { + g_page_navigation_request = dkr::library_ui::LeaderboardsPage; + g_leaderboard_navigation_requested = true; + } return; } if (SaveDraftLayoutCheck()) { page = kPageSaveManager; - g_saves_page.scope = 0; - g_saves_page.section = 1; - g_surface_scroll_bottom = true; + g_saves_page.scope = ModdedSaveDraftLayoutCheck() ? 2 : 0; + g_saves_page.section = SaveEditorSection::Progress; + g_saves_page.selected_slot = std::min(g_launcher_layout_step / 2, 2); + g_surface_scroll_bottom = false; return; } if (PlayLaunchLayoutCheck()) { @@ -56,7 +62,7 @@ void LibrarySelectCheckView(int step, int& page) { g_mods_page.section = g_mods_page.entry_section = step - 26; if (page == kPageSaveManager) { g_saves_page.scope = step == 32 ? 3 : step == 33 ? 1 : 0; - g_saves_page.section = step == 30 ? 1 : step == 31 ? 2 : 0; + g_saves_page.section = step == 31 ? SaveEditorSection::Files : SaveEditorSection::Progress; } if (page == kPageOnlineMp) { const std::array sections{OlSection::Play, OlSection::Settings, OlSection::Profile, @@ -98,7 +104,7 @@ bool LauncherLayoutCheckRoute(int& page) { // Captures only an explicitly authenticated, disposable launcher test profile. // Ordinary startup performs no pixel readback, window resize or image writes. -void LauncherLayoutCheckCapture(SDL_Renderer* renderer) { +void LauncherLayoutCheckCapture(SDL_Renderer* renderer, int current_page) { if (g_launcher_layout_root.empty() || g_launcher_layout_step >= int(kLauncherLayoutPages.size())) return; if (!g_launcher_layout_sized) { @@ -139,9 +145,8 @@ void LauncherLayoutCheckCapture(SDL_Renderer* renderer) { SDL_FreeSurface(surface); if (!saved) return; - const int page = g_leaderboard_layout_check && g_launcher_layout_step > 0 - ? dkr::library_ui::LeaderboardsPage - : kLauncherLayoutPages[std::size_t(g_launcher_layout_step)]; + const int page = + g_leaderboard_layout_check ? current_page : kLauncherLayoutPages[std::size_t(g_launcher_layout_step)]; std::fprintf(stderr, "[launcher-layout][isolated-check] step=%d page=%d width=%d height=%d captured\n", g_launcher_layout_step, page, width, height); std::fprintf(stderr, "[localisation][isolated-check] step=%d language=%s atlas=%dx%d texture=%p\n", @@ -156,7 +161,7 @@ void LauncherLayoutCheckCapture(SDL_Renderer* renderer) { ++g_launcher_layout_step; g_launcher_layout_at = PaddockClock(); if ((PlayLaunchLayoutCheck() && g_launcher_layout_step == 6) || - (g_leaderboard_layout_check && g_launcher_layout_step == 4)) { + (g_leaderboard_layout_check && g_launcher_layout_step == 5)) { SDL_Event quit{}; quit.type = SDL_QUIT; SDL_PushEvent(&quit); diff --git a/runtime-recomp/src/game/library_ui/play_launch_bar.inl b/runtime-recomp/src/game/library_ui/play_launch_bar.inl index 33fd69fa..be5f7509 100644 --- a/runtime-recomp/src/game/library_ui/play_launch_bar.inl +++ b/runtime-recomp/src/game/library_ui/play_launch_bar.inl @@ -9,11 +9,15 @@ extern int g_launcher_layout_step; bool PlayLaunchLayoutCheck() { const char* value = std::getenv("DKR_OWNED_CHECK_PLAY_LAUNCH"); return !g_launcher_layout_root.empty() && value && - (std::string_view(value) == "1" || std::string_view(value) == "save"); + (std::string_view(value) == "1" || std::string_view(value) == "save" || + std::string_view(value) == "save-modded"); } bool SaveDraftLayoutCheck() { const char* value = std::getenv("DKR_OWNED_CHECK_PLAY_LAUNCH"); - return PlayLaunchLayoutCheck() && std::string_view(value) == "save"; + return PlayLaunchLayoutCheck() && std::string_view(value).starts_with("save"); +} +bool ModdedSaveDraftLayoutCheck() { + return SaveDraftLayoutCheck() && std::string_view(std::getenv("DKR_OWNED_CHECK_PLAY_LAUNCH")) == "save-modded"; } struct PlayLaunchGeometry { ImVec2 button_min{}, button_max{}, clip_min{}, clip_max{}; @@ -78,18 +82,24 @@ void PlayLaunchCaptureCheck() { } struct SaveDraftGeometry { - ImRect panel, bounds; - float top = 0.F; - bool dirty = false; + ImRect panel, bounds, slots, editor, editor_body; + float top = 0.F, editor_scroll = 0.F; + int selected_slot = 0; + bool dirty = false, modded = false; }; SaveDraftGeometry g_save_draft_geometry; void SaveDraftCaptureCheck() { const auto& g = g_save_draft_geometry; std::fprintf( stderr, - "[save-draft][isolated-check] step=%d bar-left=%.1f bar-right=%.1f bar-top=%.1f bar-bottom=%.1f panel-left=%.1f panel-right=%.1f panel-bottom=%.1f dirty=%d\n", + "[save-draft][isolated-check] step=%d bar-left=%.1f bar-right=%.1f bar-top=%.1f bar-bottom=%.1f " + "panel-left=%.1f panel-right=%.1f panel-bottom=%.1f dirty=%d slots-left=%.1f slots-right=%.1f " + "slots-bottom=%.1f editor-left=%.1f editor-right=%.1f editor-top=%.1f editor-bottom=%.1f " + "editor-scroll=%.1f editor-body-left=%.1f editor-body-right=%.1f slot=%d modded=%d\n", g_launcher_layout_step, g.panel.Min.x, g.panel.Max.x, g.top, g.panel.Max.y, g.bounds.Min.x, g.bounds.Max.x, - g.bounds.Max.y, int(g.dirty)); + g.bounds.Max.y, int(g.dirty), g.slots.Min.x, g.slots.Max.x, g.slots.Max.y, g.editor.Min.x, g.editor.Max.x, + g.editor.Min.y, g.editor.Max.y, g.editor_scroll, g.editor_body.Min.x, g.editor_body.Max.x, g.selected_slot, + int(g.modded)); } float PlayLaunchButtonWidth(float width) { diff --git a/runtime-recomp/src/game/library_ui/play_tools.inl b/runtime-recomp/src/game/library_ui/play_tools.inl index c893f0ef..a7747e80 100644 --- a/runtime-recomp/src/game/library_ui/play_tools.inl +++ b/runtime-recomp/src/game/library_ui/play_tools.inl @@ -2,9 +2,10 @@ const char* SessionModsCaption(bool enabled) { return enabled ? "Session mods: ON" : "Session mods: OFF"; } constexpr float kPlayToolHeight = 40.F, kPlayToolGap = 8.F; -void DrawPlayTools(float width) { +void DrawPlayTools(float width, bool live) { + const char* speedrun_label = live ? "Leaderboards###play-leaderboards" : "Speedrunning###play-leaderboards"; const std::array widths{PaddockImportButtonWidth("Achievements", true), - PaddockImportButtonWidth("Leaderboards", true), + PaddockImportButtonWidth(speedrun_label, true), std::max(PaddockImportButtonWidth(SessionModsCaption(true), true), PaddockImportButtonWidth(SessionModsCaption(false), true)), PaddockImportButtonWidth("Save Manager", true)}; @@ -26,7 +27,7 @@ void DrawPlayTools(float width) { }; if (draw(0, "Achievements###play-achievements", 1)) g_page_navigation_request = kPageAchievements; - if (draw(1, "Leaderboards###play-leaderboards", 4)) + if (draw(1, speedrun_label, 4)) g_page_navigation_request = dkr::library_ui::LeaderboardsPage; const bool enabled = dkr::session_content::next_enabled.load(); const auto caption = std::string(SessionModsCaption(enabled)) + "###play-session-mods"; @@ -39,8 +40,3 @@ void DrawPlayTools(float width) { ImGui::SetCursorScreenPos(at); ImGui::Dummy({width, float(rows) * kPlayToolHeight + float(rows - 1) * kPlayToolGap}); } -void DrawPlayToolBack(float) { - if (PaddockTextLink("Back to Play")) - g_page_navigation_request = kPagePlay; - PaddockGap(16.F); -} diff --git a/runtime-recomp/src/game/library_ui/policy.hpp b/runtime-recomp/src/game/library_ui/policy.hpp index 46d652cc..405c34f9 100644 --- a/runtime-recomp/src/game/library_ui/policy.hpp +++ b/runtime-recomp/src/game/library_ui/policy.hpp @@ -11,6 +11,9 @@ namespace dkr::library_ui { // Existing page identities stay stable. Only visual order changes. inline constexpr int LibraryPage = 10, PageCount = 11, LeaderboardsPage = 14; inline constexpr std::array SidebarOrder{0, 5, LibraryPage, 6, 1, 2, 3, 7, 13, 11, 12}; +inline constexpr bool is_content_page(int page) { + return (page >= 0 && page < PageCount) || page == LeaderboardsPage; +} inline constexpr int sidebar_parent(int page) { return page == 4 || page == 9 || page == LeaderboardsPage ? 0 : page; } @@ -35,6 +38,13 @@ inline bool configurable(std::string_view id, bool selected, bool approved, bool inline bool writes_locked(bool game, bool lobby, bool preparing, bool admission, bool vehicles) { return game || lobby || preparing || admission || vehicles; } +inline constexpr bool can_post_replay_attempt(bool has_attempt, bool practice, bool personal_best) { + return has_attempt && (!practice || personal_best); +} +inline constexpr bool can_purge_replay(bool personal_best, bool submitted, bool include_bests, + bool include_unsubmitted) { + return (!personal_best || include_bests) && (submitted || include_unsubmitted); +} // This conversion is for displayed status copy, never IDs, URLs or credentials. inline std::string visible_status(std::string value) { for (const auto& words : {std::pair{"Mod Store", "Mod Library"}, std::pair{"MOD STORE", "MOD LIBRARY"}}) { diff --git a/runtime-recomp/src/game/library_ui/replay_library.inl b/runtime-recomp/src/game/library_ui/replay_library.inl new file mode 100644 index 00000000..a2b4699c --- /dev/null +++ b/runtime-recomp/src/game/library_ui/replay_library.inl @@ -0,0 +1,328 @@ +struct LocalReplay { + std::filesystem::path file; + std::filesystem::file_time_type saved; + std::string title, course, racer, vehicle, board, posted_owner, adventure_category, ruleset, track_id, track_hash; + std::int64_t time = 0, best_lap = 0; + bool practice = true; + bool valid = false; + bool can_ghost = false; + bool personal_best = false; + bool beat_ghost = false; + bool has_attempt = false; + bool local_capture = false; +}; + +std::vector g_local_replays; +std::filesystem::path g_replay_library_profile; +bool g_refresh_replay_library = true; + +constexpr std::size_t kReplayLibraryBytes = 3 * 1024 * 1024; + +dkr::store::Json ReadReplaySummary(const std::filesystem::path& file) { + const auto bytes = std::filesystem::file_size(file); + std::ifstream input(file, std::ios::binary); + std::array header{}; + if (bytes > kReplayLibraryBytes || !input.read(reinterpret_cast(header.data()), header.size()) || + std::string_view(reinterpret_cast(header.data()), 8) != "DKRREPL2") + throw std::runtime_error("This file is not a supported DKR-R replay."); + const auto length = std::uint32_t(header[8]) | (std::uint32_t(header[9]) << 8) | + (std::uint32_t(header[10]) << 16) | (std::uint32_t(header[11]) << 24); + if (!length || length > 65536 || length > bytes - header.size()) + throw std::runtime_error("The replay metadata is incomplete."); + std::string metadata(length, '\0'); + if (!input.read(metadata.data(), metadata.size())) + throw std::runtime_error("The replay metadata could not be read."); + auto manifest = dkr::store::Json::parse(metadata); + const auto rules = StoreText(manifest, "ruleset", 48); + const bool adventure = rules == trial::kAdventureRules || rules == trial::kAdventureOriginalRouteRules || + rules == trial::kAdventureMilestoneRules || + rules == trial::kAdventureColdSaveRules || + rules == trial::kAdventureVisualRngRules || + rules == trial::kAdventureSharedRngRules || + rules == trial::kLegacyAdventureRules; + const auto ticks = LeaderboardNumber(manifest, "ticks"); + const auto clock = LeaderboardNumber(manifest, "clockTicks"); + if ((!adventure && rules != trial::kLegacyRules && rules != trial::kVanillaRules && + rules != trial::kCustomRules && rules != trial::kCustomVariableLapsRules) || + !ticks || !clock || clock > ticks * 2 || bytes != header.size() + length + ticks * 4 || + !trial::supported_replay_rom(manifest.value("rom", 0U))) + throw std::runtime_error("The replay format or recording length is unsupported."); + return manifest; +} + +std::filesystem::path ReplaySidecar(std::filesystem::path file) { + return file += ".json"; +} + +bool ReplayLibraryFile(const std::filesystem::path& file) { + std::error_code ec; + return std::filesystem::symlink_status(file, ec).type() == std::filesystem::file_type::regular; +} + +dkr::store::Json ReadReplaySidecar(const std::filesystem::path& file) { + const auto path = ReplaySidecar(file); + if (ReplayLibraryFile(path)) { + try { + const auto text = dkr::updates::read_text(path, 4096); + auto metadata = dkr::store::Json::parse(text, nullptr, false); + if (metadata.is_object()) + return metadata; + } catch (const std::exception&) { + // Sidecar errors must not hide a playable replay. + } + } + return dkr::store::Json::object(); +} + +void WriteReplaySidecar(const std::filesystem::path& file, const dkr::store::Json& metadata) { + dkr::updates::durable_write(ReplaySidecar(file), metadata.dump()); +} + +void CheckManagedReplayDirectory(const std::filesystem::path& directory) { + std::error_code ec; + const auto state = std::filesystem::symlink_status(directory, ec).type(); + if (state != std::filesystem::file_type::directory && state != std::filesystem::file_type::not_found) + throw std::runtime_error("The replay folder is unavailable."); +} + +bool OwnReplayFile(const std::filesystem::path& file, const dkr::store::Json& metadata) { + const auto name = PathUtf8(file.filename()); + const auto origin = StoreText(metadata, "origin", 20); + return file.extension() == ".dkrreplay" && !name.starts_with("Replay-") && !name.starts_with("Imported-") && + origin != "Downloaded" && origin != "Imported" && ReplayLibraryFile(file); +} + +bool ReplayHasRankedAttempt(const dkr::store::Json& manifest) { + return !manifest.value("practice", true) && !StoreText(manifest, "board", 96).empty() && + !StoreText(manifest, "ticket", 160).empty(); +} + +bool IsLocalReplayCapture(const dkr::store::Json& manifest) { + return manifest.value("practice", false) && !manifest.contains("ticket") && !manifest.contains("board") && + !manifest.contains("engine") && !manifest.contains("releaseHash") && + !manifest.at("checkpoints").empty(); +} + +std::vector ReadLocalReplayLibrary(const std::filesystem::path& directory) { + CheckManagedReplayDirectory(directory); + std::vector replays; + if (!std::filesystem::exists(directory)) + return replays; + const auto installed = dkr::runtime::custom_tracks::installed_replay_tracks(); + std::map records; + for (const auto& entry : std::filesystem::directory_iterator(directory)) { + const auto& file = entry.path(); + if (file.extension() != ".dkrreplay" || !ReplayLibraryFile(file)) + continue; + const auto metadata = ReadReplaySidecar(file); + if (!OwnReplayFile(file, metadata)) + continue; + LocalReplay item; + item.file = file; + std::error_code ec; + item.saved = entry.last_write_time(ec); + item.title = StoreText(metadata, "title", 120); + item.posted_owner = StoreText(metadata, "postedOwner", 96); + std::string record; + try { + const auto manifest = ReadReplaySummary(file); + const auto rules = StoreText(manifest, "ruleset", 48); + item.ruleset = rules; + if (rules.starts_with("adventure-")) { + const auto id = StoreText(manifest, "category", 40); + item.adventure_category = id; + const auto category = trial::adventure_for(id); + item.board = "adventure-" + id; + record = rules + ":" + id; + for (const auto& choice : trial::kAdventureCategories) + if (choice.goal == category) + item.course = choice.title; + } else { + const auto racer = manifest.value("racer", trial::kDiddy); + if (racer >= trial::kRacers.size()) + throw std::runtime_error("The replay racer is unsupported."); + item.racer = trial::kRacers[racer].name; + const auto vehicle = rules == trial::kLegacyRules ? "car" : StoreText(manifest, "vehicle", 16); + trial::Vehicle route_vehicle = trial::Vehicle::Car; + for (unsigned i = 0; i < trial::kVehicleIds.size(); ++i) { + if (trial::kVehicleIds[i] == vehicle) { + item.vehicle = trial::kVehicleNames[i]; + route_vehicle = static_cast(i); + } + } + if (item.vehicle.empty()) + throw std::runtime_error("The replay vehicle is unsupported."); + if (rules == trial::kLegacyRules) { + item.course = trial::kCourses.front().name; + item.board = trial::board_for(trial::kCourses.front(), route_vehicle, racer); + record = trial::kCourses.front().id; + } else if (rules == trial::kVanillaRules) { + if (const auto* course = trial::course_for(StoreText(manifest, "course", 64))) { + item.course = course->name; + item.board = trial::board_for(*course, route_vehicle, racer); + record = course->id; + } + } else { + item.track_id = StoreText(manifest, "trackId", 96); + item.track_hash = StoreText(manifest, "trackHash", 64); + item.course = item.track_id; + record = "custom:" + item.track_id + ":" + item.track_hash; + const auto found = std::ranges::find(installed, item.course, &dkr::runtime::custom_tracks::ReplayTrack::id); + if (found != installed.end()) + item.course = found->name; + else + std::replace(item.course.begin(), item.course.end(), '-', ' '); + } + record += ":" + vehicle + ":" + std::to_string(racer); + const auto splits = manifest.value("splits", dkr::store::Json::array()); + const auto laps = rules == trial::kCustomVariableLapsRules ? manifest.value("laps", 0U) + : trial::kRetailLapCount; + if (laps > 0 && laps <= trial::kMaximumLapCount && splits.is_array() && splits.size() == laps) { + std::int64_t previous = 0; + for (const auto& value : splits) { + const auto end = value.get(); + if (end <= previous || end > LeaderboardNumber(manifest, "clockTicks")) { + item.best_lap = 0; + break; + } + const auto lap = end - previous; + item.best_lap = item.best_lap ? std::min(item.best_lap, lap) : lap; + previous = end; + } + } + } + item.time = LeaderboardNumber(manifest, "clockTicks"); + item.beat_ghost = item.time > 0 && item.time < LeaderboardNumber(metadata, "ghostTicks"); + item.has_attempt = ReplayHasRankedAttempt(manifest); + if (item.has_attempt) + item.board = StoreText(manifest, "board", 96); + item.practice = manifest.value("practice", true) || + PathUtf8(file.filename()).find("-Practice-") != std::string::npos; + item.valid = !item.course.empty(); + item.local_capture = item.valid && IsLocalReplayCapture(manifest) && + (!rules.starts_with("adventure-") || rules == trial::kAdventureRules); + item.can_ghost = item.valid && !rules.starts_with("adventure-"); + } catch (const std::exception&) { + // Keep malformed files visible so players can remove them. + } + if (item.title.empty()) + item.title = item.valid ? item.course : PathUtf8(file.filename()); + if (item.valid) { + const auto [best, inserted] = records.try_emplace(record, replays.size()); + if (inserted) { + item.personal_best = true; + } else { + auto& prior = replays[best->second]; + if (std::tie(item.time, item.saved, item.file) < std::tie(prior.time, prior.saved, prior.file)) { + prior.personal_best = false; + item.personal_best = true; + best->second = replays.size(); + } + } + } + replays.push_back(std::move(item)); + } + std::ranges::sort(replays, [](const auto& a, const auto& b) { + return a.saved != b.saved ? a.saved > b.saved : a.file > b.file; + }); + return replays; +} + +const LocalReplay* FindLocalReplay(const std::filesystem::path& file) { + if (g_replay_library_profile != g_config_directory) + return nullptr; + const auto replay = std::ranges::find(g_local_replays, file, &LocalReplay::file); + return replay == g_local_replays.end() ? nullptr : &*replay; +} + +std::string LocalReplayDate(std::time_t time, const char* format) { + std::tm calendar{}; +#ifdef _WIN32 + if (localtime_s(&calendar, &time) != 0) + return {}; +#else + if (!localtime_r(&time, &calendar)) + return {}; +#endif + char date[40]{}; + std::strftime(date, sizeof(date), format, &calendar); + return date; +} + +std::string ReplayDate(std::filesystem::file_time_type saved) { + if (saved == std::filesystem::file_time_type::min()) + return {}; +#ifdef _MSC_VER + const auto stamp = std::chrono::clock_cast(saved); +#else + const auto stamp = std::chrono::file_clock::to_sys(saved); +#endif + return LocalReplayDate(std::chrono::system_clock::to_time_t(stamp), "%Y-%m-%d"); +} + +void RenameLocalReplay(const std::filesystem::path& file, const std::string& title) { + CheckManagedReplayDirectory(file.parent_path()); + if (!ReplayLibraryFile(file)) + throw std::runtime_error("This replay is no longer in your library."); + auto metadata = ReadReplaySidecar(file); + metadata["title"] = title; + WriteReplaySidecar(file, metadata); +} + +void RemoveLocalReplay(const std::filesystem::path& file) { + CheckManagedReplayDirectory(file.parent_path()); + if (!ReplayLibraryFile(file) || !std::filesystem::remove(file)) + throw std::runtime_error("This replay could not be removed."); + for (const auto& sidecar : {ReplaySidecar(file), trial::portable_ghost_file(file)}) { + if (ReplayLibraryFile(sidecar)) { + std::error_code ec; + std::filesystem::remove(sidecar, ec); + } + } +} + +using ReplayPurgeSelection = std::map; + +ReplayPurgeSelection SelectReplayPurge(const std::vector& replays, bool include_bests, + bool include_unsubmitted) { + ReplayPurgeSelection selected; + for (const auto& replay : replays) { + if (dkr::library_ui::can_purge_replay(replay.personal_best, !replay.posted_owner.empty(), include_bests, + include_unsubmitted)) + selected.emplace(replay.file, replay.saved); + } + return selected; +} + +std::pair PurgeLocalReplays(const std::filesystem::path& directory, + const ReplayPurgeSelection& confirmed, bool include_bests, + bool include_unsubmitted) { + const auto current = SelectReplayPurge(ReadLocalReplayLibrary(directory), include_bests, include_unsubmitted); + std::size_t removed = 0; + for (const auto& [file, saved] : confirmed) { + const auto it = current.find(file); + if (it == current.end() || it->second != saved) + continue; + try { + RemoveLocalReplay(file); + ++removed; + } catch (const std::exception&) { + // Continue with other confirmed recordings when one is in use. + } + } + return {removed, confirmed.size() - removed}; +} + +void RefreshReplayLibrary() { + const auto profile = g_config_directory; + g_refresh_replay_library = false; + RankedJob([profile] { + auto replays = ReadLocalReplayLibrary(profile / "speedruns"); + return [profile, replays = std::move(replays)]() mutable { + if (profile == g_config_directory) { + g_replay_library_profile = profile; + g_local_replays = std::move(replays); + } + }; + }); +} diff --git a/runtime-recomp/src/game/library_ui/save_indicator.inl b/runtime-recomp/src/game/library_ui/save_indicator.inl index 2ff98aca..0fde8e1c 100644 --- a/runtime-recomp/src/game/library_ui/save_indicator.inl +++ b/runtime-recomp/src/game/library_ui/save_indicator.inl @@ -26,52 +26,56 @@ PlaySavePreviewData PlayReadSavePreview(const std::filesystem::path& path) { return {{}, "Save preview unavailable. Check Save Manager."}; return {std::move(image), {}}; } -void DrawPlaySaveSummary(float width, bool live) { +void DrawPlaySaveSummary(float width, bool live, bool launching) { using namespace dkr::library_ui; namespace saves = dkr::runtime::saves; SaveScope scope = SaveScope::Vanilla; std::filesystem::path path; - bool shared_modded = false; const bool lobby = dkr::runtime::netplay::session().active(); if (live) { path = saves::runtime_save_path(); scope = running_save_scope(g_config_directory, path, saves::runtime_save_selection().online); - shared_modded = scope == SaveScope::Vanilla && dkr::session_content::running_modded.load(); - } else if (lobby) + } else if (lobby) { scope = SaveScope::Online; - else if (dkr::session_content::next_enabled.load()) { - const auto mods = g_legacy_imports.snapshot(); - for (const auto& catalogue : {mods.tracks, mods.characters}) - if (catalogue) - for (const auto& item : catalogue->tracks) - shared_modded |= item.enabled && !item.hidden; - for (const auto& item : g_code_library.view()->items) - shared_modded |= item.selected && item.enabled && item.approved && item.compatibility.empty(); - for (const auto& item : g_vehicle_library.view()->items) - shared_modded |= item.enabled; - for (const auto& item : dkr::runtime::custom_tracks::tracks()) - shared_modded |= item.enabled; - for (const auto& item : dkr::runtime::texture_packs::snapshot()) - shared_modded |= item.enabled && item.compatible; - shared_modded |= dkr::runtime::magic_codes::selected_mask() != 0; + } else if (dkr::session_content::next_enabled.load()) { + scope = SaveScope::Modded; + path = saves::personal_adventure_path(g_config_directory, true); + } + const char* heading = scope == SaveScope::Online ? "ONLINE ADVENTURE" + : scope == SaveScope::Modded ? "MODDED ADVENTURE" + : "VANILLA ADVENTURE"; + const auto heading_type = PaddockReading(16.F, true, 1.45F); + const auto heading_text = dkr::localisation::source(heading); + const float heading_width = std::ceil(PaddockMeasure(heading_type, heading_text)) + 8.F; + const float cloud_width = PlayCloudSwitchWidth() + kPlayCloudGap + kPlayCloudIconWidth; + const bool inline_cloud = width - heading_width >= 118.F + kPlayCloudGap + kPlayCloudIconWidth; + const bool cloud_locked = live || lobby || launching; + if (inline_cloud) { + ImGui::BeginGroup(); + auto position = ImGui::GetCursorScreenPos(); + position.y += (kPlayCloudControlHeight - heading_type.line) * 0.5F; + PaddockDrawRun(ImGui::GetWindowDrawList(), heading_type, position, PaddockCol(0xFFF6DA), + heading_text.data(), heading_text.data() + heading_text.size()); + ImGui::Dummy({heading_width, kPlayCloudControlHeight}); + ImGui::SameLine(0.F, 0.F); + DrawPlayCloudSaves(std::min(cloud_width, width - heading_width), cloud_locked); + ImGui::EndGroup(); + } else { + PaddockText(heading_type, PaddockRgb(0xFFF6DA), heading_text, width); + PaddockGap(4.F); + DrawPlayCloudSaves(width, cloud_locked); } - const auto indicator = shared_modded ? SaveScope::Modded : scope; - const char* heading = indicator == SaveScope::Online ? "ONLINE ADVENTURE" - : indicator == SaveScope::Modded ? "MODDED ADVENTURE" - : "OFFLINE ADVENTURE"; - PaddockText(PaddockReading(16.F, true, 1.45F), PaddockRgb(0xFFF6DA), dkr::localisation::source(heading), width); PaddockGap(6.F); const auto at = ImGui::GetCursorScreenPos(); auto* draw = ImGui::GetWindowDrawList(); draw->AddRectFilled(at, {at.x + 62.F, at.y + 22.F}, PaddockCol(0x041B26), 11.F); constexpr std::array colours{0x24D493, 0xFFC04D, 0x57CDE8}; for (int i = 0; i < 3; ++i) { - const bool active = int(indicator) == i + 1; + const bool active = int(scope) == i + 1; draw->AddCircleFilled({at.x + 11.F + 20.F * i, at.y + 11.F}, 6.F, PaddockCol(active ? colours[i] : 0x304752), 14); } - const auto save_caption = dkr::localisation::source( - shared_modded ? std::string_view("Modded game - shared personal save") : save_label(scope)); + const auto save_caption = dkr::localisation::source(save_label(scope)); const std::string label = dkr::localisation::format(live ? "save.using" : "save.next", {{"save", save_caption}}); const auto type = PaddockReading(14.F, true, 1.4F); const float label_width = std::max(1.F, width - 72.F); @@ -83,13 +87,13 @@ void DrawPlaySaveSummary(float width, bool live) { PaddockGap(6.F); std::string preview; if (scope == SaveScope::Vanilla) { - const auto& save = CachedSaveManagerView(); + const auto& save = CachedSaveManagerView().adventures[false]; preview = save.image ? dkr::localisation::save_preview(*save.image) - : std::string(dkr::localisation::source(save.adventure.exists + : std::string(dkr::localisation::source(save.info.exists ? "Save preview unavailable. Check Save Manager." - : "No offline Adventure save yet.")); - } else if (!live) { + : "No Vanilla Adventure save yet.")); + } else if (!live && scope == SaveScope::Online) { preview = std::string(dkr::localisation::source("The host supplies a separate online save when the match starts.")); } else if (path.empty()) @@ -122,9 +126,8 @@ void DrawPlaySaveSummary(float width, bool live) { PaddockText( PaddockReading(13.F, false, 1.5F), PaddockRgb(0xB0C9CC), dkr::localisation::source( - live - ? "Ordinary offline mods share your personal Adventure. Online and development saves stay separate. Preview shows saved progress." - : "Ordinary offline mods share your personal Adventure. Online and development saves stay separate."), + live ? "Preview shows saved progress for this session." + : "Session Mods selects which Adventure save you use offline."), width); PaddockGap(12.F); } diff --git a/runtime-recomp/src/game/library_ui/shared_page_ui.inl b/runtime-recomp/src/game/library_ui/shared_page_ui.inl index 9761da71..bfff35bc 100644 --- a/runtime-recomp/src/game/library_ui/shared_page_ui.inl +++ b/runtime-recomp/src/game/library_ui/shared_page_ui.inl @@ -59,14 +59,12 @@ void DrawSharedUiPage(float width, int page, bool live, const PlayPageContext* l DrawSoundPage(width, live); else if (page == kPageControls) DrawControlsPage(width, live); - else if (page == kPageSaveManager) { - DrawPlayToolBack(width); + else if (page == kPageSaveManager) DrawSaveManagerPage(width, live); - } else if (page == kPageAchievements) { - DrawPlayToolBack(width); + else if (page == kPageAchievements) DrawAchievementsPage(width); - } else if (page == dkr::library_ui::LeaderboardsPage) { - DrawLeaderboardsPage(width, entered); + else if (page == dkr::library_ui::LeaderboardsPage) { + DrawLeaderboardsPage(width, entered, live); } else if (page == kPageOnlineMp) DrawOnlinePage(width, !live, live || play->rom_ready); else if (page == kPageModLibrary) @@ -92,6 +90,7 @@ void DrawSharedUiPage(float width, int page, bool live, const PlayPageContext* l ImGui::SetScrollY(ImGui::GetScrollMaxY()); LibrarySurfaceProbe(live, page, width, ImGui::GetCursorPosY() - top); g_launcher_rom = previous; - if (page != kPagePlay) + const bool save_workspace = page == kPageSaveManager && (g_saves_page.scope == 0 || g_saves_page.scope == 2); + if (page != kPagePlay && !save_workspace) ImGui::Dummy({0.F, 54.F}); } diff --git a/runtime-recomp/src/game/library_ui/speedrunning_options.inl b/runtime-recomp/src/game/library_ui/speedrunning_options.inl new file mode 100644 index 00000000..b8368759 --- /dev/null +++ b/runtime-recomp/src/game/library_ui/speedrunning_options.inl @@ -0,0 +1,335 @@ +namespace speed = dkr::runtime::speedrunning; +using RunOption = speed::Option; + +int RunPreference(RunOption key) { + return speed::options.get(key); +} + +std::string RunClock(std::int64_t ticks) { + auto time = LeaderboardTime(ticks); + if (RunPreference(RunOption::Precision) == 1) + time.pop_back(); + return time; +} + +struct RunCorner { + ImVec2 position, pivot; +}; + +RunCorner RunOverlayCorner(const ImGuiViewport& view, int corner) { + const auto inset = std::array{12.F, 22.F, 36.F}[RunPreference(RunOption::Inset)]; + const bool right = corner % 2, bottom = corner >= 2; + return {{view.WorkPos.x + (right ? view.WorkSize.x - inset : inset), + view.WorkPos.y + (bottom ? view.WorkSize.y - inset : inset + 24.F)}, + {float(right), float(bottom)}}; +} + +void SetRunPreference(RunOption key, int value) { + speed::options.set(key, value); + SaveSettings(); +} + +ImTextureID RunPreviewTexture() { +#if DKR_RUNTIME_HAS_RT64 + struct PreviewPixels { + int width = 0, height = 0; + std::unique_ptr rgba{nullptr, stbi_image_free}; + }; + static const auto pixels = [] { + PreviewPixels image; + image.rgba.reset(stbi_load_from_memory(reinterpret_cast(SpeedrunningHudPreview), + static_cast(SpeedrunningHudPreview_size), &image.width, + &image.height, nullptr, STBI_rgb_alpha)); + return image; + }(); + if (!pixels.rgba) + return {}; + if (!g_mod_store_renderer) + return reinterpret_cast( + dkr::store::overlay::image( + "speedrunning-hud-preview", pixels.width, pixels.height, + std::span(pixels.rgba.get(), std::size_t(pixels.width) * pixels.height * STBI_rgb_alpha)) + .id); + if (!g_speedrunning_preview_texture) { + auto* texture = SDL_CreateTexture(g_mod_store_renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, + pixels.width, pixels.height); + if (texture && SDL_UpdateTexture(texture, nullptr, pixels.rgba.get(), pixels.width * STBI_rgb_alpha) != 0) { + SDL_DestroyTexture(texture); + return {}; + } + if (texture) { + SDL_SetTextureScaleMode(texture, SDL_ScaleModeLinear); + SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); + } + g_speedrunning_preview_texture = texture; + } + return reinterpret_cast(g_speedrunning_preview_texture); +#else + return {}; +#endif +} + +void PaintReplayController(ImDrawList* draw, ImVec2 base, const trial::Progress& state, float scale); + +void DrawRunHudPreview(float width, bool replay) { + const bool splits = RunPreference(RunOption::Splits) && (!replay || RunPreference(RunOption::ReplaySplits)); + const bool inputs = replay && RunPreference(RunOption::ReplayInputs); + const bool contrast = RunPreference(RunOption::Contrast); + const int detail = RunPreference(RunOption::SplitDetail); + const int upcoming = detail == 2 ? 0 : RunPreference(RunOption::Upcoming); + const int comparison = RunPreference(RunOption::Comparison); + OlHeading("HUD Preview", 18.F, kOlCream, width); + const ImVec2 origin = ImGui::GetCursorScreenPos(); + const float height = width * 9.F / 16.F; + const ImVec2 end{origin.x + width, origin.y + height}; + const float scale = std::clamp(width / 530.F, .54F, 1.4F); + auto* draw = ImGui::GetWindowDrawList(); + const auto type = OlRead(14.F * scale); + if (const auto texture = RunPreviewTexture()) + draw->AddImageRounded(texture, origin, end, {0.F, 0.F}, {1.F, 1.F}, IM_COL32_WHITE, 9.F); + else + draw->AddRectFilled(origin, end, IM_COL32(15, 45, 62, 255), 9.F); + draw->AddRect(origin, end, PaddockCol(kOlSoft, 87), 9.F); + draw->PushClipRect(origin, end, true); + const float inset = scale * std::array{6.F, 11.F, 17.F}[RunPreference(RunOption::Inset)]; + const auto card_origin = [&](int corner, float w, float h) { + return ImVec2{corner % 2 ? end.x - inset - w : origin.x + inset, + corner >= 2 ? end.y - inset - h : origin.y + inset}; + }; + if (splits) { + const auto clock = RunClock(replay ? 1036 : 8009); + const std::array comparisons{"PB", "WR", "Best segments", ""}; + const auto pace = + std::string(comparisons[comparison]) + (RunPreference(RunOption::DeltaWords) ? " 0.38 ahead" : " -0.38"); + std::array, 6> lines; + std::size_t rows = 0; + const auto add_line = [&](std::string_view text, unsigned color) { lines[rows++] = {text, color}; }; + add_line(replay ? "REPLAY · LAP 1 / 3" : "LIVE SPLITS", kOlAmber); + add_line(clock, kOlCream); + if (detail != 2) { + add_line(detail ? "Ancient Lake" : "Dino Domain · 2:13", kOlInk); + if (comparison != 3) + add_line(pace, kOlGoText); + if (upcoming) + add_line("Next · Fossil Canyon", kOlSoft); + if (upcoming == 2) + add_line("Then · Jungle Falls", kOlSoft); + } + const auto visible_lines = std::span(lines).first(rows); + const float padding = 7.F * scale; + float desired_width = scale * std::array{155.F, 177.F, 195.F}[RunPreference(RunOption::HudSize)]; + for (const auto& [value, color] : visible_lines) { + const auto measured = + type.font->CalcTextSizeA(type.size, FLT_MAX, 0.F, value.data(), value.data() + value.size()); + desired_width = std::max(desired_width, measured.x + 2.F * padding); + } + const float x = std::min(width - 2.F * inset, desired_width); + const float lh = type.size + 4.F * scale; + const float h = rows * lh + 12.F; + const auto pos = card_origin(RunPreference(RunOption::SplitPosition), x, h); + const int alpha = contrast ? 255 : RunPreference(RunOption::Background) * 255 / 100; + draw->AddRectFilled(pos, {pos.x + x, pos.y + h}, IM_COL32(6, 18, 31, alpha), 7.F); + auto line = ImVec2{pos.x + padding, pos.y + 6.F}; + draw->PushClipRect(pos, {pos.x + x, pos.y + h}, true); + for (const auto& [value, color] : visible_lines) { + draw->AddText(type.font, type.size, line, PaddockCol(color), value.data(), value.data() + value.size()); + line.y += lh; + } + draw->PopClipRect(); + } + if (inputs) { + int corner = RunPreference(RunOption::InputPosition); + if (splits && corner == RunPreference(RunOption::SplitPosition)) + corner ^= 1; + const float input_scale = scale * std::array{.40F, .50F, .60F}[RunPreference(RunOption::InputSize)]; + const ImVec2 size{232.F * input_scale, 140.F * input_scale}; + const auto point = card_origin(corner, size.x, size.y); + const int alpha = contrast ? 255 : 212; + draw->AddRectFilled(point, {point.x + size.x, point.y + size.y}, IM_COL32(6, 18, 31, alpha), 7.F); + const trial::Progress sample{.buttons = 0x8000, .stick_x = 25, .stick_y = 35}; + PaintReplayController(draw, point, sample, input_scale); + } + draw->PopClipRect(); + ImGui::Dummy({width, height}); +} + +void DrawRunOptionPanel(int group, int panel, float width) { + static constexpr std::array headings{ + std::array{"Timer display", "Split comparisons"}, std::array{"HUD layout", "Accessibility"}, + std::array{"Appearance", "Race information"}, std::array{"Replay overlays", "Playback"}, + std::array{"Finish details", "Celebrations"}, std::array{"Run setup", "Replay library"}, + }; + DrawOlCard( + width, OlPanelLook{}, + [&](float inner) { + OlHeading(headings[group][panel], 20.F, kOlCream, inner); + PaddockGap(4.F); + const auto id = [](RunOption key) { return speed::settings[static_cast(key)].key.data(); }; + const auto choice = [&](RunOption key, const char* title, std::initializer_list labels, + bool disabled = false) { + int value = RunPreference(key); + if (SettingsDropdown(id(key), title, &value, labels, inner, disabled)) + SetRunPreference(key, value); + }; + const auto toggle = [&](RunOption key, const char* title, const char* help) { + bool value = RunPreference(key) != 0; + if (OlSwitchRow(id(key), title, help, &value, inner, false)) + SetRunPreference(key, value); + }; + const auto range = [&](RunOption key, const char* title, int minimum) { + int value = RunPreference(key); + if (SettingsRange(id(key), title, &value, minimum, 100, inner, + [](int percent) { return SettingsRangeValue{std::to_string(percent), "%"}; })) + SetRunPreference(key, value); + }; + const std::initializer_list corners{"Top left", "Top right", "Bottom left", "Bottom right"}; + const std::initializer_list sizes{"Small", "Standard", "Large"}; + switch (group) { + case 0: + if (panel == 0) { + toggle(RunOption::Splits, "Show Live Splits", "Show the speedrunning timer and splits."); + const bool hidden = !RunPreference(RunOption::Splits); + choice(RunOption::SplitPosition, "Position", corners, hidden); + choice(RunOption::SplitDetail, "Detail", {"Detailed", "Compact", "Timer only"}, hidden); + choice(RunOption::Precision, "Time precision", {"Milliseconds", "Hundredths"}, hidden); + } else { + const bool timer = !RunPreference(RunOption::Splits) || RunPreference(RunOption::SplitDetail) == 2; + choice(RunOption::Comparison, "Compare against", + {"Personal Best", "World Record", "Best Segments", "Off"}, timer); + choice(RunOption::Upcoming, "Upcoming splits", {"Hide", "Next split", "Next two splits"}, timer); + } + break; + case 1: + if (panel == 0) { + choice(RunOption::HudSize, "Split HUD size", sizes); + choice(RunOption::Inset, "Screen-edge padding", {"Narrow", "Normal", "Wide"}); + range(RunOption::Background, "Background opacity", 55); + } else { + toggle(RunOption::Contrast, "High contrast HUD", "Use an opaque background and brighter text."); + toggle(RunOption::DeltaWords, "Label deltas ahead / behind", + "Use words as well as colour to show pace."); + toggle(RunOption::ReducedMotion, "Reduce overlay animations", + "Show static celebrations and loading indicators."); + } + break; + case 2: + if (panel == 0) { + choice(RunOption::GhostStyle, "Ghost appearance", {"Translucent racer", "Outline marker"}); + range(RunOption::GhostOpacity, "Ghost opacity", 0); + toggle(RunOption::GhostNames, "Show ghost racer names", + "Display the credited Discord name above leaderboard ghosts."); + } else { + choice(RunOption::GhostProximity, "When the ghost is close", {"Keep visible", "Fade out"}); + toggle(RunOption::GhostGap, "Show time gap to ghost", + "Compare your lap crossing with the ghost's."); + toggle(RunOption::GhostMarker, "Ghost marker on minimap", + "Show the ghost's position on the course map."); + } + break; + case 3: + if (panel == 0) { + toggle(RunOption::ReplayInputs, "Show controller inputs", + "Display the recorded N64 controller inputs."); + toggle(RunOption::ReplaySplits, "Show Live Splits in replays", + "Use your Live Splits layout during playback."); + const bool no_controller = !RunPreference(RunOption::ReplayInputs); + choice(RunOption::InputPosition, "Controller position", corners, no_controller); + choice(RunOption::InputSize, "Controller size", sizes, no_controller); + } else { + choice(RunOption::ReplaySpeed, "Starting speed", {"0.5x", "1x", "1.5x", "2x"}); + choice(RunOption::PlaybackControls, "Playback controls", {"Always show", "Auto-hide"}); + choice(RunOption::SeekStep, "Seek step", {"5 seconds", "10 seconds", "30 seconds"}); + toggle(RunOption::StartPaused, "Open replays paused", "Wait for Play after the replay loads."); + toggle(RunOption::LapMarkers, "Show timeline markers", + "Show lap or split markers on the timeline."); + } + break; + case 4: + if (panel == 0) { + toggle(RunOption::LapDelta, "Show lap time comparisons", + "Show your lap time and gap to the selected reference."); + toggle(RunOption::FinishSummary, "Show finish time card", "Show your time when the run ends."); + } else { + choice(RunOption::Celebration, "Podium celebrations", {"Full screen", "Compact", "Off"}); + choice(RunOption::CelebrationScope, "Celebrate", + {"Top-three pace", "Record pace only", "Personal bests and podiums"}, + RunPreference(RunOption::Celebration) == 2); + range(RunOption::CueVolume, "Speedrunning cue volume", 0); + } + break; + case 5: + if (panel == 0) { + choice(RunOption::ReturnTo, "After a run, open", {"Last Run", "Replays"}); + toggle(RunOption::RememberSetup, "Remember last run setup", + "Keep your last course, vehicle, racer, and challenge."); + toggle(RunOption::ConfirmRestart, "Confirm before restarting", + "Ask before replacing the current attempt."); + } else { + choice(RunOption::Retention, "Keep new local replays", + {"All completed runs", "Personal bests and pending posts"}); + choice(RunOption::ReplaySort, "Default replay order", + {"Newest first", "Personal bests first", "Track name"}); + toggle(RunOption::PostPrompt, "Offer to post eligible personal bests", + "Show the posting action in the Last Run card."); + } + break; + } + }, + 16.F); +} + +void DrawSpeedrunningOptions(float width) { + static int group = 0; + static const std::vector groups{"Live Splits", "HUD & Accessibility", "Ghosts", + "Replay Theatre", "Finish & Cues", "Run & Library"}; + group = StoreTabLine(groups, group, width, "speedrunning-options", true); + PaddockGap(8.F); + + constexpr float gap = 16.F; + constexpr float minimum_pair = 640.F; + const auto draw_row = [&](float row_width, std::span columns, auto&& draw_column) { + const auto at = ImGui::GetCursorScreenPos(); + float left = at.x, bottom = at.y; + for (std::size_t i = 0; i < columns.size(); ++i) { + ImGui::SetCursorScreenPos({left, at.y}); + ImGui::BeginGroup(); + draw_column(i, columns[i]); + ImGui::EndGroup(); + bottom = std::max(bottom, ImGui::GetItemRectMax().y); + left += columns[i] + gap; + } + ImGui::SetCursorScreenPos(at); + ImGui::Dummy({row_width, bottom - at.y}); + }; + const auto draw_settings = [&](float settings_width) { + if (settings_width >= minimum_pair) { + const float column = (settings_width - gap) * .5F; + draw_row(settings_width, std::array{column, column}, + [&](std::size_t panel, float size) { DrawRunOptionPanel(group, static_cast(panel), size); }); + } else { + DrawRunOptionPanel(group, 0, settings_width); + PaddockGap(gap); + DrawRunOptionPanel(group, 1, settings_width); + } + }; + const auto draw_preview = [&](float preview_width) { + DrawOlCard(preview_width, OlPanelLook{}, [&](float inner) { DrawRunHudPreview(inner, group == 3); }, 16.F); + }; + + const bool preview = group == 0 || group == 1 || group == 3; + if (preview && width >= 740.F) { + const float preview_width = (width - gap) * .46F; + draw_row(width, std::array{width - gap - preview_width, preview_width}, [&](std::size_t column, float size) { + if (column == 0) + draw_settings(size); + else + draw_preview(size); + }); + } else { + draw_settings(width); + if (preview) { + PaddockGap(gap); + draw_preview(width); + } + } +} diff --git a/runtime-recomp/src/game/library_ui/speedrunning_welcome.inl b/runtime-recomp/src/game/library_ui/speedrunning_welcome.inl new file mode 100644 index 00000000..8b032fae --- /dev/null +++ b/runtime-recomp/src/game/library_ui/speedrunning_welcome.inl @@ -0,0 +1,92 @@ +void DrawSpeedrunningWelcome(bool entered, bool signed_in, bool staff, const dkr::store::Json* catalogue) { + constexpr const char* popup = "Welcome to Speedrunning!"; + static std::filesystem::path acknowledged; + const auto marker = g_config_directory / "speedrunning-welcome-seen"; + std::error_code ec; + if (entered && acknowledged != marker && !std::filesystem::is_regular_file(marker, ec)) + ImGui::OpenPopup(popup); + if (!ImGui::IsPopupOpen(popup)) + return; + + const auto viewport = ImGui::GetMainViewport()->WorkSize; + const float modal_width = std::min(790.F, viewport.x - 38.F); + ImGui::SetNextWindowSize({modal_width, 0.F}, ImGuiCond_Always); + constexpr ImGuiWindowFlags flags = ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; + if (!BeginPaddedModal(popup, flags)) + return; + + const float width = ImGui::GetContentRegionAvail().x; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {10.F, 5.F}); + ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 0)); + ImGui::BeginChild("Speedrunning guide", {width, std::min(405.F, viewport.y * .62F)}, false); + const float body = ImGui::GetContentRegionAvail().x; + OlParagraph("Fancy getting a time on the leaderboards? Use the tabs across the top to have a look around. " + "Here's how to get your first run posted.", 16.F, kOlInk, body); + PaddockGap(9.F); + + const bool columns = body > 630.F; + const float column = columns ? (body - 22.F) / 2.F : body; + ImGui::BeginGroup(); + OlParagraph("Where to find things", 18.F, kOlAmber, column, true, 1.25F); + PaddockGap(3.F); + for (const auto* line : { + "Top Players — See who's leading overall and how the points work.", + "Vanilla Tracks — Check the times for the original tracks.", + "Custom Tracks — Check the times for tracks made by the community.", + "Full Game — See runs for categories like Any%, 100% and All Trophy Races.", + "Runs — Start a run under Run. My Submitted Runs shows how your posts are getting on.", + "Replays (under Runs) — Watch your saved runs, race a ghost or post an eligible time."}) { + OlParagraph(line, 15.F, kOlSoft, column, false, 1.3F); + PaddockGap(2.F); + } + if (staff) + OlParagraph("Review Runs — This is where mods and admins can watch and review verified runs.", + 15.F, kOlSoft, column, false, 1.3F); + ImGui::EndGroup(); + + if (columns) + ImGui::SameLine(0.F, 22.F); + else + PaddockGap(8.F); + ImGui::BeginGroup(); + OlParagraph("Posting your first run", 18.F, kOlAmber, column, true, 1.25F); + PaddockGap(3.F); + for (const auto* step : { + "1. Sign in with Discord before you start a run you want to post. Once you're signed in, come back to the Launcher.", + "2. Go to Runs > Run, pick a track or a Full Game category and hit Start Run.", + "3. When you finish, hit Post to Leaderboard if it's there. You can also do this from Runs > Replays. " + "Check Runs > My Submitted Runs to see the status."}) { + OlParagraph(step, 15.F, kOlSoft, column, false, 1.3F); + PaddockGap(3.F); + } + ImGui::EndGroup(); + PaddockGap(10.F); + OlParagraph("Just having a go? You can race without signing in. Local runs stay on your device.", + 15.F, kOlInk, body); + if (catalogue && catalogue->value("canClaimLocal", false)) + OlParagraph("You can link an eligible local run to your Discord account from Runs > Replays.", 15.F, kOlSoft, body); + ImGui::EndChild(); + ImGui::PopStyleColor(); + ImGui::PopStyleVar(); + + PaddockGap(10.F); + const bool dismiss = OlButton("Got it", OlTone::Go) || ImGui::IsKeyPressed(ImGuiKey_Escape, false) || + ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false); + bool login = false; + if (!signed_in) { + ImGui::SameLine(); + login = OlButton("Sign in with Discord"); + } + if (dismiss || login) { + acknowledged = marker; + try { + dkr::updates::durable_write(marker, "seen\n"); + } catch (const std::exception&) { + // Keep the acknowledgement for this session if the profile is read-only. + } + if (login) + dkr::store::service().login(); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} diff --git a/runtime-recomp/src/game/library_ui/submitted_runs.inl b/runtime-recomp/src/game/library_ui/submitted_runs.inl new file mode 100644 index 00000000..b3acd800 --- /dev/null +++ b/runtime-recomp/src/game/library_ui/submitted_runs.inl @@ -0,0 +1,195 @@ +struct SubmissionQuota { + std::int64_t remaining; + std::int64_t limit; + std::int64_t next_slot; +}; + +std::optional ReadSubmissionQuota(const dkr::store::Json& listing) { + const auto quota = listing.find("submissionQuota"); + if (quota == listing.end() || !quota->is_object()) + return {}; + const auto limit = LeaderboardNumber(*quota, "maxRuns"); + const auto observed = RecordUnix(*quota, "observedAt"); + const auto releases = quota->find("releasesAt"); + if (limit <= 0 || observed <= 0 || releases == quota->end() || !releases->is_array() || + releases->size() > static_cast(limit)) + return {}; + const auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - g_ranked_runs_received).count(); + const auto now = observed + elapsed; + SubmissionQuota slots{limit, limit, 0}; + for (const auto& release : *releases) { + if (!release.is_number_integer()) + continue; + const auto stamp = release.get(); + if (stamp <= now) + continue; + --slots.remaining; + if (!slots.next_slot || stamp < slots.next_slot) + slots.next_slot = stamp; + } + return slots; +} + +void DrawSubmissionQuota(float width, const SubmissionQuota& quota) { + const auto time = quota.next_slot > 0 + ? LocalReplayDate(static_cast(quota.next_slot), "%d %b, %H:%M:%S") + : std::string{}; + const bool has_next_slot = !time.empty(); + constexpr float gap = 20.F; + const float meter_width = std::min(width, 294.F); + const bool inline_next = has_next_slot && width >= meter_width + gap + 215.F; + ImGui::BeginGroup(); + OlHeading(std::to_string(quota.remaining) + " / " + std::to_string(quota.limit), 27.F, kOlCream, + meter_width, 1.2F); + OlParagraph("Submissions left", 14.F, kOlSoft, meter_width, true, 1.25F); + const auto meter = ImGui::GetCursorScreenPos(); + auto* draw = ImGui::GetWindowDrawList(); + const float fraction = static_cast(quota.remaining) / static_cast(quota.limit); + PaddockFill(draw, meter, {meter.x + meter_width, meter.y + 6.F}, PaddockRound(3.F), PaddockCol(0x254658U)); + if (quota.remaining > 0) + PaddockFill(draw, meter, {meter.x + meter_width * fraction, meter.y + 6.F}, PaddockRound(3.F), PaddockCol(kOlGo)); + ImGui::Dummy({meter_width, 6.F}); + ImGui::EndGroup(); + if (has_next_slot) { + if (inline_next) + ImGui::SameLine(0.F, gap); + const float next_width = inline_next ? width - meter_width - gap : width; + ImGui::BeginGroup(); + OlParagraph("Next slot opens", 14.F, kOlSoft, next_width, true, 1.2F); + OlParagraph(time + " (local time)", 16.F, kOlInk, next_width, true, 1.2F); + ImGui::EndGroup(); + } +} + +struct SubmittedRunStatus { + std::string_view id; + const char* label; + PaddockTone tone; +}; + +constexpr std::array kSubmittedRunStatuses{ + SubmittedRunStatus{"uploading", "Upload incomplete", PaddockTone::Warning}, + SubmittedRunStatus{"queued", "Waiting for verification", PaddockTone::Neutral}, + SubmittedRunStatus{"verified", "Awaiting review", PaddockTone::Warning}, + SubmittedRunStatus{"published", "Published", PaddockTone::On}, + SubmittedRunStatus{"rejected", "Rejected", PaddockTone::Warning}, +}; + +void DrawSubmittedRun(float width, const dkr::store::Json& run, float status_width, float watch_width) { + const auto id = StoreText(run, "id", 96); + if (id.empty()) + return; + + const auto state = StoreText(run, "state", 24); + const auto badge = std::ranges::find(kSubmittedRunStatuses, state, &SubmittedRunStatus::id); + const auto label = dkr::localisation::source(badge == kSubmittedRunStatuses.end() ? "Status unavailable" : badge->label); + const auto tone = badge == kSubmittedRunStatuses.end() ? PaddockTone::Neutral : badge->tone; + const auto verified_ticks = LeaderboardNumber(run, "ticks"); + const auto ticks = verified_ticks ? verified_ticks : LeaderboardNumber(run, "claimedTicks"); + const auto time = ticks > 0 ? LeaderboardTime(ticks) : std::string("—"); + const auto vehicle = StoreText(run, "vehicle", 24); + std::string metadata = vehicle == "mixed" ? std::string(dkr::localisation::source("Full Game")) + : LeaderboardVehicle(vehicle); + const auto submitted_at = RecordUnix(run, "createdAt"); + const auto date = submitted_at > 0 ? LocalReplayDate(static_cast(submitted_at), "%d %b %Y") : ""; + for (const auto& part : {date, + run.value("linkedLocal", false) ? std::string(dkr::localisation::source("Linked local run")) + : std::string{}}) { + if (!part.empty()) { + if (!metadata.empty()) + metadata += " · "; + metadata += part; + } + } + const auto title = StoreText(run, "title", 120); + OlPanelLook look; + look.ring_width = 1.F; + ImGui::PushID(id.c_str()); + DrawOlCard(width, look, [&](float inner) { + constexpr float gap = 10.F; + const float time_width = std::min(inner, std::max(104.F, PaddockMeasure(OlSignType(19.F, 1.25F), time) + 4.F)); + const float action_width = time_width + status_width + watch_width + 2.F * gap; + const bool inline_actions = inner >= action_width + gap + 216.F; + const float title_width = inline_actions ? inner - action_width - gap : inner; + ImGui::BeginGroup(); + OlHeading(title, 20.F, kOlCream, title_width, 1.25F); + if (!metadata.empty()) + OlParagraph(metadata, 14.F, kOlSoft, title_width, false, 1.2F); + ImGui::EndGroup(); + if (inline_actions) + ImGui::SameLine(0.F, gap); + ImGui::BeginGroup(); + OlHeading(time, 19.F, kOlInk, time_width, 1.25F); + if (!verified_ticks && ticks > 0) + OlParagraph("Recorded time", 13.F, kOlSoft, time_width, false, 1.2F); + ImGui::EndGroup(); + + const auto badge_label = PaddockEllipsize(PaddockReading(11.F, true, 1.5F), label, std::max(1.F, inner - 27.F)); + const auto size = PaddockBadgeSize(badge_label); + const float badge_width = size.x; + const bool inline_badge = time_width + gap + (inline_actions ? status_width : badge_width) <= inner; + if (inline_badge) + ImGui::SameLine(0.F, gap); + const auto origin = ImGui::GetCursorScreenPos(); + PaddockBadge(ImGui::GetWindowDrawList(), {origin.x, origin.y + (34.F - size.y) * .5F}, badge_label, tone); + ImGui::Dummy({inline_actions ? status_width : std::min(badge_width, inner), 34.F}); + + if (state != "uploading") { + const float used = (inline_badge ? time_width + gap : 0.F) + + (inline_actions ? status_width : badge_width); + if (used + gap + watch_width <= inner) + ImGui::SameLine(0.F, gap); + const OlDisabled launch(DialogJobRunning() || !CanLaunchLeaderboardReplay()); + if (OlButton("Watch replay", OlTone::Plain, std::min(watch_width, inner), nullptr, 34.F)) + WatchLeaderboardReplay(id, true); + StoreControlFocus(); + } + for (const auto* field : {"notes", "reason"}) + if (const auto value = StoreText(run, field, 600); !value.empty()) + OlParagraph(value, 14.F, kOlSoft, inner, false, 1.25F); + }, 12.F); + ImGui::PopID(); +} + +void DrawSubmittedRuns(float width) { + const auto owner = RankedRunsOwner(); + const auto rows = g_ranked_runs.find("runs"); + const bool loaded = !owner.empty() && g_ranked_runs_owner == owner && !g_ranked_runs_review && + rows != g_ranked_runs.end() && rows->is_array(); + const auto quota = loaded ? ReadSubmissionQuota(g_ranked_runs) : std::nullopt; + + const auto spacing = ImGui::GetStyle().ItemSpacing; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {spacing.x, 7.F}); + DrawOlCard(width, OlPanelLook{}, [&](float inner) { + OlHeading("My Submitted Runs", 24.F, kOlCream, inner); + if (owner.empty()) { + OlParagraph("Sign in with Discord to see your submitted runs.", 15.F, kOlSoft, inner); + const OlDisabled busy(DialogJobRunning()); + if (OlButton("Sign in with Discord", OlTone::Go)) + dkr::store::service().login(); + StoreControlFocus(); + return; + } + if (quota) + DrawSubmissionQuota(inner, *quota); + if (loaded) { + OlParagraph("The leaderboard host prepares videos for review. You can close DKR-R once your upload finishes.", + 14.F, kOlSoft, inner, false, 1.25F); + if (rows->empty()) + OlParagraph("You haven't submitted a run yet.", 15.F, kOlInk, inner); + } else { + OlParagraph(DialogJobRunning() ? "Loading submitted runs..." : "Use Refresh to check for runs.", + 15.F, kOlSoft, inner); + } + }, 14.F); + if (loaded && !rows->empty()) { + float status_width = PaddockBadgeSize(dkr::localisation::source("Status unavailable")).x; + for (const auto& status : kSubmittedRunStatuses) + status_width = std::max(status_width, PaddockBadgeSize(dkr::localisation::source(status.label)).x); + const float watch_width = OlButtonWidth("Watch replay"); + for (const auto& run : *rows) + DrawSubmittedRun(width, run, status_width, watch_width); + } + ImGui::PopStyleVar(); +} diff --git a/runtime-recomp/src/game/lobby_controls.inl b/runtime-recomp/src/game/lobby_controls.inl index 13e85900..680f685e 100644 --- a/runtime-recomp/src/game/lobby_controls.inl +++ b/runtime-recomp/src/game/lobby_controls.inl @@ -227,7 +227,7 @@ void DrawOlPartyStart(float width, const OnlineFrame& frame) { if (host || watcher) { ImGui::SetCursorScreenPos(pair ? ImVec2{at.x + button + 10.F, at.y} : ImVec2{at.x, at.y + 62.F}); const bool disabled = OlPartyChanging(frame) || (!host && watcher && !live); - const bool waiting_ready = g_ol_party.save_ready && + const bool waiting_ready = !SharedSaveBusy() && g_ol_party.save_ready && std::count_if(frame.view.room.players.begin(), frame.view.room.players.end(), [](const auto& p) { return p.occupied; }) >= 2 && std::none_of(frame.view.room.players.begin(), frame.view.room.players.end(), diff --git a/runtime-recomp/src/game/localisation/imgui_ui.hpp b/runtime-recomp/src/game/localisation/imgui_ui.hpp index 0e5185cb..2a53523b 100644 --- a/runtime-recomp/src/game/localisation/imgui_ui.hpp +++ b/runtime-recomp/src/game/localisation/imgui_ui.hpp @@ -1,7 +1,9 @@ #pragma once #include "service.hpp" +#include "../dialog_style.hpp" #include "imgui.h" #include "imgui_internal.h" +#include #include #include #include @@ -66,6 +68,7 @@ template void UiTextColored(const ImVec4& colour, T&& f } } template void UiSetTooltip(T&& format, Args&&... args) { + const dkr::runtime::ui::ScopedDialogStyle style({12.0F, 8.0F}, 10.0F); if constexpr (sizeof...(Args) > 0) { SetTooltip(LocalisedUi::format_copy(std::forward(format)).data(), std::forward(args)...); } else { @@ -147,6 +150,12 @@ bool UiSelectable(T&& label, bool* selected, ImGuiSelectableFlags flags = 0, con return Selectable(shown.c_str(), selected, flags, size); } template bool UiBeginPopupModal(T&& label, bool* open = nullptr, ImGuiWindowFlags flags = 0) { + // Custom dialogs supply their chrome before calling BeginPopupModal. + std::optional dialog_style; + const auto& current = GetStyle(); + if ((current.WindowRounding <= 0.0F || current.WindowPadding.x <= 0.0F || current.WindowPadding.y <= 0.0F) && + IsPopupOpen(label)) + dialog_style.emplace(); // Popup identity must match existing OpenPopup()/IsPopupOpen() calls. const bool visible = BeginPopupModal(label, open, flags); if constexpr (LocalisedUi::caption_array) { diff --git a/runtime-recomp/src/game/localisation/literal_ui.inl b/runtime-recomp/src/game/localisation/literal_ui.inl index 665555d8..af459168 100644 --- a/runtime-recomp/src/game/localisation/literal_ui.inl +++ b/runtime-recomp/src/game/localisation/literal_ui.inl @@ -56,14 +56,14 @@ template bool UiPaddockTextLink(T&& label) { const auto shown = LocalisedUi::widget(std::forward(label)); return PaddockTextLink(shown.c_str()); } -template float UiPaddockSectionTabWidth(T&& label) { +template float UiPaddockSectionTabWidth(T&& label, bool compact = false) { // Section tabs are owned registry captions, including counted headings. const auto shown = dkr::localisation::label(std::string_view(label)); - return PaddockSectionTabWidth(shown.c_str()); + return PaddockSectionTabWidth(shown.c_str(), compact); } -template bool UiPaddockSectionTab(T&& label, bool open, float width = 0.F) { +template bool UiPaddockSectionTab(T&& label, bool open, float width = 0.F, bool compact = false) { const auto shown = dkr::localisation::label(std::string_view(label)); - return PaddockSectionTab(shown.c_str(), open, width); + return PaddockSectionTab(shown.c_str(), open, width, compact); } template bool UiPaddockCheckbox(const char* id, T&& label, bool* value, float width, diff --git a/runtime-recomp/src/game/mod_library/website/assets/adventure-catalogue.js b/runtime-recomp/src/game/mod_library/website/assets/adventure-catalogue.js new file mode 100644 index 00000000..e1ea38cc --- /dev/null +++ b/runtime-recomp/src/game/mod_library/website/assets/adventure-catalogue.js @@ -0,0 +1,15 @@ +// Stage names and order from the community LiveSplit route templates. +export const adventureCatalogue = [ + {"id": "any-percent", "title": "Any%", "summary": "Beat the final Wizpig race.", "stages": ["Enter Wizpig 1", "Wizpig 1", "Dino 2", "Enter FFL", "T.T. Stomp", "Wizpig 2"]}, + {"id": "100-percent", "title": "100%", "summary": "Complete the Adventure checklist and beat Wizpig.", "stages": ["Overworld", "Fire Mountain", "Dino 2", "Snowflake 1", "Sherbet 1", "Darkwater Beach", "Sherbet Trophy", "Sherbet 2", "Icicle Pyramid", "Snow Trophy", "Snowflake 2", "Dino Trophy", "Dragon Trophy", "Dragon 1", "Smokey Castle", "Dragon 2", "Wizpig 1", "FFL", "Wizpig 2"]}, + {"id": "any-percent-glitchless", "title": "Any% Glitchless", "summary": "Complete the regular Adventure route.", "stages": ["Overworld", "Dino 1", "Fire Mountain", "Dino 2", "Dino Trophy", "Car Challenge", "Snow 1", "Icicle Pyramid", "Snow 2", "Snow Trophy", "Hover Challenge", "Sherbet 1", "Darkwater Beach", "Sherbet 2", "Sherbet Trophy", "Plane Challenge", "Dragon 1", "Smokey Castle", "Dragon 2", "Dragon Trophy", "Wizpig 1", "Future Fun Land 1", "Future Fun Land 2", "Wizpig 2"]}, + {"id": "all-bosses", "title": "All Bosses", "summary": "Win six boss rematches from a completed Adventure save.", "stages": ["Tricky", "Bluey", "Bubbler", "Smokey", "Wizpig 1", "Wizpig 2"]}, + {"id": "all-minigames", "title": "All Minigames", "summary": "Win all four minigames in Tracks Mode.", "stages": ["Darkwater Beach", "Fire Mountain", "Icicle Pyramid", "Smokey Castle"]}, + {"id": "all-trophy-races", "title": "All Trophy Races", "summary": "Finish all five Trophy sets in Tracks Mode.", "stages": ["Ancient Lake", "Fossil Canyon", "Jungle Falls", "Hot Top Volcano", "Whale Bay", "Pirate Lagoon", "Crescent Island", "Treasure Caves", "Everfrost Peak", "Walrus Cove", "Snowball Valley", "Frosty Village", "Boulder Canyon", "Greenwood Village", "Windmill Plains", "Haunted Woods", "Spacedust Alley", "Darkmoon Caverns", "Star City", "Spaceport Alpha"]}, + {"id": "all-trophy-races-dino-first", "title": "All Trophy Races – Dino Domain First", "summary": "Race all five Trophy sets, beginning in Dino Domain.", "stages": ["Ancient Lake", "Fossil Canyon", "Jungle Falls", "Hot Top Volcano", "Whale Bay", "Pirate Lagoon", "Crescent Island", "Treasure Caves", "Everfrost Peak", "Walrus Cove", "Snowball Valley", "Frosty Village", "Boulder Canyon", "Greenwood Village", "Windmill Plains", "Haunted Woods", "Spacedust Alley", "Darkmoon Caverns", "Star City", "Spaceport Alpha"]}, + {"id": "all-trophy-races-ffl-first", "title": "All Trophy Races – Future Fun Land First", "summary": "Race all five Trophy sets, beginning in Future Fun Land.", "stages": ["Spacedust Alley", "Darkmoon Caverns", "Star City", "Spaceport Alpha", "Boulder Canyon", "Greenwood Village", "Windmill Plains", "Haunted Woods", "Everfrost Peak", "Walrus Cove", "Snowball Valley", "Frosty Village", "Whale Bay", "Pirate Lagoon", "Crescent Island", "Treasure Caves", "Ancient Lake", "Fossil Canyon", "Jungle Falls", "Hot Top Volcano"]}, + {"id": "car-percent", "title": "Car%", "summary": "Complete the car course route.", "stages": ["Greenwood Village", "Walrus Cove", "Everfrost Peak", "Spacedust Alley", "Darkmoon Caverns", "Star City", "Spaceport Alpha", "Haunted Woods", "Windmill Plains", "Snowball Valley", "Frosty Village", "Treasure Caves", "Crescent Island", "Ancient Lake", "Fossil Canyon", "Jungle Falls"]}, + {"id": "hover-percent", "title": "Hover%", "summary": "Complete the hovercraft course route.", "stages": ["Everfrost Peak", "Boulder Canyon", "Spacedust Alley", "Darkmoon Caverns", "Greenwood Village", "Windmill Plains", "Star City", "Spaceport Alpha", "Haunted Woods", "Frosty Village", "Snowball Valley", "Walrus Cove", "Ancient Lake", "Fossil Canyon", "Jungle Falls", "Hot Top Volcano", "Crescent Island", "Treasure Caves", "Whale Bay", "Pirate Lagoon"]}, + {"id": "plane-percent", "title": "Plane%", "summary": "Complete the plane course route.", "stages": ["Windmill Plains", "Spaceport Alpha", "Star City", "Spacedust Alley", "Everfrost Peak", "Frosty Village", "Treasure Caves", "Hot Top Volcano", "Jungle Falls", "Fossil Canyon", "Ancient Lake"]}, + {"id": "tt-amulet-no-wrong-warp", "title": "T.T. Amulet – No Wrong Warp", "summary": "Earn the four T.T. Amulet pieces through normal progression.", "stages": ["Overworld", "Fire Mountain", "Hot Top Volcano", "Car Challenge", "Frosty Village", "Snowball Valley", "Icicle Pyramid", "Walrus Cove", "Everfrost Peak", "Hover Challenge", "Pirate Lagoon", "Crescent Island", "Whale Bay", "Darkwater Beach", "Treasure Caves", "Plane Challenge", "Windmill Planes", "Smokey Castle"]}, +]; diff --git a/runtime-recomp/src/game/mod_library/website/assets/api-store.js b/runtime-recomp/src/game/mod_library/website/assets/api-store.js index 95caea78..90fce945 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/api-store.js +++ b/runtime-recomp/src/game/mod_library/website/assets/api-store.js @@ -14,7 +14,8 @@ let apiBase = ''; try { const configured = new URL((root.DKR_CONFIG || {}).apiBase); - if (configured.protocol !== 'https:' || configured.username || configured.password || configured.search || configured.hash) throw new Error(); + const loopback = configured.origin === root.location.origin && ['127.0.0.1','localhost'].includes(configured.hostname); + if ((!loopback && configured.protocol !== 'https:') || configured.username || configured.password || configured.search || configured.hash) throw new Error(); apiBase = configured.href.replace(/\/+$/, ''); D.configured = true; } catch (_) { D.error = 'The website library service address is missing or invalid. Reload this page or contact the site owner.'; } function notify() { listeners.forEach(function (callback) { try { callback(D); } catch (_) { /* UI failures do not affect store state. */ } }); } @@ -91,6 +92,16 @@ D.visibleReviews = function (id) { return (publicReviews.get(id) || []).slice(); }; D.ownReview = function (id) { return self ? ownReviews.find(function (review) { return review.itemId === id; }) || null : null; }; D.onChange = function (callback) { if (typeof callback !== 'function') throw new TypeError('Expected a listener.'); listeners.add(callback); return function () { listeners.delete(callback); }; }; + async function notificationRequest(path,body) { + const epoch = generation; + await ensureAuth(); + const token = auth && auth.getToken(); + if (invalidated(epoch)) throw staleError(); + if (!token || !self) throw new Error('Sign in to see your notifications.'); + return requestJSON('/v1/notifications' + path,token,body,epoch); + } + D.getNotifications = cursor => notificationRequest(cursor ? '?before=' + encodeURIComponent(cursor) : ''); + D.markNotifications = (operation,body) => notificationRequest('/' + operation,body); D.refresh = async function () { // Start loading synchronously: a login listener can immediately wait for // this refresh, even while its session-validation promise is pending. diff --git a/runtime-recomp/src/game/mod_library/website/assets/app.js b/runtime-recomp/src/game/mod_library/website/assets/app.js index 82c8f315..8b077150 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/app.js +++ b/runtime-recomp/src/game/mod_library/website/assets/app.js @@ -354,7 +354,7 @@ function header() { const u=user(); - return ''; + return ''; } function footer() { return 'DKR-R Mod Library · Community creations, one starting grid.
DKR-R project'+textButton('help','Install help')+textButton('staff-login','Moderator login')+'Privacy
'; } function modcard(item) { @@ -473,6 +473,14 @@ } const Racing = window.DKRRacingUI.create({root, config, Auth, view:()=>s.view, user, isStaff, esc, icon, button, pagehead, requireSignedIn, go, renderIcons}); + const Notifications = window.DKRNotificationsUI.create({ + root, user, esc, icon, button, renderIcons, + read:cursor=>D.getNotifications(cursor), + mark:(operation,body)=>D.markNotifications(operation,body), + signIn:()=>go('login',{loginMode:'player',returnTo:{view:s.view}}), + navigate:event=>event.type === 'run' ? Racing.openRunList(event.staff ? 'review' : 'mine',event.itemId) : + go(event.staff ? 'review-request' : 'request-status',{requestId:event.itemId}), + }); const Community = window.DKRCommunityUI.create({root,state:()=>s,store:()=>D,esc,icon,button,banner,empty,categories:C.categories,category,image,dateText,user,isStaff,render,go,flash,perform}); @@ -758,7 +766,7 @@ } } if(Auth&&Auth.signoutPending&&!Auth.completionWindow){main.insertAdjacentHTML('afterbegin',banner(esc(Auth.signoutWarning||'Sign-out could not be confirmed. Reconnect and finish signing out to remove remembered access from this device.')+'
'+button('retry-signout','Finish signing out','quiet')+'
','error'));} - renderIcons();applyBusy();if(focus)focusPage();Community.mounted();Racing.mounted(); + renderIcons();applyBusy();if(focus)focusPage();Community.mounted();Racing.mounted();Notifications.mounted(); } async function go(view,data,refresh) { if(view!==s.view){captureListingForm();if(Uploads&&Uploads.state.running&&uploadMatchesContext(uploadTarget,false))Uploads.pause();s.uploadOpenKind='';s.uploadJobsShown=false;s.uploadError='';s.uploadConnection='';} @@ -811,6 +819,7 @@ try { if(await workflowAction(action,id,target))return; if(await Racing.action(action,id,target))return; + if(await Notifications.action(action,id))return; if(action==='store'){await go('store');return;} if(action==='category'){s.category=id;s.tag='all';s.limit=6;s.view='store';clearFlash();render();restoreFocus(action,id);return;} if(action==='tag'){s.tag=id;s.limit=6;clearFlash();render();restoreFocus(action,id);return;} diff --git a/runtime-recomp/src/game/mod_library/website/assets/notifications-ui.js b/runtime-recomp/src/game/mod_library/website/assets/notifications-ui.js new file mode 100644 index 00000000..b47e0704 --- /dev/null +++ b/runtime-recomp/src/game/mod_library/website/assets/notifications-ui.js @@ -0,0 +1,162 @@ +(function () { + 'use strict'; + + const modStatuses = { + pending:'Waiting for review',review:'Under review',changes:'Changes requested', + approved:'Approved for publication',rejected:'Rejected',published:'Published', + }; + const runStatuses = { + queued:'Waiting for verification',verified:'Ready for staff review',rejected:'Rejected',published:'Published', + }; + const timestamp = new Intl.DateTimeFormat(undefined,{dateStyle:'medium',timeStyle:'short'}); + + window.DKRNotificationsUI = { create({ root, user, esc, icon, button, read, mark, navigate, signIn, renderIcons }) { + let inbox = null; + let identity = ''; + let opened = false; + let busy = false; + let errorMessage = ''; + let generation = 0; + let updatedAt = 0; + let timer; + + function syncIdentity() { + const account = user(); + const key = account ? account.id + ':' + account.role : ''; + if (key !== identity) { + identity = key; + ++generation; + inbox = null; + opened = busy = false; + errorMessage = ''; + updatedAt = 0; + } + } + + function markup() { + syncIdentity(); + const unread = inbox?.unread || 0; + const label = 'Notifications' + (unread ? ', ' + unread + ' unread' : ''); + return '' + (opened ? panel() : ''); + } + + function panel() { + const entries = inbox?.events || []; + return '
' + + '

Notifications

' + + (inbox?.through && !busy ? button('notifications-read-all','Mark all as read','quiet small') : '') + '
' + + (errorMessage ? '

' + esc(errorMessage) + '

' : '') + + (!inbox && busy ? '

Loading notifications…

' : '') + + (entries.length ? '
    ' + entries.map(event => { + const status = event.staff ? (event.type === 'mod' ? 'Mod ready for review' : 'Run ready for review') : + (event.type === 'mod' ? modStatuses[event.status] : runStatuses[event.status]) || event.status; + const date = new Date(event.createdAt * 1000); + return '
  • '; + }).join('') + '
' : (inbox ? '

You have no notifications.

' : '')) + + (inbox?.nextCursor && !busy ? button('notifications-more','More notifications','quiet small') : '') + '
'; + } + + function render() { + const slot = root.querySelector('[data-notification-slot]'); + if (!slot) return; + const focused = slot.contains(document.activeElement) ? document.activeElement : null; + const action = focused?.dataset.action; + const id = focused?.dataset.id; + slot.innerHTML = markup(); + renderIcons(); + if (action) [...slot.querySelectorAll('[data-action]')].find(item => item.dataset.action === action && + item.dataset.id === id)?.focus({preventScroll:true}); + } + + async function update(operation, append = false) { + syncIdentity(); + if (!identity || busy) return false; + const token = ++generation; + busy = true; + errorMessage = ''; + if (opened) render(); + try { + const data = await operation(); + syncIdentity(); + if (token !== generation) return false; + inbox = append && inbox ? {...data,events:[...inbox.events,...data.events]} : data; + return true; + } catch (error) { + if (token === generation && opened) errorMessage = error.message || 'Notifications are temporarily unavailable.'; + return false; + } finally { + if (token === generation) { + updatedAt = Date.now(); + busy = false; + render(); + } + } + } + + function poll() { + syncIdentity(); + if (identity && !opened && document.visibilityState !== 'hidden' && Date.now()-updatedAt > 30000) + update(() => read()); + } + + function mounted() { + if (!timer) timer = setInterval(poll,15000); + poll(); + } + + function close(focus) { + if (!opened) return; + opened = false; + render(); + if (focus) root.querySelector('[data-action="notifications-toggle"]')?.focus({preventScroll:true}); + } + + async function action(name, id) { + if (!name.startsWith('notifications-')) return false; + if (name === 'notifications-toggle') { + if (!user()) await signIn(); + else if (opened) close(true); + else { + opened = true; + render(); + await update(() => read()); + } + } + if (name === 'notifications-more' && inbox?.nextCursor) + await update(() => read(inbox.nextCursor),true); + if (name === 'notifications-read-all' && inbox?.through) + await update(() => mark('read-all',{ through:inbox.through })); + if (name === 'notifications-item') { + const event = inbox?.events.find(row => row.id === Number(id)); + if (!event) return true; + const current = identity; + if (!event.read && !await update(() => mark('read',{id:event.id}))) return true; + if (current === identity) { + close(false); + await navigate(event); + } + } + return true; + } + + document.addEventListener('pointerdown',event => { + if (opened && !event.target.closest('[data-notification-slot]')) close(false); + }); + document.addEventListener('keydown',event => { + if (opened && event.key === 'Escape') { + event.preventDefault(); + close(true); + } + }); + document.addEventListener('visibilitychange',poll); + return { markup, action, mounted }; + } }; +}()); + diff --git a/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js b/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js index 10309bc7..b80ff60b 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js +++ b/runtime-recomp/src/game/mod_library/website/assets/racing-ui.js @@ -1,8 +1,7 @@ (function () { 'use strict'; - const replayModule = new URL('replay-format.js?v=1', document.currentScript?.src || new URL('assets/racing-ui.js', document.baseURI).href); const activityPeriods = [['7','7 days'],['30','30 days'],['all','All time']]; - const sections = [['vanilla','Vanilla Tracks'],['custom','Custom Tracks'],['full-game','Full Game']]; + const sections = [['overall','Top Players'],['vanilla','Vanilla Tracks'],['custom','Custom Tracks'],['full-game','Full Game']]; const phases = {waiting:'In lobby',testing:'Testing connection',starting:'Starting',loading:'Loading',racing:'Racing',returning:'Returning to lobby'}; const states = {uploading:'Upload incomplete',queued:'Waiting for verification',verified:'Waiting for moderator review',published:'Published',rejected:'Rejected'}; const clock = ticks => { @@ -16,17 +15,19 @@ const linkedRoom = /^#lobby=([a-f0-9]{32})$/.exec(location.hash)?.[1]; let activityPeriod = 'all'; let online, directoryError, directoryBusy = false, directoryTimer; - let catalogue, board, selectedBoard = '', section = 'vanilla', listingTab = 'boards'; - let privateRows = []; + let catalogue, ranking, overall, profile, section = 'overall', listingTab = 'boards', runId = ''; + let playerId = '', playerPanel = 'score', profileError = ''; + let fromProfile = false, explainPoints = false, selectedRecord = null; + let privateRuns, quotaTimer, score = 'race'; + const quotaDate = new Intl.DateTimeFormat(undefined, { dateStyle:'medium', timeStyle:'medium' }); + let query = '', world = '', vehicle = '', availability = '', course = '', courseVehicle = '', racer = ''; + const vehicleNames = {car:'Car',hovercraft:'Hovercraft',plane:'Plane',mixed:'Mixed'}; + const matches = value => value.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()); let leaderboardBusy = false, leaderboardError = '', leaderSequence = 0; - let file, manifest, postMessage = '', posting = false, fileSequence = 0, postError = false; let currentPage = '', onlineNotice = '', privateIdentity = ''; - async function request(path, { fresh = false, method = 'GET', body, privateAccess = false, type = 'application/json', download = false } = {}) { - const endpoint = new URL(config.apiBase); - if (endpoint.protocol !== 'https:' || endpoint.username || endpoint.password || endpoint.hash || endpoint.search) - throw new Error('The library address is invalid.'); - const headers = { Accept: download ? 'application/octet-stream' : 'application/json' }; + async function request(path, { fresh = false, method = 'GET', body, privateAccess = false, type = 'application/json' } = {}) { + const headers = { Accept:'application/json' }; if (privateAccess) { await Auth.ensureSession(); const token = Auth.getToken(); @@ -34,9 +35,8 @@ headers.Authorization = 'Bearer ' + token; } if (body !== undefined) headers['Content-Type'] = type; - const reply = await fetch(new URL('/v1/' + path, endpoint), { method, body, headers, redirect:'error', + const reply = await fetch(apiURL(path), { method, body, headers, redirect:'error', credentials:'omit', cache:fresh ? 'reload' : 'default', signal:AbortSignal.timeout(20000) }); - if (download && reply.ok) return reply.blob(); const data = await reply.json().catch(() => ({})); if (reply.ok) return data; const error = new Error(data.error?.message || 'The service is temporarily unavailable.'); @@ -51,6 +51,7 @@ const action = focusAction || focused?.dataset.action; const id = focusAction ? null : focused?.dataset.id; region.innerHTML = template(); + if (region.hasAttribute('data-leaderboard-region')) updateSubmissionQuota(); renderIcons(); if (action) [...region.querySelectorAll('[data-action]')] .find(node => node.dataset.action === action && (id == null || node.dataset.id === id))?.focus(); @@ -165,7 +166,6 @@ } } - const postButton = () => button('post-run','Post a run','gold'); function clearPrivateIfChanged() { const account = user(); const identity = account ? account.id + ':' + account.role : ''; @@ -176,12 +176,8 @@ listingTab = 'boards'; leaderboardError = ''; leaderboardBusy = false; - privateRows = []; + privateRuns = undefined; } - ++fileSequence; - file = manifest = undefined; - postMessage = ''; - postError = false; } function speedrunsPage() { clearPrivateIfChanged(); @@ -195,121 +191,463 @@ const nav = ''; - const tools = '
' + postButton() + + const tools = '
' + (user() ? button('run-list','My runs','quiet','mine') : '') + (isStaff() ? button('run-list','Review runs','quiet','review') : '') + '
'; if (!catalogue) return nav + '
Loading leaderboards…
'; - const matching = catalogue.boards.filter(value => value.kind === section); - return nav + tools + (board ? rankingContent() : matching.length ? '
' + - matching.map(track => '

' + esc(track.title) + - '

' + esc(track.category) + ' · ' + esc(track.vehicle) + - '

' + button('run-board','View times','quiet',track.id) + '
').join('') + '
' : - '

' + (section === 'full-game' ? 'Full-game categories planned for replay qualification include Any%, 100% and All Trophy Races.' : - 'Times will appear here once the first tracks pass replay qualification.') + '

') + - (section === 'custom' && !board ? customContent() : ''); + if (course) return nav + tools + rankingContent(); + if (section === 'overall') return nav + tools + overallContent(); + if (section === 'vanilla') return nav + tools + vanillaContent(); + if (section === 'custom') return nav + tools + customContent(); + return nav + fullGameContent(); + } + + const points = milli => Number.isSafeInteger(milli) ? (milli/1000).toLocaleString(undefined,{maximumFractionDigits:3}) : '—'; + function overallContent() { + const explanation = '
How points work
' + + '

Verified results earn points for placing higher (70%) and getting closer to the record (30%). Solo boards count for 35%. Board weight grows to 100% at eight players.

' + + '

Track scores are 75% Full Race and 25% Best Lap. Each player contributes their best time in each, across all racers.

' + + '

Posted PBs count each current verified, published best time on a scored board. A Time Trial can have a race PB and a lap PB. World Records are the PBs holding or sharing first place.

' + + '
Vanilla Tracks · 500
Scores across populated boards, with equal weight per vehicle type.
' + + '
Custom Tracks · 250
Best 10 tracks for up to 200 points, plus the next 20 for up to 50. A new track can earn more points without reducing existing scores.
' + + '
Full Game · 250
Finish scores across populated Full Game categories.
'; + if (!overall) return explanation + '

Loading top players…

'; + const players = overall.players; + const selected = players.find(player=>player.id===playerId) || players[0]; + const rows = players.map(player => { + const active = player.id===selected.id; + return '' + esc(player.place) + '' + + button('overall-player',esc(player.name),'quiet small',player.id,'aria-pressed="'+active+'"') + + '' + esc(personalBestCount(player)) + '' + esc(player.records) + + '' + points(player.total) + ''; + }).join(''); + return explanation + '
' + + '

Top Players

' + (players.length ? + '' + + '' + + rows + '
RankPlayerPosted PBsWorld RecordsPoints
' : '

The first published run will appear here.

') + + (overall.tiedCutoff ? '

More players share the final rank shown.

' : '') + '
' + + (selected ? profileContent(selected) : '') + '
'; + } + + const personalBestCount = player => Number.isSafeInteger(player.personalBests) ? player.personalBests : '—'; + + function profileContent(player) { + const tabs = [['score','Score breakdown'],['runs','Ranked runs']].map(([id,label]) => + button('overall-panel',label,'quiet small',id,'aria-pressed="'+(playerPanel===id)+'"')).join(''); + const stats = '
Posted PBs
' + esc(personalBestCount(player)) + + '
World Records
' + esc(player.records) + '
'; + const scoreBreakdown = '
' + + [['Vanilla Tracks','vanilla',500],['Custom Tracks','custom',250],['Full Game','fullGame',250]].map(([name,id,cap]) => { + const value = player.points[id]; + return '
' + name + '' + points(value) + + ' / ' + cap + ' pts
'; + }).join('') + '

' + esc(player.podiums) + ' podiums · ' + + esc(player.coverage) + ' ranked events

'; + return '
' + + '

#' + esc(player.place) + + ' overall

' + esc(player.name) + + '

' + points(player.total) + ' pts
' + + '' + stats + + (playerPanel==='runs' ? profileRunsContent(player.id) : scoreBreakdown) + '
'; + } + + function profileRunsContent(id) { + if (profileError) return '

' + esc(profileError) + '

' + button('run-refresh','Try again','quiet small'); + if (profile?.player.id!==id) return '

Loading ranked runs…

'; + const {events,customTracks} = profile; + const custom = new Map(customTracks.map(track=>[track.id,track])); + return '
' + events.map(event => { + const customScore = event.kind==='custom' && custom.get(event.id); + const record = (label,result) => '
' + label + ' · #' + esc(result.place) + ' · ' + + clock(result.ticks) + '' + (result.place===1 ? 'World Record' : '') + + (result.hasVideo ? button('run-video','Watch Video','quiet small',result.runId) : '') + '
'; + return '
' + esc(event.title) + '' + + '

' + + esc(sections.find(([id]) => id===event.kind)?.[1]) + (event.kind==='full-game' ? '' : ' · ' + esc(vehicleNames[event.vehicle])) + + (customScore ? ' · Scoring track #' + esc(customScore.slot) + ' (' + points(customScore.points) + ' pts)' : '') + '

' + + record(event.kind==='full-game' ? 'Finish' : 'Full Race',event.race) + + (event.lap ? record('Best Lap',event.lap) : '') + '
'; + }).join('') + '
' + (profile.nextOffset!=null ? button('run-more-profile','More results','quiet') : ''); + } + + const recordDay = stamp => new Date(stamp*1000).toLocaleDateString(undefined,{day:'numeric',month:'short',year:'numeric',timeZone:'UTC'}); + function reignDuration(seconds) { + for (const [unit,size] of [['day',86400],['hour',3600],['minute',60]]) { + const count = Math.floor(seconds/size); + if (count>0) return count + ' ' + unit + (count===1 ? '' : 's'); + } + return Math.max(0,seconds) + ' sec'; + } + function recordHistoryContent(history) { + if (!Array.isArray(history?.changes)) return ''; + const events = history.changes; + const incomplete = '

Some publication dates are unavailable.

'; + if (!events.length) return '

World record history

' + + (history.complete ? '

History appears after the first published run.

' : incomplete) + '
'; + const first = events[0], last = events.at(-1); + const choice = events.findIndex(event=>event.at===selectedRecord); + const index = choice<0 ? events.length-1 : choice; + const chosen = events[index]; + const end = history.complete ? Math.max(last.at,history.asOf) : last.at; + const x = stamp => 12 + 976*(stamp-first.at)/Math.max(end-first.at,1); + const y = time => 9 + 78*(first.ticks-time)/Math.max(first.ticks-last.ticks,1); + const line = events.map((event,i)=>i ? 'H '+x(event.at)+' V '+y(event.ticks) : 'M '+x(event.at)+' '+y(event.ticks)).join(' ')+' H '+x(end); + const duration = chosen.until || history.complete ? ' · ' + (chosen.until ? 'Stood for ' : 'Unbeaten for ') + + reignDuration((chosen.until || end)-chosen.at) : ''; + return '

World record history

' + + '' + clock(last.ticks) + '
' + + '
' + clock(first.ticks) + '' + + (last.ticks!==first.ticks ? ''+clock(last.ticks)+'' : '') + + '
' + events.map((event,i) => '').join('') + + '
' + recordDay(first.at) + '' + (end!==first.at ? ''+recordDay(end)+'' : '') + + '
' + clock(chosen.ticks) + ' · ' + + recordDay(chosen.at) + esc(duration) + '' + chosen.holders.map(holder => '

' + esc(holder.name) + + (holder.until || history.complete ? ' · ' + (holder.until ? 'Held for ' : 'Holding for ') + + reignDuration((holder.until || end)-holder.from) : '') + '

').join('') + + '
' + (!history.complete ? incomplete : '') + + (history.earlierChanges ? '

Showing the latest record changes.

' : '') + '
'; + } + + function option(value, label, selected) { + return ''; + } + + function filterSelect(label, key, first, options, value) { + return ''; + } + + function trackFilters(trackWorlds = []) { + const search = ''; + const kind = section === 'custom' ? '' : + filterSelect('World', 'world', 'All worlds', trackWorlds.map(name => [name,name]), world) + + filterSelect('Vehicle', 'vehicle', 'All vehicles', Object.entries(vehicleNames).slice(0,3), vehicle); + return '
' + search + kind + filterSelect('Status', 'availability', 'All tracks', + [['ranked','Ranked'],['pending','Awaiting qualification']],availability) + '
'; + } + + function statusMatches(qualified) { + return !availability || qualified === (availability === 'ranked'); + } + + function trackScore(label, score) { + return '
' + label + '' + + (Number.isSafeInteger(score?.ticks) && score.ticks > 0 ? + '' + esc(score.name) + '' + + clock(score.ticks) + '' + icon('crown') + + '' : '—') + '
'; + } + + function trackRow(track, details, qualified, fullGame = false) { + const vehicles = track.vehicles || []; + const leaders = track.leaders || {}; + const records = fullGame ? trackScore('Finish time', leaders.mixed?.race) : + vehicles.map(id => '

' + + esc(vehicleNames[id]) + '

' + trackScore('Full race', leaders[id]?.race) + + trackScore('Best lap', leaders[id]?.lap) + '
').join(''); + const route = fullGame && track.stages.length ? '
Route splits' + + '
    ' + track.stages.map(stage => '
  1. ' + esc(stage) + '
  2. ').join('') + + '
' : ''; + return '

' + + esc(track.title) + '

' + esc(details) + + '

' + + (qualified ? button('run-course','View Times','quiet',track.id) : 'Awaiting qualification') + + route + '
' + + (records ? '
' + records + '
' : '') + '
'; + } + + function vanillaContent() { + const boards = catalogue.boards.filter(value => value.kind === 'vanilla'); + const tracks = catalogue.vanillaTracks || []; + const isRanked = track => boards.some(value => value.title === track.title && value.ranked && (!vehicle || value.vehicle === vehicle)); + const worlds = [...new Set(tracks.map(track => track.world))].filter(Boolean); + const matching = tracks.filter(track => matches(track.title) && (!world || track.world === world) && + (!vehicle || track.vehicles.includes(vehicle)) && statusMatches(isRanked(track))); + return trackFilters(worlds) + '

' + matching.length + ' of ' + tracks.length + ' tracks

' + + (matching.length ? '
' + matching.map(track => + trackRow(track, [track.world,...track.vehicles.map(id => vehicleNames[id])].join(' · '), isRanked(track)) + ).join('') + '
' : '

No tracks match these filters.

') + '
'; } function customContent() { - return '

Tracks in the Mod Library

' + - catalogue.customTracks.map(track => '
' + - esc(track.title) + '

Version ' + esc(track.version) + '

' + - (track.qualified ? 'Ranked' : 'Awaiting qualification') + '
').join('') + - (catalogue.customTracks.length ? '' : '

No custom tracks are listed yet.

') + + const matching = catalogue.customTracks.filter(track => matches(track.title) && statusMatches(track.qualified)); + return trackFilters() + '

Tracks in the Mod Library

' + + matching.map(track => trackRow(track, ['Version ' + track.version,...(track.vehicles || []).map(id => vehicleNames[id])].join(' · '), + track.qualified)).join('') + + (matching.length ? '' : '

No loaded tracks match these filters.

') + '
' + (catalogue.nextCursor ? button('run-more','More tracks','quiet') : '') + '
'; } + function rankingContent() { - return '

' + - esc(board.board.title) + '

' + button('run-back','All tracks','quiet small') + '

' + - esc(board.board.category) + ' · ' + esc(board.board.vehicle) + '

' + - (board.entries.length ? '' + - board.entries.map(entry => '').join('') + '
RankRacerTimeReplay
' + esc(entry.place) + '' + esc(entry.name) + '' + - clock(entry.ticks) + '' + button('run-download','Download','quiet small',entry.id) + - '
' : '

No verified runs have been published yet.

') + '
'; + if (!ranking) return '
Loading times…
'; + const videoEnabled = catalogue?.videoEnabled !== false; + const videoNotice = videoEnabled && catalogue?.hostedVideos ? + '

The leaderboard host prepares videos for review. You can close DKR-R once your upload finishes.

' : ''; + const filters = section === 'full-game' ? '' : + filterSelect('Racer','ranking-racer','All racers',ranking.racers.map(item => [item.id,item.name]),ranking.racer) + + (ranking.vehicles.length ? filterSelect('Vehicle','ranking-vehicle','',ranking.vehicles.map(id => [id,vehicleNames[id]]),ranking.vehicle) : ''); + return '

' + + esc(ranking.track.title) + '

' + esc(ranking.track.world || ranking.track.version || '') + + '

' + button('run-back',fromProfile ? 'Back to player stats' : section==='full-game' ? 'All categories' : 'All tracks','quiet small') + '
' + + '
' + filters + '
' + + (section === 'full-game' ? '' : '') + + videoNotice + + (ranking.entries.length ? '' + + (videoEnabled ? '' : '') + '' + + ranking.entries.map(entry => '' + + (videoEnabled ? '' : '') + + '').join('') + '
RankPlayerRacerTimeVideo
' + esc(entry.place) + '' + esc(entry.name) + '' + + esc(entry.racer || '—') + '' + clock(entry.ticks) + '' + (catalogue?.hostedVideos && !entry.hasVideo ? 'Video pending' : + button('run-video','Watch Video','quiet small',entry.id)) + '
' : + '

' + (ranking.ranked ? 'No verified runs have been published for this selection.' : 'This track and vehicle are awaiting replay qualification.') + + '

') + (ranking.nextOffset != null ? button('run-more-times','More times','quiet') : '') + + recordHistoryContent(ranking.history) + '
'; + } + + function fullGameContent() { + const categories = catalogue.adventureCatalogue || []; + return '
' + categories.map(category => { + const ranked = catalogue.boards.some(board => board.id === 'adventure-' + category.id && board.ranked); + return trackRow(category, category.summary, ranked, true); + }).join('') + + '
Shared rules and verification' + icon('chevron-down') + + '

The ranked launcher supports US v1.0 and US v1.1. Tracks routes get one completed save slot to unlock the courses. All Bosses uses that slot in Adventure. The other Adventure routes start from a new save. Each run uses its own save and blocks gameplay mods and Magic Codes.

' + + '

The clock starts in the Overworld for Adventure routes and in the first race for Tracks routes. It keeps running across menus, travel and races. The verifier checks the finish event and split times before staff review.

'; + } + function updateSubmissionQuota() { + clearTimeout(quotaTimer); + const panel = view() === 'speedruns' && root.querySelector('[data-submission-quota]'); + const quota = privateRuns?.submissionQuota; + if (!panel || !quota) return; + const now = quota.observedAt * 1000 + (performance.now() - privateRuns.receivedAt); + const active = quota.releasesAt.filter(stamp => stamp * 1000 > now); + panel.querySelector('strong').textContent = (quota.maxRuns - active.length) + ' of ' + quota.maxRuns + ' submissions left'; + const time = panel.querySelector('time'); + time.parentElement.hidden = active.length === 0; + if (active.length) { + const next = Math.min(...active) * 1000; + const date = new Date(next); + time.dateTime = date.toISOString(); + time.textContent = quotaDate.format(date); + quotaTimer = setTimeout(updateSubmissionQuota, Math.ceil(next - now)); + } } + function runListContent() { + const review = listingTab === 'review'; + const rows = privateRuns?.runs ?? []; + const quota = !review && !runId && privateRuns?.submissionQuota ? + '

' + + '
' : ''; + const videoStatus = { + queued:'Waiting for the video renderer', + rendering:'Preparing video…', + retrying:'Video render will retry automatically', + unavailable:'Video rendering is unavailable', + }; return '

' + (listingTab === 'review' ? 'Review runs' : 'My runs') + - '

' + button('run-back','Back to leaderboards','quiet') + '
' + - (leaderboardBusy ? '

Loading runs…

' : privateRows.length ? - '
' + privateRows.map(run => '

' + + '

' + (runId ? button('run-list','Show all runs','quiet',listingTab) : '') + + button('run-refresh','Refresh','quiet') + button('run-back','Back to leaderboards','quiet') + '
' + quota + + (leaderboardBusy ? '

Loading runs…

' : rows.length ? + '
' + rows.map(run => '

' + esc(run.title) + '

' + esc(states[run.state] || run.state) + '

' + esc(run.category) + ' · ' + esc(run.vehicle) + ' · ' + clock(run.ticks ?? run.claimedTicks) + (run.ticks == null ? ' (recorded)' : '') + '

' + esc(run.name) + ' · ' + - esc(run.platform) + ' ' + esc(run.arch) + ' · US ROM ' + esc(run.rom) + '

' + + (run.linkedLocal ? 'Linked local run' : esc(run.platform) + ' ' + esc(run.arch)) + (run.rom === 77 ? ' · US v1.0' : ' · US v1.1') + '

' + (run.notes ? '

' + esc(run.notes) + '

' : '') + (run.reason ? '

' + esc(run.reason) + '

' : '') + - '
' + (run.state === 'uploading' ? '' : button('run-download','Download replay','quiet',run.id)) + '
' + - (listingTab === 'review' ? '
' + - button('run-publish','Publish','gold', run.id) + button('run-reject','Reject','red', run.id) + '
' : '') + - '
').join('') + '
' : '

No runs to show yet.

'); + (run.state === 'published' || review && run.videoState === 'ready' ? + '
' + button('run-video','Watch Video',review ? 'gold' : 'quiet',run.id) + '
' : + run.state === 'verified' && videoStatus[run.videoState] ? + '

' + videoStatus[run.videoState] + '

' : '') + + (review ? '
' + + (run.videoRequired && run.videoState !== 'ready' ? + '' : button('run-publish','Publish','gold',run.id)) + + button('run-reject','Reject','red',run.id) + '
' : '') + + '
').join('') + '
' : '

' + + (runId ? 'This run is no longer available in this list.' : 'No runs to show yet.') + '

'); } async function loadLeaderboards({ more = false, focus } = {}) { const seq = ++leaderSequence; + const playerOnly = listingTab==='boards' && !course && section==='overall' && playerPanel==='runs' && !!playerId; leaderboardBusy = true; leaderboardError = ''; + if (playerOnly) profileError = ''; try { if (listingTab !== 'boards') { - const data = await request('speedruns/' + listingTab, { privateAccess:true }); - if (seq === leaderSequence) privateRows = data.runs; - } else if (selectedBoard) { - const data = await request('speedruns/boards/' + encodeURIComponent(selectedBoard)); - if (seq === leaderSequence) board = data; + const endpoint = 'speedruns/' + listingTab + (runId ? '?run=' + encodeURIComponent(runId) : ''); + const data = await request(endpoint, { privateAccess:true }); + if (seq === leaderSequence) privateRuns = { ...data, receivedAt:performance.now() }; + } else if (course) { + const params = new URLSearchParams({score,kind:section}); + if (courseVehicle) params.set('vehicle',courseVehicle); + if (racer) params.set('racer',racer); + if (more && ranking?.nextOffset != null) params.set('offset',ranking.nextOffset); + const data = await request('speedruns/tracks/' + encodeURIComponent(course) + '?' + params); + if (seq === leaderSequence) ranking = more && ranking ? + {...data,history:ranking.history,entries:[...ranking.entries,...data.entries]} : data; } else { - const data = await request('speedruns' + (more && catalogue?.nextCursor ? '?cursor=' + encodeURIComponent(catalogue.nextCursor) : '')); - if (seq === leaderSequence) catalogue = more && catalogue ? {...catalogue, nextCursor:data.nextCursor, - customTracks:[...catalogue.customTracks, ...data.customTracks]} : data; + if (section==='overall') { + const path = playerOnly ? 'speedruns/overall/'+encodeURIComponent(playerId) + + (more && profile?.nextOffset!=null ? '?offset='+profile.nextOffset : '') : 'speedruns/overall'; + const [base,data] = await Promise.all([catalogue || request('speedruns'),request(path,{fresh:true})]); + if (seq === leaderSequence) { + catalogue = base; + if (playerOnly) profile = more && profile ? {...data,events:[...profile.events,...data.events]} : data; + else { + overall = data; + if (!overall.players.some(player=>player.id===playerId)) playerId = overall.players[0]?.id || ''; + } + } + } else { + const data = await request('speedruns' + (more && catalogue?.nextCursor ? '?cursor=' + encodeURIComponent(catalogue.nextCursor) : '')); + if (seq === leaderSequence) catalogue = more && catalogue ? {...catalogue, nextCursor:data.nextCursor, + customTracks:[...catalogue.customTracks, ...data.customTracks]} : data; + } } } catch (error) { - if (seq === leaderSequence) leaderboardError = error.message; + if (seq === leaderSequence) { + if (playerOnly) profileError = error.message; + else leaderboardError = error.message; + } } finally { if (seq === leaderSequence) { leaderboardBusy = false; if (view() === 'speedruns') refreshRegion('[data-leaderboard-region]',speedrunContent,focus); - if (view() === 'post-run') refreshRegion('[data-post-region]',postContent); } } } function postPage() { - clearPrivateIfChanged(); - return pagehead('Post a run','Attach a replay from DKR-R to send it for verification and review.','speedruns') + - '
' + postContent() + '
'; - } - function postContent() { - const qualified = catalogue?.boards?.find(entry => entry.id === manifest?.board); - return '
' + - (!user() ? '

Sign in with the same library account you use to post mods and comments.

' + - button('run-sign-in',icon('user-round') + 'Sign in','gold') : - '' + - (manifest ? '

' + esc(qualified?.title || manifest.board) + '

' + - esc(file.name) + '

' + - esc(qualified?.category || 'Unknown category') + ' · ' + clock(manifest.clockTicks) + - ' recorded · US ROM ' + esc(manifest.rom) + ' · ' + esc(manifest.platform) + '

' : '') + - (!catalogue?.canSubmit ? '

Posting opens once replay verification is ready.

' : '') + - '
' + (catalogue?.canSubmit && qualified && !posting && file ? button('run-upload','Post run','gold') : '') + '
') + - '

' + esc(postMessage) + '

'; + return pagehead('Post a run', 'Choose Post to Leaderboard in the Launcher’s Replays tab. Once the upload finishes you can close DKR-R. The host prepares the video and Time Trial ghost for review. Track the submission in My runs.', 'speedruns'); } - root.addEventListener('change', async event => { - if (!event.target.matches('[data-run-file]')) return; - const sequence = ++fileSequence; - const next = event.target.files[0]; - file = manifest = undefined; - postMessage = ''; - postError = false; - if (next) { - try { - const { MAX_REPLAY_BYTES, parseReplay } = await import(replayModule.href); - if (next.size > MAX_REPLAY_BYTES) throw new Error(); - const parsed = parseReplay(new Uint8Array(await next.arrayBuffer())); - if (sequence !== fileSequence || view() !== 'post-run') return; - file = next; - manifest = parsed; - } catch { - if (sequence !== fileSequence || view() !== 'post-run') return; - postMessage = 'Choose a valid .dkrreplay file under 1 MiB.'; - postError = true; + + function apiURL(path) { + const endpoint = new URL(config.apiBase, location.href); + const local = endpoint.origin === location.origin && ['127.0.0.1','localhost'].includes(endpoint.hostname); + if ((!local && endpoint.protocol !== 'https:') || endpoint.username || endpoint.password || endpoint.hash || endpoint.search) + throw new Error('The library address is invalid.'); + return new URL('/v1/' + path, endpoint); + } + + async function openRunVideo(id, target) { + if (!/^[A-Za-z0-9_-]{1,96}$/.test(id)) return; + const parent = target.closest('[data-leaderboard-region]'); + if (!parent) return; + const reviewCard = target.closest('[data-review-run]'); + const previous = parent.querySelector('[data-run-player]'); + const resumeAt = previous?.dataset.runPlayer === id ? previous.querySelector('video')?.currentTime : 0; + if (previous) previous.remove(); + const player = document.createElement('section'); + player.className = 'dkr-panel dkr-stack dkr-run-player'; + player.dataset.runPlayer = id; + const label = document.createElement('h2'); + label.className = 'dkr-subtitle'; + label.textContent = reviewCard ? 'Review video' : 'Verifier-rendered replay'; + const status = document.createElement('p'); + status.setAttribute('role', 'status'); + status.textContent = 'Checking for video…'; + const close = document.createElement('button'); + close.type = 'button'; + close.className = 'dkr-btn quiet'; + close.textContent = 'Close video'; + close.addEventListener('click', () => { player.remove(); target.focus(); }); + player.append(label, status, close); + if (reviewCard) target.parentElement.after(player); + else parent.append(player); + player.scrollIntoView({ block:'nearest' }); + close.focus({ preventScroll:true }); + try { + const path = 'speedruns/runs/' + encodeURIComponent(id) + '/video'; + const url = apiURL(path); + if (reviewCard) { + const { grant } = await request(path, {method:'POST', privateAccess:true}); + if (!player.isConnected) return; + url.searchParams.set('review',grant); + } + const ready = await fetch(url, { method:'HEAD', signal:AbortSignal.timeout(15000), redirect:'error' }); + if (!player.isConnected) return; + if (ready.status === 404) { + status.textContent = 'This run’s video is preparing or has not been rendered yet.'; + return; } + if (!ready.ok) throw new Error(); + const video = document.createElement('video'); + video.controls = true; + video.preload = 'metadata'; + video.playsInline = true; + if (reviewCard) video.crossOrigin = 'anonymous'; + video.setAttribute('aria-label', 'Verifier-rendered gameplay'); + if (resumeAt > 0) video.addEventListener('loadedmetadata', () => { video.currentTime = resumeAt; }, {once:true}); + video.addEventListener('error', () => { + status.hidden = false; + status.textContent = 'The video could not be played. Open Watch Video again to retry.'; + }); + video.src = url.href; + status.hidden = true; + player.insertBefore(video, close); + } catch { + status.textContent = 'The run video is temporarily unavailable.'; + } + } + + async function openRunList(tab, id = '') { + if (!requireSignedIn({view:'speedruns'}, tab === 'review')) return; + if (view() !== 'speedruns') await go('speedruns', {}, false); + listingTab = tab; + runId = id; + privateRuns = undefined; + refreshRegion('[data-leaderboard-region]', speedrunContent); + await loadLeaderboards({focus:'run-back'}); + } + + function updateTrackFilter(target) { + const filter = target.dataset.boardFilter; + if (!filter || !catalogue) return; + if (filter === 'query') query = target.value; + if (filter === 'world') world = target.value; + if (filter === 'vehicle') vehicle = target.value; + if (filter === 'availability') availability = target.value; + const template = document.createElement('template'); + template.innerHTML = section === 'custom' ? customContent() : vanillaContent(); + root.querySelector('[data-track-results]')?.replaceWith(template.content.querySelector('[data-track-results]')); + renderIcons(); + } + root.addEventListener('input', event => { + if (event.target.dataset.boardFilter === 'query') updateTrackFilter(event.target); + }); + root.addEventListener('change', async event => { + const filter = event.target.dataset.boardFilter; + if (course && filter==='record') { + selectedRecord = Number(event.target.value); + refreshRegion('[data-leaderboard-region]',speedrunContent); + root.querySelector('[data-board-filter="record"]')?.focus({preventScroll:true}); + return true; } - refreshRegion('[data-post-region]',postContent, file && catalogue?.canSubmit ? 'run-upload' : undefined); + if (course && (filter === 'ranking-racer' || filter === 'ranking-vehicle')) { + if (filter === 'ranking-vehicle') { + courseVehicle = event.target.value; + racer = ''; + } else racer = event.target.value; + selectedRecord = null; + await loadLeaderboards(); + root.querySelector('[data-board-filter="' + filter + '"]')?.focus({preventScroll:true}); + } else if (filter !== 'query') updateTrackFilter(event.target); }); async function action(action, id, target) { @@ -336,55 +674,82 @@ refreshRegion('[data-online-region]',onlineContent); return true; } - if (action === 'run-category' || action === 'run-back') { - if (action === 'run-category') section = id; + if (action === 'overall-player') { + if (playerId===id) return true; ++leaderSequence; - selectedBoard = ''; board = undefined; listingTab = 'boards'; privateRows = []; leaderboardError = ''; + leaderboardBusy = false; + playerId = id; + playerPanel = 'score'; + profile = undefined; + profileError = ''; refreshRegion('[data-leaderboard-region]',speedrunContent); - if (!catalogue) await loadLeaderboards(); return true; } - if (action === 'run-board' || action === 'run-list' || action === 'run-more' || action === 'run-refresh') { - if (action === 'run-board') selectedBoard = id; - if (action === 'run-list') { - if (!requireSignedIn({view:'speedruns'},id === 'review')) return true; - listingTab = id; privateRows = []; - } - await loadLeaderboards({more:action === 'run-more', focus:action === 'run-board' ? 'run-back' : undefined}); + if (action === 'overall-panel' && (id==='score' || id==='runs')) { + playerId = playerId || overall?.players[0]?.id || ''; + playerPanel = id; + refreshRegion('[data-leaderboard-region]',speedrunContent); + if (id==='runs' && profile?.player.id!==playerId) await loadLeaderboards(); return true; } - if (action === 'run-sign-in') { requireSignedIn({view:'post-run'}); return true; } - if (action === 'run-upload') { - if (posting || !file || !user()) return true; - const owner = user().id; - posting = true; - postError = false; - postMessage = 'Posting your run…'; - refreshRegion('[data-post-region]',postContent); - try { - const data = await request('speedruns/runs', { method:'POST', privateAccess:true, type:'application/octet-stream',body:file }); - if (view() === 'post-run' && user()?.id === owner) { - file = manifest = undefined; - postMessage = 'Run saved. ' + (states[data.run.state] || 'Check My runs for its status') + '.'; - } - } catch (error) { - if (view() === 'post-run' && user()?.id === owner) { postError = true; postMessage = error.message; } - } finally { - posting = false; - refreshRegion('[data-post-region]',postContent); + if (action === 'record-point') { + selectedRecord = Number(id); + refreshRegion('[data-leaderboard-region]',speedrunContent); + return true; + } + if (action === 'run-course' || action === 'overall-track') { + fromProfile = action==='overall-track'; + if (fromProfile) section = target.dataset.kind; + course = id; + courseVehicle = fromProfile && section!=='full-game' ? target.dataset.vehicle : section === 'vanilla' ? vehicle : ''; + selectedRecord = null; + ranking = undefined; + racer = ''; + score = 'race'; + refreshRegion('[data-leaderboard-region]',speedrunContent); + await loadLeaderboards({focus:'run-back'}); + return true; + } + if (action === 'run-category' || action === 'run-back') { + if (action === 'run-category') { + section = id; + fromProfile = false; + playerId = ''; + playerPanel = 'score'; + profile = undefined; + profileError = ''; + query = world = vehicle = availability = ''; + } else if (fromProfile) { + section = 'overall'; + fromProfile = false; } + ++leaderSequence; + const previous = course; + course = runId = ''; + ranking = undefined; + listingTab = 'boards'; + privateRuns = undefined; + leaderboardError = ''; + refreshRegion('[data-leaderboard-region]',speedrunContent); + if (previous) [...root.querySelectorAll('[data-action="run-course"]')] + .find(button => button.dataset.id === previous)?.focus({preventScroll:true}); + if (previous && section==='overall') [...root.querySelectorAll('[data-action="overall-track"]')] + .find(button=>button.dataset.id===previous)?.focus({preventScroll:true}); + if (!catalogue || section==='overall' && !overall) await loadLeaderboards(); + return true; + } + if (action === 'run-list') { await openRunList(id); return true; } + if (action === 'run-more' || action === 'run-more-times' || action === 'run-more-profile' || action === 'run-refresh') { + await loadLeaderboards({more:action !== 'run-refresh'}); return true; } - if (action === 'run-download') { - const blob = await request('speedruns/runs/' + encodeURIComponent(id) + '/replay', - { download:true, privateAccess:listingTab !== 'boards' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; link.download = 'DKR-R-' + id + '.dkrreplay'; - link.click(); - setTimeout(() => URL.revokeObjectURL(url),1000); + if (action === 'run-score' && (id === 'race' || id === 'lap')) { + score = id; + selectedRecord = null; + await loadLeaderboards({focus:'run-score'}); return true; } + if (action === 'run-video') { await openRunVideo(id, target); return true; } if (action === 'run-publish' || action === 'run-reject') { const reason = target.closest('article').querySelector('[data-review-note]').value; target.disabled = true; @@ -402,17 +767,31 @@ const next = view(); if (!root.querySelector('[data-online-region],[data-leaderboard-region],[data-post-region]') && ['online','speedruns','post-run'].includes(next)) return; + updateSubmissionQuota(); if (next === currentPage) return; currentPage = next; clearInterval(directoryTimer); - if (next !== 'post-run') { ++fileSequence; file = manifest = undefined; postMessage = ''; postError = false; } - if (next !== 'speedruns') { ++leaderSequence; listingTab = 'boards'; selectedBoard = ''; board = undefined; privateRows = []; leaderboardError = ''; } + if (next !== 'speedruns') { + ++leaderSequence; + section = 'overall'; + listingTab = 'boards'; + course = runId = playerId = ''; + playerPanel = 'score'; + ranking = profile = undefined; + profileError = ''; + fromProfile = false; + privateRuns = undefined; + leaderboardError = ''; + } if (next === 'online' && root.querySelector('[data-online-region]')) { loadOnline(); directoryTimer = setInterval(() => { if (!document.hidden) loadOnline(); },30000); } - if ((next === 'speedruns' || next === 'post-run') && !catalogue) loadLeaderboards(); + if (next === 'speedruns' && !course && (!catalogue || !overall)) loadLeaderboards(); } - return { onlinePage, speedrunsPage, postPage, action, mounted }; + root.addEventListener('toggle',event => { + if (event.target.matches('[data-points-explainer]')) explainPoints = event.target.open; + },true); + return { onlinePage, speedrunsPage, postPage, action, mounted, openRunList }; }}; }()); diff --git a/runtime-recomp/src/game/mod_library/website/assets/racing.css b/runtime-recomp/src/game/mod_library/website/assets/racing.css index 73d05553..3fa5c89f 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/racing.css +++ b/runtime-recomp/src/game/mod_library/website/assets/racing.css @@ -57,3 +57,180 @@ background: #1abfa9; border-radius: 3px 3px 0 0; } + + +#dkr-mod-library .dkr-board-filters { + display: grid; + grid-template-columns: minmax(12rem,2fr) repeat(3,minmax(8rem,1fr)); + gap: .75rem; +} +#dkr-mod-library .dkr-ranking-filters { display: flex; flex-wrap: wrap; gap: .75rem; } +#dkr-mod-library .dkr-ranked-select { display:grid; gap:.375rem; min-width:0; font-size:.875rem; font-weight:600; color:#c9dee7; } +#dkr-mod-library .dkr-ranked-select-control { position:relative; min-width:0; } +#dkr-mod-library .dkr-ranked-select-control .dkr-select { appearance:none; width:100%; min-height:44px; padding-right:2.3rem; } +#dkr-mod-library .dkr-ranked-select-control > .dkr-icon { position:absolute; top:50%; right:.75rem; transform:translateY(-50%); color:#ffc15a; pointer-events:none; } +#dkr-mod-library .dkr-board-filters .dkr-search { min-width:0; } +#dkr-mod-library .dkr-board-filters .dkr-search:focus-within { outline:2px solid #ffc15a; outline-offset:2px; } +#dkr-mod-library .dkr-board-filters .dkr-search input:focus { outline:none; } +#dkr-mod-library .dkr-track-name { min-width:0; overflow-wrap:anywhere; } +#dkr-mod-library .dkr-track-name h2, #dkr-mod-library .dkr-track-name p { margin:0; } +#dkr-mod-library .dkr-track-name h2 { font-size:1.025rem; } +#dkr-mod-library .dkr-track-name p { margin-top:.25rem; } +#dkr-mod-library .dkr-track-row { + display:grid; grid-template-columns:clamp(10rem,22%,16rem) minmax(0,1fr); + align-items:start; gap:1rem 1.25rem; +} +#dkr-mod-library .dkr-track-actions { display:grid; justify-items:start; gap:.5rem; margin-top:.75rem; } +#dkr-mod-library .dkr-track-splits { font-size:.85rem; color:#c9dee7; } +#dkr-mod-library .dkr-track-splits summary { cursor:pointer; } +#dkr-mod-library .dkr-track-records { + display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,10rem),1fr)); + gap:.85rem 1rem; min-width:0; +} +#dkr-mod-library .dkr-track-vehicle { display:grid; align-content:start; gap:.35rem; min-width:0; } +#dkr-mod-library .dkr-track-vehicle h3 { color:#ffc15a; font-size:.9rem; margin:0; } +#dkr-mod-library .dkr-track-score { + display:flex; flex-wrap:wrap; align-items:baseline; gap:.2rem .5rem; min-width:0; font-size:.85rem; +} +#dkr-mod-library .dkr-track-keeper { overflow-wrap:anywhere; min-width:0; } +#dkr-mod-library .dkr-track-time { display:inline-flex; align-items:baseline; gap:.45rem; white-space:nowrap; font-variant-numeric:tabular-nums; } +#dkr-mod-library .dkr-first-place { + display:inline-flex; align-items:center; gap:.2rem; color:#ffc15a; font-size:.75rem; font-weight:700; +} +#dkr-mod-library .dkr-first-place .dkr-icon { width:.9rem; height:.9rem; } +#dkr-mod-library .dkr-first-place svg { width:100%; height:100%; } +#dkr-mod-library .dkr-full-category summary { display:flex; align-items:center; flex-wrap:wrap; gap:.6rem; cursor:pointer; list-style:none; } +#dkr-mod-library .dkr-full-category summary::-webkit-details-marker { display:none; } +#dkr-mod-library .dkr-full-category .dkr-track-name { display:grid; flex:1; min-width:min(100%,12rem); } +#dkr-mod-library .dkr-full-category[open] summary .dkr-icon { transform:rotate(180deg); } +#dkr-mod-library .dkr-full-category p { margin-top:.75rem; } +@media (max-width:800px) { + #dkr-mod-library .dkr-board-filters { grid-template-columns:repeat(2,minmax(0,1fr)); } +} +@media (max-width:660px) { + #dkr-mod-library .dkr-track-row { grid-template-columns:minmax(0,1fr); } +} +@media (max-width:440px) { + #dkr-mod-library .dkr-board-filters { grid-template-columns:1fr; } + #dkr-mod-library .dkr-run-table th, #dkr-mod-library .dkr-run-table td { padding:.4rem .23rem; font-size:.79rem; } +} + +#dkr-mod-library .dkr-notification-slot { position:relative; display:inline-flex; } +#dkr-mod-library .dkr-header-nav .dkr-notification-bell { position:relative; width:42px; justify-content:center; padding:8px; } +#dkr-mod-library .dkr-notification-badge { + position:absolute; top:-.37rem; right:-.33rem; min-width:1.15rem; padding:0 .22rem; + border:1px solid #ffe6aa; border-radius:1rem; background:#c74a22; color:#fff4d4; + text-align:center; font-size:.69rem; line-height:1.05rem; +} +#dkr-mod-library .dkr-notification-panel { + position:absolute; z-index:20; top:calc(100% + .5rem); right:0; + width:min(24rem,calc(100vw - 2rem)); display:grid; gap:.6rem; + background:#0b2637; box-shadow:0 8px 20px #0007; padding:1rem; +} +#dkr-mod-library .dkr-notification-panel h2 { font-size:1.1rem; margin:0; } +#dkr-mod-library .dkr-notification-panel ul { + list-style:none; margin:0; padding:0 0 .3rem; max-height:min(50vh,24rem); overflow-y:auto; +} +#dkr-mod-library .dkr-notification-item { + width:100%; display:grid; gap:.25rem; padding:.65rem .6rem; + background:#102f43; border:1px solid #31536a; border-radius:6px; margin-bottom:.35rem; text-align:left; + color:#e4eef2; overflow-wrap:anywhere; +} +#dkr-mod-library .dkr-notification-item:hover { background:#16445b; } +#dkr-mod-library .dkr-notification-item[data-unread=true] { border-color:#ab8548; } +#dkr-mod-library .dkr-notification-dot { + display:inline-block; height:.48rem; width:.48rem; border-radius:50%; background:#ffc15a; margin-right:.4rem; +} +@media (max-width:850px) { + #dkr-mod-library .dkr-header { position:relative; } + #dkr-mod-library .dkr-notification-slot { position:static; } + #dkr-mod-library .dkr-notification-panel { top:calc(100% - .45rem); right:.55rem; } +} + +.dkr-run-player video { + display: block; + width: 100%; + max-height: 70vh; + border-radius: .65rem; + background: #071420; +} +.dkr-adventure-splits { padding-inline-start: 1.5rem; } + +#dkr-mod-library .dkr-points { + border-left: 3px solid #f3b759; + padding: .55rem .9rem; + background: #102d3f; + border-radius: .35rem; +} +#dkr-mod-library .dkr-points summary { color: #ffd083; font-weight: 700; cursor: pointer; } +#dkr-mod-library .dkr-points[open] summary { margin-bottom: .55rem; } +#dkr-mod-library .dkr-points dl { + display: grid; grid-template-columns: minmax(9.5rem,auto) minmax(0,1fr); gap: .25rem .75rem; margin: 0; +} +#dkr-mod-library .dkr-points dt { font-weight: 700; } +#dkr-mod-library .dkr-points dd { margin: 0; } +#dkr-mod-library .dkr-overall-layout { + display: grid; grid-template-columns: minmax(0,1.12fr) minmax(0,1fr); gap: 1rem; align-items: start; +} +#dkr-mod-library .dkr-overall-layout > section { min-width: 0; } +#dkr-mod-library .dkr-overall-table { font-variant-numeric: tabular-nums; } +#dkr-mod-library .dkr-overall-table :is(th,td):nth-child(3), +#dkr-mod-library .dkr-overall-table :is(th,td):nth-child(4) { text-align: right; } +#dkr-mod-library .dkr-overall-table td:nth-child(4), +#dkr-mod-library .dkr-overall-counts > div:last-child dd { color: #ffc965; } +#dkr-mod-library .dkr-overall-table :is(th,td):last-child { text-align: right; } +#dkr-mod-library .dkr-overall-table button { overflow-wrap: anywhere; max-width: 100%; text-align: left; } +#dkr-mod-library :is(.dkr-overall-table,.dkr-overall-profile-tabs) button[aria-pressed=true] { + background: #a93e24; border-color: #f3b759; color: #fff6da; +} +#dkr-mod-library .dkr-overall-profile h2 { overflow-wrap: anywhere; } +#dkr-mod-library .dkr-overall-score { color: #ffc965; font-size: 1.35rem; font-variant-numeric: tabular-nums; } +#dkr-mod-library .dkr-overall-counts { + display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: .7rem; + margin: 0; padding: .65rem 0; border-block: 1px solid #31566b; +} +#dkr-mod-library .dkr-overall-counts dt { color: #b9d0dc; } +#dkr-mod-library .dkr-overall-counts dd { margin: .1rem 0 0; font-size: 1.15rem; font-weight: 700; } +#dkr-mod-library .dkr-profile-points { display: grid; gap: .65rem; } +#dkr-mod-library .dkr-profile-points span { color: #ffc965; font-variant-numeric: tabular-nums; } +#dkr-mod-library .dkr-profile-points progress { + display: block; appearance: none; width: 100%; height: .45rem; margin-top: .25rem; + overflow: hidden; border: 0; border-radius: .3rem; background: #061e2c; +} +#dkr-mod-library .dkr-profile-points progress::-webkit-progress-bar { background: #061e2c; } +#dkr-mod-library .dkr-profile-points progress::-webkit-progress-value { background: #2edfbd; } +#dkr-mod-library .dkr-profile-points progress::-moz-progress-bar { background: #2edfbd; } +#dkr-mod-library .dkr-overall-record { color: #ffc965; } +#dkr-mod-library .dkr-record-history { + border: 1px solid #305a70; background: #0c2434; border-radius: .55rem; padding: .75rem; +} +#dkr-mod-library .dkr-record-history h3 { margin: 0; } +#dkr-mod-library .dkr-record-history strong { color: #ffd083; font-variant-numeric: tabular-nums; } +#dkr-mod-library .dkr-record-plot { + display: grid; grid-template-columns: minmax(4.9rem,auto) minmax(0,1fr); + gap: .35rem; color: #b8d0da; font-size: .78rem; font-variant-numeric: tabular-nums; +} +#dkr-mod-library .dkr-record-axis { display: flex; flex-direction: column; justify-content: space-between; height: 126px; padding: 3px .25rem 10px; } +#dkr-mod-library .dkr-record-line { height: 126px; position: relative; } +#dkr-mod-library .dkr-record-line svg { display: block; width: 100%; height: 100%; } +#dkr-mod-library .dkr-record-line path { fill: none; vector-effect: non-scaling-stroke; } +#dkr-mod-library .dkr-record-grid { stroke: #325369; stroke-width: 1; } +#dkr-mod-library .dkr-record-step { stroke: #ffc965; stroke-width: 2.2; } +#dkr-mod-library .dkr-record-mark { + position: absolute; transform: translate(-50%,-50%); width: 1.5rem; height: 1.5rem; + border: 0; padding: 0; background: transparent; cursor: pointer; +} +#dkr-mod-library .dkr-record-mark::after { + content: ''; display: block; margin: auto; width: .6rem; height: .6rem; + border: 2px solid #ffc965; border-radius: 50%; background: #0c2434; +} +#dkr-mod-library .dkr-record-mark[aria-pressed=true]::after { background: #ffc965; } +#dkr-mod-library .dkr-record-dates { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .25rem; } +#dkr-mod-library .dkr-record-history select { max-width: 100%; text-overflow: ellipsis; } +@media (max-width:850px) { + #dkr-mod-library .dkr-overall-layout { grid-template-columns: minmax(0,1fr); } +} +@media (max-width:480px) { + #dkr-mod-library .dkr-points dl { grid-template-columns: minmax(0,1fr); } + #dkr-mod-library .dkr-overall-table button { padding-inline: .35rem; } +} diff --git a/runtime-recomp/src/game/mod_library/website/assets/replay-format.js b/runtime-recomp/src/game/mod_library/website/assets/replay-format.js index 335e152f..eeff9fd2 100644 --- a/runtime-recomp/src/game/mod_library/website/assets/replay-format.js +++ b/runtime-recomp/src/game/mod_library/website/assets/replay-format.js @@ -1,37 +1,138 @@ -// DKRREPL1 stores an UTF-8 manifest and one applied controller sample per 60 Hz tick. +// DKRREPL2 stores one applied controller sample per 30 Hz update. The race +// result ends at finishTick, and optional neutral input extends playback. // The file is untrusted evidence. Only native re-simulation can verify its claims. -export const MAX_REPLAY_BYTES = 1024 * 1024; +export const MAX_REPLAY_BYTES = 3 * 1024 * 1024; +export const ADVENTURE_RULES = 'adventure-us80-7'; +const originalRouteRules = 'adventure-us80-6'; +const milestoneRules = 'adventure-us80-5'; +const oldAdventureRules = [originalRouteRules,milestoneRules,'adventure-us80-4','adventure-us80-3','adventure-us80-2','adventure-us80-1']; +const tracksCategories = ['all-trophy-races-dino-first','all-trophy-races-ffl-first','car-percent','hover-percent','plane-percent']; +export const adventureCategories = ['any-percent','100-percent','all-trophy-races', + 'all-bosses','all-minigames','tt-amulet-no-wrong-warp','any-percent-glitchless',...tracksCategories]; +const adventureKeys = new Set(['board','engine','ruleset','releaseHash','rom','platform','arch','ticks', + 'finishTick','clockTicks','startSeed','checkpoints','notes','ticket','practice','category','splits']); export const replayHash = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value); export const replayId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,96}$/.test(value); const decoder = new TextDecoder('utf-8', { fatal: true }); const manifestKeys = new Set(['board', 'engine', 'ruleset', 'releaseHash', 'rom', 'platform', 'arch', 'ticks', 'clockTicks', 'startSeed', 'checkpoints', 'splits', 'notes']); +const rankedKeys = new Set([...manifestKeys, 'ticket', 'practice', 'racer', 'finishTick', 'course', 'vehicle', 'trackId', 'trackHash', 'laps']); +export const CUSTOM_RULES = 'custom-time-trial-us80-1'; +export const CUSTOM_VARIABLE_LAPS_RULES = 'custom-time-trial-us80-2'; +export const ancientLakeRacers = [ + ['ancient-lake-car-krunch', 'Krunch'], ['ancient-lake-car-bumper', 'Bumper'], + ['ancient-lake-car-tiptup', 'Tiptup'], ['ancient-lake-car-conker', 'Conker'], + ['ancient-lake-car-timber', 'Timber'], ['ancient-lake-car-banjo', 'Banjo'], + ['ancient-lake-car-drumstick', 'Drumstick'], ['ancient-lake-car-pipsy', 'Pipsy'], + ['ancient-lake-car-tt', 'T.T.'], ['ancient-lake-car', 'Diddy'] +]; +export const rankedTicket = value => typeof value === 'string' && /^[A-Za-z0-9_-]{24}\.[0-9]{1,12}\.[a-f0-9]{64}$/.test(value); const tick = (value, maximum) => Number.isInteger(value) && value > 0 && value <= maximum; export function parseReplay(bytes) { const invalid = () => { throw new Error('Choose a valid DKR-R replay made with a supported build.'); }; if (bytes.byteLength < 16 || bytes.byteLength > MAX_REPLAY_BYTES || - decoder.decode(bytes.subarray(0, 8)) !== 'DKRREPL1') invalid(); + !['DKRREPL1', 'DKRREPL2'].includes(decoder.decode(bytes.subarray(0, 8)))) invalid(); + const native = bytes[7] === 50; const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const size = view.getUint32(8, true); - if (size < 2 || size > 16384 || size > bytes.byteLength - 16) invalid(); + if (size < 2 || size > 65536 || size > bytes.byteLength - 16) invalid(); const manifest = JSON.parse(decoder.decode(bytes.subarray(12, 12 + size))); + if (native && [ADVENTURE_RULES, ...oldAdventureRules].includes(manifest?.ruleset)) { + if (!validAdventure(manifest, bytes, size)) invalid(); + return manifest; + } + if (size > 16384 || bytes.byteLength > 1024 * 1024) invalid(); + if (native && manifest?.practice === true) { + if (!validNative(manifest, bytes, size)) invalid(); + return manifest; + } if (!manifest || Array.isArray(manifest) || typeof manifest !== 'object' || - Object.keys(manifest).some(key => !manifestKeys.has(key)) || + Object.keys(manifest).some(key => !(native ? rankedKeys : manifestKeys).has(key)) || + (native && (manifest.practice !== false || !rankedTicket(manifest.ticket) || + !validNative(manifest, bytes, size))) || !replayId(manifest.board) || !replayHash(manifest.engine) || !replayId(manifest.ruleset) || (manifest.releaseHash !== null && !replayHash(manifest.releaseHash)) || ![77, 80].includes(manifest.rom) || !['windows', 'linux'].includes(manifest.platform) || !['x86_64', 'aarch64'].includes(manifest.arch) || - !tick(manifest.ticks, 216000) || !tick(manifest.clockTicks, manifest.ticks) || + !tick(manifest.ticks, 216000) || !tick(manifest.clockTicks, manifest.ticks * (native ? 2 : 1)) || !Number.isInteger(manifest.startSeed) || manifest.startSeed < 0 || manifest.startSeed > 0xffffffff || bytes.byteLength !== 12 + size + 4 * manifest.ticks || (manifest.notes !== undefined && (typeof manifest.notes !== 'string' || manifest.notes.length > 600))) invalid(); const { ticks, clockTicks, checkpoints, splits } = manifest; - if (!Array.isArray(checkpoints) || checkpoints.length !== Math.ceil(ticks / 600)) invalid(); + const finish = native ? manifest.finishTick ?? ticks : ticks; + if (!Array.isArray(checkpoints) || checkpoints.length !== Math.ceil(finish / 600)) invalid(); if (checkpoints.some((entry, index) => !Array.isArray(entry) || entry.length !== 2 || - entry[0] !== Math.min((index + 1) * 600, ticks) || !replayHash(entry[1]))) invalid(); + entry[0] !== Math.min((index + 1) * 600, finish) || !replayHash(entry[1]))) invalid(); if (!Array.isArray(splits) || splits.length < 1 || splits.length > 32 || splits.at(-1) !== clockTicks || splits.some((value, index) => !tick(value, clockTicks) || (index && value <= splits[index - 1]))) invalid(); return manifest; } + +function validAdventure(manifest, bytes, size) { + const { ticks, clockTicks, checkpoints, category } = manifest; + const splits = manifest.splits; + const routeSplits = [ADVENTURE_RULES, originalRouteRules].includes(manifest.ruleset); + const nativeSplits = routeSplits || manifest.ruleset === milestoneRules; + const categories = routeSplits ? adventureCategories : adventureCategories.slice(0, nativeSplits ? 6 : 3); + const tracks = routeSplits && (tracksCategories.includes(category) || + (manifest.ruleset === ADVENTURE_RULES && ['all-trophy-races','all-minigames'].includes(category))); + const start = tracks ? 'Start' : 'Overworld'; + const uniqueLabels = new Set(); + const validSplits = nativeSplits ? + Array.isArray(splits) && splits.length >= 2 && splits.length <= 64 && + splits.every((entry, i) => { + if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string' || + !/^[A-Za-z0-9 .%-]{1,64}$/.test(entry[0]) || uniqueLabels.has(entry[0]) || + !tick(entry[1], clockTicks) || entry[1] % 2 || (i && entry[1] < splits[i-1][1])) return false; + uniqueLabels.add(entry[0]); + return true; + }) && splits[0][0] === start && splits[0][1] === 2 && splits.at(-1)[0] === 'Finish' && splits.at(-1)[1] === clockTicks : + splits === undefined; + return Object.keys(manifest).every(key => adventureKeys.has(key)) && + validSplits && categories.includes(category) && + (manifest.rom === 77 || manifest.rom === 80) && manifest.startSeed === 0x444b5252 && + tick(ticks, 648000) && ticks === manifest.finishTick && tick(clockTicks, 2 * ticks) && + clockTicks % 2 === 0 && bytes.byteLength === 12 + size + 4 * ticks && + Array.isArray(checkpoints) && checkpoints.length === Math.ceil(ticks / 1800) && + checkpoints.every((entry, i) => Array.isArray(entry) && entry.length === 2 && + entry[0] === Math.min((i + 1) * 1800, ticks) && replayHash(entry[1])) && + (manifest.notes === undefined || (typeof manifest.notes === 'string' && manifest.notes.length <= 600)) && + (manifest.practice === true || + (manifest.practice === false && [ADVENTURE_RULES, ...oldAdventureRules.slice(0,4)].includes(manifest.ruleset) && + manifest.releaseHash === null && + manifest.board === 'adventure-' + category && replayHash(manifest.engine) && rankedTicket(manifest.ticket) && + ['windows','linux'].includes(manifest.platform) && manifest.arch === 'x86_64')); +} + +function validNative(manifest, bytes, size) { + const { ticks, clockTicks, checkpoints, splits } = manifest; + const finish = manifest.finishTick ?? ticks; + const racer = manifest.racer ?? 9; + const legacy = manifest.ruleset === 'ancient-lake-us80-practice-2'; + const variable = manifest.ruleset === CUSTOM_VARIABLE_LAPS_RULES; + const custom = variable || manifest.ruleset === CUSTOM_RULES; + const laps = variable ? manifest.laps : 3; + if (variable ? (!tick(laps, 5) || laps === 3) : manifest.laps !== undefined) return false; + const vehicle = ['car','hovercraft','plane'].includes(manifest.vehicle); + if (!custom && (manifest.trackId !== undefined || manifest.trackHash !== undefined)) return false; + const target = custom ? manifest.course === undefined && replayId(manifest.trackId) && + replayHash(manifest.trackHash) && vehicle && (manifest.practice || replayHash(manifest.releaseHash)) : + legacy ? manifest.course === undefined && manifest.vehicle === undefined : + manifest.ruleset === 'vanilla-time-trial-us80-1' && + typeof manifest.course === 'string' && /^[a-z][a-z0-9-]{1,47}$/.test(manifest.course) && + vehicle && + (manifest.course !== 'ancient-lake' || manifest.vehicle !== 'car'); + return (manifest.rom === 77 || manifest.rom === 80) && manifest.startSeed === 0x444b5252 && target && + Number.isInteger(racer) && racer >= 0 && racer < ancientLakeRacers.length && + tick(finish, 54000) && tick(ticks, finish + 210) && ticks >= finish && + tick(clockTicks, 2 * finish) && clockTicks % 2 === 0 && + bytes.byteLength === 12 + size + 4 * ticks && + bytes.subarray(12 + size + 4 * finish).every(value => value === 0) && + Array.isArray(checkpoints) && checkpoints.length === Math.ceil(finish / 600) && + checkpoints.every((entry, i) => Array.isArray(entry) && entry.length === 2 && + entry[0] === Math.min((i + 1) * 600, finish) && replayHash(entry[1])) && + Array.isArray(splits) && splits.length === laps && splits.at(-1) === clockTicks && + splits.every((value, i) => tick(value, clockTicks) && value % 2 === 0 && (!i || value > splits[i - 1])); +} diff --git a/runtime-recomp/src/game/mod_library/website/index.html b/runtime-recomp/src/game/mod_library/website/index.html index eb3867a7..ba938cdc 100644 --- a/runtime-recomp/src/game/mod_library/website/index.html +++ b/runtime-recomp/src/game/mod_library/website/index.html @@ -7,14 +7,14 @@ - + DKR-R Mod Library - + @@ -22,9 +22,10 @@ - - - + + + +
diff --git a/runtime-recomp/src/game/mod_library/website/privacy.html b/runtime-recomp/src/game/mod_library/website/privacy.html index 392fee53..16b1a8f8 100644 --- a/runtime-recomp/src/game/mod_library/website/privacy.html +++ b/runtime-recomp/src/game/mod_library/website/privacy.html @@ -15,6 +15,7 @@

What we keep

Ratings, reviews and datesHelp players choose mods and keep one rating per account for each mod.Visitors when the review is visible. Hidden reviews remain available to their author and staff. Mod requests and repliesCheck a suggested mod and tell you the outcome.The requester and staff. Private staff notes are visible only to staff. Online player count and public lobby detailsShow how many signed-in players are connected, the number of active accounts, peak activity, and which lobbies are open to the public.Visitors see aggregate counts and peak times, plus public lobby titles and available places. Private lobbies and join credentials stay in the launcher. +Submission notifications and read statusTell you when your mod or run changes status and remember which notices you have read.You can see updates for your own submissions. Moderators and administrators can see items in their review queues. Speedrun replays, game inputs and run detailsCheck the time, ruleset, ROM revision, track version, platform and recorded inputs before a run is published.You and authorised reviewers see pending runs. Visitors can download published replays and see the display name on the leaderboard. Temporary sign-in records, session hashes and optional remembered-device hashesComplete sign-in and protect account actions.The private account service. Staff upload records, filenames, file sizes, transfer checksums and statusResume interrupted transfers and connect completed files to the library.The private library service and authorised staff. Completed mod packages and cover images are served publicly by the web host. @@ -40,6 +41,7 @@

Requests, retention and deletion

The browser uses a fingerprint of a selected file's size and sample bytes to help match it when resuming an upload. It also checks the previously accepted file chunks against their stored checksums before resuming. These checks identify file contents, not your device. The website does not save the selected file's bytes in browser storage. Deleting a staff account removes the account link from retained upload records; it does not remove files used by published mods.

Published and rejected requests, published draft history and staff activity logs are removed after 180 days by scheduled cleanup. Unfinished requests and unpublished drafts stay available while work is pending. Expired sign-in, session and remembered-device records are removed by scheduled cleanup; expired credentials stop working immediately even before that cleanup runs.

You can delete your website account from account settings. This removes its Discord identity mapping, sessions, remembered devices, ratings, reviews, comments, comment reports and review reports you submitted and your mod requests. In retained staff history, your account name is replaced with “Deleted account”. Published mods and their creator credits stay in the catalogue unless staff remove or update them separately. An administrator must leave another active administrator before deleting their own account.

+

Your submission notifications are kept for 90 days. Staff queue notifications stay available until the related review leaves the queue. Deleting your account removes your notification read state.

Deleting your account removes your runs from the leaderboard and makes their replay files unavailable through the website. Scheduled cleanup then removes those files and clears rejected submissions after 30 days. Private provider backups and infrastructure records can have their own retention periods. If you sign in again after deletion, a new website account is created.

Please keep personal information out of public reviews and comments. Mod requests are shared with the team that reviews them; include only the release information and links they need.

Questions or corrections

diff --git a/runtime-recomp/src/game/mod_store.cpp b/runtime-recomp/src/game/mod_store.cpp index bfacc562..54e6b182 100644 --- a/runtime-recomp/src/game/mod_store.cpp +++ b/runtime-recomp/src/game/mod_store.cpp @@ -7,9 +7,12 @@ #include "linux_keyring.hpp" #include "store_vehicle_adapter.hpp" #include "mod_store.hpp" +#include "cloud_saves/progress.hpp" #include "mod_store_install.hpp" +#include "mods/magic_code_package.hpp" #include "stb/stb_image.h" #include "updates/update_core.hpp" +#include "time_trial/ghost_file.hpp" #include #include #include @@ -50,6 +53,7 @@ #define DKR_PROFILE_WITH_KEYRING 1 #include "online_profile/linux_device_store.hpp" #include "atomic_snapshot.hpp" +#include "save_manager.hpp" namespace dkr::store { namespace { @@ -64,6 +68,9 @@ struct Error : std::runtime_error { Error(std::string message, unsigned s = 0, Json context = Json::object()) : std::runtime_error(std::move(message)), status(s), details(std::move(context)) {} }; +struct TransportFailure : Error { + using Error::Error; +}; std::string lower(std::string value) { for (auto& c : value) if (c >= 'A' && c <= 'Z') @@ -192,7 +199,16 @@ struct Request { std::uint64_t offset = 0, limit = MaxJson; unsigned timeout = 12000; std::string online_instance; + unsigned test_port = 0; }; +constexpr auto kReplayLimit = 3 * 1024 * 1024; +std::string local_ranked_origin(unsigned port) { + return "http://127.0.0.1:" + std::to_string(port); +} +bool local_ranked_request(const Request& request) { + return request.test_port > 1023 && request.test_port <= 65535 && + prefix(request.url, local_ranked_origin(request.test_port) + "/v1/speedruns"); +} using Sink = std::function; #ifdef _WIN32 @@ -233,16 +249,19 @@ std::string header(HINTERNET request, DWORD field) { return out; } Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { - if (!trusted_url(r.url, prefix(r.url, Api))) + const bool loopback = local_ranked_request(r); + if (!loopback && !trusted_url(r.url, prefix(r.url, Api))) throw Error("The library returned an unapproved file address."); auto url = wide(r.url); URL_COMPONENTS parts{}; parts.dwStructSize = sizeof(parts); parts.dwHostNameLength = parts.dwUrlPathLength = parts.dwExtraInfoLength = DWORD(-1); - if (!WinHttpCrackUrl(url.c_str(), DWORD(url.size()), 0, &parts) || parts.nScheme != INTERNET_SCHEME_HTTPS || - parts.nPort != 443) + if (!WinHttpCrackUrl(url.c_str(), DWORD(url.size()), 0, &parts) || + parts.nScheme != (loopback ? INTERNET_SCHEME_HTTP : INTERNET_SCHEME_HTTPS) || + parts.nPort != (loopback ? r.test_port : 443U)) throw Error("Use the secure library address."); - Internet session{WinHttpOpen(L"DKR-R-ModStore/1.0.7-beta8", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, + Internet session{WinHttpOpen(L"DKR-R-ModStore/1.0.7-beta8", + loopback ? WINHTTP_ACCESS_TYPE_NO_PROXY : WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0)}; if (!session.h) throw Error("The secure connection could not start."); @@ -251,16 +270,16 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { #ifdef WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3 tls |= WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; #endif - if (!WinHttpSetOption(session, WINHTTP_OPTION_SECURE_PROTOCOLS, &tls, sizeof(tls))) + if (!loopback && !WinHttpSetOption(session, WINHTTP_OPTION_SECURE_PROTOCOLS, &tls, sizeof(tls))) throw Error("The secure connection could not start."); std::wstring host(parts.lpszHostName, parts.dwHostNameLength), path(parts.lpszUrlPath, parts.dwUrlPathLength); if (parts.dwExtraInfoLength) path.append(parts.lpszExtraInfo, parts.dwExtraInfoLength); - Internet connection{WinHttpConnect(session, host.c_str(), 443, 0)}; + Internet connection{WinHttpConnect(session, host.c_str(), parts.nPort, 0)}; const auto method = wide(r.method); Internet request{connection.h ? WinHttpOpenRequest(connection, method.c_str(), path.c_str(), nullptr, WINHTTP_NO_REFERER, - WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) + WINHTTP_DEFAULT_ACCEPT_TYPES, loopback ? 0 : WINHTTP_FLAG_SECURE) : nullptr}; if (!request.h) throw Error("The library connection could not open."); @@ -269,8 +288,9 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { DWORD disable = WINHTTP_DISABLE_COOKIES; WinHttpSetOption(request, WINHTTP_OPTION_DISABLE_FEATURE, &disable, sizeof(disable)); std::string headers = "Accept: */*\r\n"; - if (prefix(r.url, Api)) { - headers += "Origin: https://positron-portal.com\r\n"; + if (loopback || prefix(r.url, Api)) { + if (!loopback) + headers += "Origin: https://positron-portal.com\r\n"; if (!r.online_instance.empty()) headers += "X-DKRR-Instance: " + r.online_instance + "\r\n"; if (!r.token.empty()) { @@ -283,7 +303,7 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { throw Error("Credentials cannot be sent to a file host."); headers += "Referer: https://positron-portal.com/dkr-r/index.html\r\n"; } - if (r.method == "POST") + if (r.method == "POST" || r.method == "PUT") headers += "Content-Type: " + r.type + "\r\n"; if (r.offset) { headers += "Range: bytes=" + std::to_string(r.offset) + "-\r\n"; @@ -291,12 +311,13 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { headers += "If-Range: " + r.etag + "\r\n"; } auto wh = wide(headers); - if (stop.stop_requested() || - !WinHttpSendRequest(request, wh.c_str(), DWORD(wh.size()), + if (stop.stop_requested()) + throw Error("Transfer paused."); + if (!WinHttpSendRequest(request, wh.c_str(), DWORD(wh.size()), r.body.empty() ? WINHTTP_NO_REQUEST_DATA : const_cast(r.body.data()), DWORD(r.body.size()), DWORD(r.body.size()), 0) || !WinHttpReceiveResponse(request, nullptr)) - throw Error("Could not reach the library. Check your connection and retry."); + throw TransportFailure("Could not reach the library. Check your connection and retry."); Response response; response.url = r.url; DWORD bytes = sizeof(response.status); @@ -323,7 +344,7 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { throw Error("Transfer paused."); DWORD read = 0; if (!WinHttpReadData(request, buffer.data(), DWORD(buffer.size()), &read)) - throw Error("The connection was interrupted. Retry to continue."); + throw TransportFailure("The connection was interrupted. Retry to continue."); if (!read) break; if (read > r.limit - total) @@ -344,7 +365,8 @@ Response http_once(const Request&, std::stop_token, const Sink&) { } #else Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { - if (!trusted_url(r.url, prefix(r.url, Api))) + const bool loopback = local_ranked_request(r); + if (!loopback && !trusted_url(r.url, prefix(r.url, Api))) throw Error("Unapproved library address."); static const bool initialized = [] { return curl_global_init(CURL_GLOBAL_DEFAULT) == CURLE_OK; }(); if (!initialized) @@ -373,8 +395,9 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { }; Transfer transfer{&r, &out, &sink, stop}; auto add = [&](std::string value) { cleanup.headers = curl_slist_append(cleanup.headers, value.c_str()); }; - if (prefix(r.url, Api)) { - add("Origin: https://positron-portal.com"); + if (loopback || prefix(r.url, Api)) { + if (!loopback) + add("Origin: https://positron-portal.com"); if (!r.online_instance.empty()) add("X-DKRR-Instance: " + r.online_instance); if (!r.token.empty() && r.token.size() == 43 && identifier(r.token)) @@ -384,7 +407,8 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { throw Error("Credentials cannot be sent to a file host."); add("Referer: https://positron-portal.com/dkr-r/index.html"); } - if (r.method == "POST") + const bool sends_body = r.method == "POST" || r.method == "PUT"; + if (sends_body) add("Content-Type: " + r.type); if (r.offset && !r.etag.empty() && r.etag.find_first_of("\r\n") == r.etag.npos) add("If-Range: " + r.etag); @@ -396,11 +420,15 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { curl_easy_setopt(cleanup.curl, CURLOPT_LOW_SPEED_TIME, 15L); curl_easy_setopt(cleanup.curl, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(cleanup.curl, CURLOPT_FOLLOWLOCATION, 0L); - curl_easy_setopt(cleanup.curl, CURLOPT_PROTOCOLS_STR, "https"); - if (r.method == "POST") { + curl_easy_setopt(cleanup.curl, CURLOPT_PROTOCOLS_STR, loopback ? "http" : "https"); + if (loopback) + curl_easy_setopt(cleanup.curl, CURLOPT_PROXY, ""); + if (sends_body) { curl_easy_setopt(cleanup.curl, CURLOPT_POST, 1L); curl_easy_setopt(cleanup.curl, CURLOPT_POSTFIELDS, r.body.data()); curl_easy_setopt(cleanup.curl, CURLOPT_POSTFIELDSIZE_LARGE, curl_off_t(r.body.size())); + if (r.method == "PUT") + curl_easy_setopt(cleanup.curl, CURLOPT_CUSTOMREQUEST, "PUT"); } std::string range; if (r.offset) { @@ -481,7 +509,7 @@ Response http_once(const Request& r, std::stop_token stop, const Sink& sink) { if (transfer.error) std::rethrow_exception(transfer.error); if (code != CURLE_OK) - throw Error("The library connection was interrupted. Retry to continue."); + throw TransportFailure("The library connection was interrupted. Retry to continue."); return out; } #endif @@ -494,7 +522,7 @@ Response http(Request request, std::stop_token stop, const Sink& sink = {}) { if (response.status != 301 && response.status != 302 && response.status != 303 && response.status != 307 && response.status != 308) return response; - if (hops == 3 || request.method != "GET" || !request.token.empty() || prefix(request.url, Api)) + if (hops == 3 || request.test_port || request.method != "GET" || !request.token.empty() || prefix(request.url, Api)) throw Error("The library returned an unsupported redirect.", response.status); auto next = response.location; if (next.starts_with('/') && !next.starts_with("//")) @@ -638,6 +666,7 @@ struct Service::Impl { std::mutex download_persist_mutex; std::condition_variable_any cv; Snapshot state; + std::mutex cloud_saves_mutex; dkr::runtime::AtomicSnapshot published{std::make_shared()}; std::filesystem::path root; std::string version, token, device, browser; @@ -665,8 +694,11 @@ struct Service::Impl { std::map preparation_stops; #include "mod_store/community_service.inl" // Workers are last: joined before the objects captured by their callbacks. - std::jthread worker, image_worker, download_worker, auth_worker; + std::jthread worker, image_worker, download_worker, auth_worker, cloud_save_worker; void publish() { + const bool cloud_active = !token.empty() && !state.cloud_saves_account.empty() && + state.cloud_saves_account == text(state.user, "id", 160); + cloud_saves::progress_writes.account(cloud_active ? std::optional(account) : std::nullopt); community_fence(); ++state.generation; published.store(std::make_shared(state)); @@ -713,6 +745,24 @@ struct Service::Impl { } catch (...) { /* A diagnostic must never replace the original failure. */ } } + Request ranked_request(std::string path, bool authenticated = false) { + const auto local = read_json(root.parent_path() / "ranked-local.json"); + const auto port = local.find("port"); + if (port != local.end() && port->is_number_integer()) { + const auto value = port->get(); + auto credential = text(local, "token", 43); + if (value < 1024 || value > 65535 || (authenticated && (credential.size() != 43 || !identifier(credential)))) + throw Error("The local ranked test profile is invalid."); + Request request{local_ranked_origin(unsigned(value)) + path, "GET", {}, + authenticated ? std::move(credential) : std::string{}}; + request.test_port = unsigned(value); + return request; + } + std::lock_guard lock(mutex); + if (authenticated && token.empty()) + throw Error("Sign in to the Mod Library to submit a run."); + return {std::string(Api) + path, "GET", {}, authenticated ? token : std::string{}}; + } Json get(std::string path, std::stop_token stop, bool private_request = false) { std::string credential; { @@ -752,6 +802,8 @@ struct Service::Impl { token.clear(); ++account; state.user = nullptr; + state.cloud_sync = cloud_saves::SyncStatus::Idle; + state.cloud_saves_status.clear(); state.personal = Json::object(); state.staff = Json::object(); state.admin = Json::object(); @@ -1269,6 +1321,7 @@ Service::~Service() { p.image_worker.request_stop(); p.download_worker.request_stop(); p.auth_worker.request_stop(); + p.cloud_save_worker.request_stop(); p.community_tracking_worker.request_stop(); p.cv.notify_all(); } @@ -1280,6 +1333,7 @@ std::string download_key(const std::string& item, const std::string& release, co return item + "_" + release + (instance.empty() ? "" : "_" + instance); } void Service::gameplay(bool active) { + cloud_saves::progress_writes.gameplay(active); dkr::storage::gameplay(active); auto& p = *impl_; { @@ -1310,10 +1364,12 @@ void Service::configure(const std::filesystem::path& config, std::string version p.image_worker.request_stop(); p.download_worker.request_stop(); p.auth_worker.request_stop(); + p.cloud_save_worker.request_stop(); p.community_tracking_worker.request_stop(); p.cv.notify_all(); for (auto* worker : - {&p.worker, &p.image_worker, &p.download_worker, &p.auth_worker, &p.community_tracking_worker}) + {&p.worker, &p.image_worker, &p.download_worker, &p.auth_worker, &p.cloud_save_worker, + &p.community_tracking_worker}) if (worker->joinable()) worker->join(); }); @@ -1322,15 +1378,19 @@ void Service::configure(const std::filesystem::path& config, std::string version p.worker = std::jthread([&p](std::stop_token stop) { p.run(stop); }); p.image_worker = std::jthread([&p](std::stop_token stop) { p.image_run(stop); }); p.download_worker = std::jthread([&p](std::stop_token stop) { p.download_run(stop); }); + p.cloud_save_worker = std::jthread([this](std::stop_token stop) { publish_progress(stop); }); p.community_tracking_worker = std::jthread([&p](std::stop_token stop) { p.community_tracking(stop); }); p.queue([&p](std::stop_token stop) { const auto preferences = read_json(p.root / "preferences.json"), cached = read_json(p.root / "catalogue.json"); + const auto cloud = read_json(p.root / "cloud-saves.json"); const auto saved = read_json(p.root / "downloads.json"); const auto receipts = read_json(p.root / "installations.json"); auto restored = dkr::store::history::restore(saved, receipts, [&](const std::string& path) { return dkr::store::history::member_present(p.root.parent_path(), path); }); p.update([&](Snapshot& s) { + if (cloud.value("enabled", false)) + s.cloud_saves_account = text(cloud, "account", 160); if (preferences.value("layout", 0) == 1) s.layout = 1; s.remember = preferences.contains("remember") && preferences["remember"] == true; @@ -1389,8 +1449,10 @@ void Service::refresh() { auto& p = *impl_; p.queue([&p](std::stop_token stop) { p.refresh(stop); }); } -void Service::load_leaderboards(std::string board, std::string cursor) { - if ((!board.empty() && !identifier(board)) || (!cursor.empty() && !identifier(cursor))) +void Service::load_leaderboards(std::string cursor, std::optional track) { + if ((!cursor.empty() && !identifier(cursor)) || + (track && (!identifier(track->id) || (!track->vehicle.empty() && !identifier(track->vehicle)) || + (!track->racer.empty() && !identifier(track->racer))))) return; auto& p = *impl_; { @@ -1398,32 +1460,54 @@ void Service::load_leaderboards(std::string board, std::string cursor) { if (!p.configured || p.state.speedrun_loading) return; p.state.speedrun_loading = true; - p.state.speedrun_request = board; p.state.speedrun_error.clear(); p.publish(); } - if (!p.queue([&p, board = std::move(board), cursor = std::move(cursor)](std::stop_token stop) { + if (!p.queue([&p, cursor = std::move(cursor), track = std::move(track)](std::stop_token stop) { try { - const auto url = board.empty() - ? "/v1/speedruns" + (cursor.empty() ? std::string{} : "?cursor=" + cursor) - : "/v1/speedruns/boards/" + board; - auto data = p.get(url, stop); - if (board.empty() && (!data.contains("boards") || !data["boards"].is_array() || - !data.contains("customTracks") || !data["customTracks"].is_array())) + std::string url = "/v1/speedruns"; + if (track) { + const char* kind = track->full_game ? "?kind=full-game" : + track->custom ? "?kind=custom" : "?kind=vanilla"; + url += "/tracks/" + track->id + kind; + if (!track->vehicle.empty()) + url += "&vehicle=" + track->vehicle; + if (!track->racer.empty()) + url += "&racer=" + track->racer; + if (track->best_lap) + url += "&score=lap"; + if (track->offset) + url += "&offset=" + std::to_string(track->offset); + } else if (!cursor.empty()) { + url += "?cursor=" + cursor; + } + auto data = document(p.ranked_request(url), stop); + if (!track && (!data.contains("boards") || !data["boards"].is_array() || + !data.contains("customTracks") || !data["customTracks"].is_array())) throw Error("The leaderboard service returned an invalid track list."); - if (!board.empty() && (!data.contains("board") || !data["board"].is_object() || - !data.contains("entries") || !data["entries"].is_array())) + if (track && (!data.contains("track") || !data["track"].is_object() || + data["track"].value("id", std::string{}) != track->id || + !data.contains("entries") || !data["entries"].is_array() || + !data.contains("vehicles") || !data["vehicles"].is_array() || + !data.contains("racers") || !data["racers"].is_array())) throw Error("The leaderboard service returned an invalid result list."); p.update([&](Snapshot& state) { state.speedrun_loading = false; - if (!board.empty()) { + if (track) { + if (track->offset && state.speedrun_board) { + Json combined = *state.speedrun_board; + for (auto& row : data["entries"]) + combined["entries"].push_back(std::move(row)); + data["entries"] = std::move(combined["entries"]); + data["history"] = std::move(combined["history"]); + } state.speedrun_board = std::make_shared(std::move(data)); return; } if (!cursor.empty() && state.speedrun_catalogue) { Json combined = *state.speedrun_catalogue; - for (auto& track : data["customTracks"]) - combined["customTracks"].push_back(std::move(track)); + for (auto& item : data["customTracks"]) + combined["customTracks"].push_back(std::move(item)); combined["nextCursor"] = data["nextCursor"]; data = std::move(combined); } @@ -1442,6 +1526,313 @@ void Service::load_leaderboards(std::string board, std::string cursor) { }); } } +Json Service::overall_rankings(const std::string& player, unsigned offset) { + if (!player.empty() && !identifier(player)) + throw Error("Invalid leaderboard player."); + auto path = std::string("/v1/speedruns/overall"); + if (!player.empty()) + path += "/" + player + "?offset=" + std::to_string(offset); + auto data = document(impl_->ranked_request(path), {}); + if (!data.is_object() || data.value("scoringVersion", 0) != 1 || + !(player.empty() ? data.contains("players") && data["players"].is_array() + : data.contains("player") && data["player"].is_object() && + text(data["player"], "id", 96) == player && data.contains("events") && + data["events"].is_array())) + throw Error("Overall rankings are unavailable. Try refreshing."); + return data; +} +Json Service::ranked_attempt(std::string board) { + auto request = impl_->ranked_request("/v1/speedruns/attempts", true); + request.method = "POST"; + request.body = Json{{"board", std::move(board)}}.dump(); + return document(request, {}); +} +Json Service::adventure_record(const std::string& category) { + if (!identifier(category)) + throw Error("Invalid Full Game category."); + return document(impl_->ranked_request("/v1/speedruns/tracks/" + category + "?kind=full-game", false), {}); +} +Json Service::submit_ranked_replay(const std::filesystem::path& path, bool link_local) { + const auto file = dkr::mods::read_file(path, kReplayLimit); + auto request = impl_->ranked_request(link_local ? "/v1/speedruns/runs/claim" : "/v1/speedruns/runs", true); + request.method = "POST"; + request.type = "application/octet-stream"; + request.body.assign(file.begin(), file.end()); + return document(request, {}); +} +Json Service::ranked_runs(bool review) { + return document(impl_->ranked_request(review ? "/v1/speedruns/review" : "/v1/speedruns/mine", true), {}); +} +std::vector Service::published_replay_times() { + auto request = impl_->ranked_request("/v1/speedruns/mine/published", true); + const auto route = request.url; + std::vector times; + for (;;) { + const auto page = document(request, {}); + const auto& scores = page.at("scores"); + const bool more = page.at("more").get(); + if (!scores.is_array() || scores.size() > 256 || (more && scores.empty())) + throw Error("The leaderboard returned an invalid time page."); + for (const auto& score : scores) { + const auto board = text(score, "board", 96); + const auto& ticks = score.at("ticks"); + if (!identifier(board) || !ticks.is_number_integer() || ticks.get() <= 0) + throw Error("The leaderboard returned an invalid time."); + PublishedReplayTime time{board, ticks.get()}; + if (!times.empty() && times.back() >= time) + throw Error("The leaderboard returned an invalid time order."); + times.push_back(std::move(time)); + } + if (!more) + return times; + const auto& [board, ticks] = times.back(); + request.url = route + "?afterBoard=" + board + "&afterTicks=" + std::to_string(ticks); + } +} +void Service::review_ranked_run(const std::string& id, bool publish, std::string reason) { + if (!identifier(id)) + throw Error("Invalid replay ID."); + auto request = impl_->ranked_request("/v1/speedruns/runs/" + id + "/review", true); + request.method = "POST"; + Json review{{"decision", publish ? "published" : "rejected"}, {"reason", std::move(reason)}}; + if (publish) + review["evidence"] = "replay"; + request.body = review.dump(); + (void)document(request, {}); +} +void Service::save_ranked_replay(const std::string& id, const std::filesystem::path& destination, bool own_run) { + if (!identifier(id)) + throw Error("Invalid replay ID."); + auto request = impl_->ranked_request("/v1/speedruns/runs/" + id + "/replay", own_run); + request.limit = kReplayLimit; + const auto file = http(std::move(request), {}); + if (file.status != 200 || !file.body.starts_with("DKRREPL2")) + throw Error("The replay could not be downloaded."); + const dkr::mods::Bytes replay(file.body.begin(), file.body.end()); + dkr::mods::write_new_file(destination, replay); + try { + namespace trial = dkr::runtime::time_trial; + auto ghost_request = impl_->ranked_request("/v1/speedruns/runs/" + id + "/ghost", own_run); + ghost_request.limit = trial::kMaxPortableGhostBytes; + const auto ghost = http(std::move(ghost_request), {}); + if (ghost.status == 200 && ghost.body.starts_with(trial::portable_ghost_prefix(dkr::mods::sha256(replay)))) + dkr::mods::write_new_file(trial::portable_ghost_file(destination), + dkr::mods::Bytes(ghost.body.begin(), ghost.body.end())); + } catch (const std::exception&) { + // Older runs and temporarily unavailable ghosts are still playable from their replay. + } +} +void Service::set_cloud_saves(const std::string& account, bool enabled) { + auto& p = *impl_; + std::scoped_lock operation(p.cloud_saves_mutex); + std::lock_guard lock(p.mutex); + if (p.gameplay || account.empty() || p.token.empty() || text(p.state.user, "id") != account) + throw Error("Sign in with Discord and return to the launcher to change Cloud Saves."); + auto state = read_json(p.root / "cloud-saves.json"); + if (text(state, "account") != account || (enabled && !state.value("enabled", false))) + state = {{"account", account}, {"common", Json::object()}}; + state["enabled"] = enabled; + try { + write_json(p.root / "cloud-saves.json", state); + } catch (const std::exception&) { + p.state.cloud_sync = cloud_saves::SyncStatus::Error; + p.state.cloud_saves_status = "Could not save the Cloud Saves setting on this device."; + p.publish(); + throw; + } + p.state.cloud_sync = cloud_saves::SyncStatus::Idle; + p.state.cloud_saves_account = enabled ? account : std::string{}; + p.state.cloud_saves_status = enabled ? "Cloud Saves enabled for this device." : "Cloud Saves paused on this device."; + p.publish(); +} + +void Service::publish_progress(std::stop_token stop) { + while (auto batch = cloud_saves::progress_writes.take(stop)) { + std::string account; + { + std::lock_guard lock(impl_->mutex); + if (impl_->account != batch->account_generation) + continue; + account = impl_->state.cloud_saves_account; + } + try { + sync_cloud_saves(account, cloud_saves::SyncScope::PublishProgress, &*batch, stop); + } catch (const Error& error) { + if (!stop.stop_requested() && + (dynamic_cast(&error) || error.status >= 500 || error.status == 409)) + cloud_saves::progress_writes.retry(*batch); + } catch (const std::exception&) { + // The shared sync path publishes the failure for the launcher. + } + } +} + +void Service::sync_cloud_saves(const std::string& account, cloud_saves::SyncScope scope) { + sync_cloud_saves(account, scope, nullptr, {}); +} + +void Service::sync_cloud_saves(const std::string& account, cloud_saves::SyncScope scope, + const cloud_saves::ProgressBatch* progress, std::stop_token stop) { + namespace saves = dkr::runtime::saves; + using cloud_saves::Action; + using cloud_saves::SyncStatus; + auto& p = *impl_; + std::scoped_lock operation(p.cloud_saves_mutex); + std::string credential; + std::uint64_t generation; + { + std::lock_guard lock(p.mutex); + if (progress && progress->account_generation != p.account) + return; + if ((!progress && p.gameplay) || account.empty() || account != p.state.cloud_saves_account || + account != text(p.state.user, "id") || p.token.empty()) + throw Error("Enable Cloud Saves while signed in with Discord on this device."); + credential = p.token; + generation = p.account; + p.state.cloud_sync = SyncStatus::Syncing; + p.state.cloud_saves_status = "Syncing Cloud Saves..."; + p.publish(); + } + const auto check_account = [&] { + if (stop.stop_requested() || (!progress && p.gameplay) || generation != p.account || + account != p.state.cloud_saves_account || account != text(p.state.user, "id")) + throw Error("The signed-in account changed while syncing. Your local saves are still available."); + }; + unsigned uploaded = 0, downloaded = 0; + const auto reconcile = [&] { + constexpr std::string_view route = "/v1/launcher/cloud-saves"; + const auto make_request = [&](std::string suffix = {}) { + Request request{std::string(Api) + std::string(route) + std::move(suffix), "GET", {}, credential}; + request.timeout = 4500; + return request; + }; + auto state = read_json(p.root / "cloud-saves.json"); + if (text(state, "account") != account || !state.value("enabled", false)) + throw Error("Cloud Saves are disabled on this device."); + auto& common = state["common"]; + if (!common.is_object()) + common = Json::object(); + const auto inventory = document(make_request("?format=2"), stop); + if (text(inventory, "accountId") != account || !inventory.contains("saves") || !inventory["saves"].is_array() || + inventory["saves"].size() > saves::cloud_save_slots().size()) + throw Error("The Cloud Save service returned an invalid account or save inventory."); + std::map remote; + for (const auto& entry : inventory["saves"]) + if (!remote.emplace(text(entry, "key", 40), entry).second) + throw Error("Cloud Save inventory contains a duplicate save."); + + const bool modded_supported = inventory.value("moddedAdventure", false); + unsigned needs_recovery = 0, deferred = 0; + bool modded_unavailable = false; + for (const auto& slot : saves::cloud_save_slots()) { + if (!cloud_saves::includes_slot(scope, slot.key) || (progress && !progress->slots.contains(slot.key))) + continue; + const std::string key(slot.key); + if (key == "modded-adventure" && !modded_supported) { + modded_unavailable = true; + continue; + } + std::string error; + std::vector local; + if (!saves::read_cloud_save(key, local, error)) { + ++needs_recovery; + continue; + } + const auto found = remote.find(key); + const auto local_hash = local.empty() ? std::string{} : dkr::mods::sha256(local); + const auto cloud_hash = found == remote.end() ? std::string{} : text(found->second, "digest", 64); + const auto revision = found == remote.end() ? 0ULL : found->second.value("revision", 0ULL); + const auto size = found == remote.end() ? 0ULL : found->second.value("bytes", 0ULL); + if (found != remote.end() && (!hash_string(cloud_hash) || !revision || !size || size > slot.limit)) + throw Error("The cloud metadata for " + std::string(slot.label) + " is invalid."); + const auto action = cloud_saves::next_action(local_hash, cloud_hash, text(common, key.c_str(), 64), scope); + if (action == Action::Defer) { + ++deferred; + continue; + } + if (action == Action::None) { + if (!local_hash.empty()) + common[key] = local_hash; + continue; + } + + auto request = make_request("/" + key + "?revision=" + std::to_string(revision)); + { + std::lock_guard lock(p.mutex); + check_account(); + } + if (action == Action::Upload) { + request.method = "PUT"; + request.type = "application/octet-stream"; + request.body.assign(reinterpret_cast(local.data()), local.size()); + const auto result = document(request, stop); + if (text(result, "digest", 64) != local_hash || result.value("revision", 0ULL) != revision + 1) + throw Error("The cloud service did not confirm the uploaded save."); + common[key] = local_hash; + ++uploaded; + } else { + request.limit = slot.limit; + const auto result = http(request, stop); + const std::vector replacement(result.body.begin(), result.body.end()); + if (result.status != 200) + throw Error("The cloud image could not be downloaded. Sync again to retry.", result.status); + if (result.type != "application/octet-stream" || replacement.size() != size || + dkr::mods::sha256(replacement) != cloud_hash) + throw Error("The cloud image changed or could not be verified. Sync again to retry."); + std::lock_guard lock(p.mutex); + check_account(); + if (!saves::replace_cloud_save(key, local, replacement, error)) + throw Error(error); + common[key] = cloud_hash; + ++downloaded; + } + std::lock_guard lock(p.mutex); + check_account(); + write_json(p.root / "cloud-saves.json", state); + } + std::lock_guard lock(p.mutex); + check_account(); + write_json(p.root / "cloud-saves.json", state); + p.state.cloud_sync = + needs_recovery || modded_unavailable ? SyncStatus::Error : deferred ? SyncStatus::Idle : SyncStatus::Synced; + p.state.cloud_saves_status = uploaded || downloaded + ? "Cloud Saves synced. Downloaded " + std::to_string(downloaded) + + " and uploaded " + std::to_string(uploaded) + " save files." + : "Cloud Saves checked."; + if (needs_recovery) + p.state.cloud_saves_status += " Save Manager can help recover " + std::to_string(needs_recovery) + " local files."; + if (modded_unavailable) + p.state.cloud_saves_status += " Modded Adventure cloud sync is unavailable."; + if (deferred) + p.state.cloud_saves_status += scope == cloud_saves::SyncScope::PublishHostedOnline + ? " Newer cloud saves will be applied after leaving the lobby." + : " Newer cloud saves will be applied after play."; + p.publish(); + }; + try { + try { + reconcile(); + } catch (const Error& error) { + if (error.status != 409) + throw; + // Another device committed a newer revision. Recheck which copy to use. + reconcile(); + } + } catch (const std::exception& error) { + std::lock_guard lock(p.mutex); + if (generation == p.account && account == p.state.cloud_saves_account) { + const auto* http_error = dynamic_cast(&error); + p.state.cloud_sync = cloud_saves::sync_failure(dynamic_cast(&error) != nullptr, + http_error ? http_error->status : 0); + p.state.cloud_saves_status = p.state.cloud_sync == SyncStatus::Unreachable + ? "Could not reach Cloud Saves. Try again in a moment." + : error.what(); + p.publish(); + } + throw; + } +} + bool Service::refresh_names() { auto& p = *impl_; { @@ -1721,6 +2112,8 @@ void Service::login() { p.token = token; p.device = device; ++p.account; + p.state.cloud_sync = cloud_saves::SyncStatus::Idle; + p.state.cloud_saves_status.clear(); p.upload_proofs.clear(); p.state.personal = Json::object(); p.state.staff = Json::object(); @@ -1768,6 +2161,8 @@ void Service::logout() { ++p.account; p.browser.clear(); p.state.user = nullptr; + p.state.cloud_sync = cloud_saves::SyncStatus::Idle; + p.state.cloud_saves_status.clear(); p.state.personal = Json::object(); p.state.staff = Json::object(); p.state.admin = Json::object(); diff --git a/runtime-recomp/src/game/mod_store.hpp b/runtime-recomp/src/game/mod_store.hpp index 5b3c873f..3141b4e0 100644 --- a/runtime-recomp/src/game/mod_store.hpp +++ b/runtime-recomp/src/game/mod_store.hpp @@ -1,16 +1,24 @@ #pragma once +#include "cloud_saves/sync.hpp" #include #include #include #include #include #include +#include #include #include +#include #include +namespace dkr::cloud_saves { +struct ProgressBatch; +} + namespace dkr::store { using Json = nlohmann::json; +using PublishedReplayTime = std::pair; struct Download { std::string key, item, release, title, category, state = "Queued", error, digest, version, intent, instance; std::filesystem::path file; @@ -20,14 +28,22 @@ struct Image { unsigned width = 0, height = 0; std::vector rgba; }; +struct LeaderboardTrackQuery { + std::string id, vehicle, racer; + bool custom = false, best_lap = false; + unsigned offset = 0; + bool full_game = false; +}; struct Snapshot { std::shared_ptr items = std::make_shared(Json::array()); std::shared_ptr speedrun_catalogue, speedrun_board; - std::string speedrun_request, speedrun_error; + std::string speedrun_error; bool speedrun_loading = false; Json user = nullptr, personal = Json::object(), staff = Json::object(), admin = Json::object(); Json reviews = Json::object(), uploads = Json::array(), assets = Json::array(), upload = Json::object(); std::vector downloads; + std::string cloud_saves_account, cloud_saves_status; + cloud_saves::SyncStatus cloud_sync = cloud_saves::SyncStatus::Idle; std::string status, error, last_action; Json last_result; std::uint64_t generation = 0, mutation = 0; @@ -45,8 +61,18 @@ class Service { void configure(const std::filesystem::path&, std::string version); std::shared_ptr view() const; void refresh(); - void load_leaderboards(std::string board = {}, std::string cursor = {}); + void load_leaderboards(std::string cursor = {}, std::optional track = {}); + Json overall_rankings(const std::string& player = {}, unsigned offset = 0); + Json ranked_attempt(std::string board); + Json adventure_record(const std::string& category); + Json submit_ranked_replay(const std::filesystem::path&, bool link_local = false); + Json ranked_runs(bool review = false); + std::vector published_replay_times(); + void review_ranked_run(const std::string& id, bool publish, std::string reason); + void save_ranked_replay(const std::string& id, const std::filesystem::path& destination, bool own_run); void gameplay(bool active); + void set_cloud_saves(const std::string& account, bool enabled); + void sync_cloud_saves(const std::string& account, cloud_saves::SyncScope scope = cloud_saves::SyncScope::All); bool refresh_names(); void layout(int); void remember(bool); @@ -72,6 +98,10 @@ class Service { std::string take_browser_url(); private: + void sync_cloud_saves(const std::string& account, cloud_saves::SyncScope scope, + const cloud_saves::ProgressBatch* progress, std::stop_token stop); + void publish_progress(std::stop_token stop); + struct Impl; std::unique_ptr impl_; }; diff --git a/runtime-recomp/src/game/mod_store_style.inl b/runtime-recomp/src/game/mod_store_style.inl index 3784c585..71252659 100644 --- a/runtime-recomp/src/game/mod_store_style.inl +++ b/runtime-recomp/src/game/mod_store_style.inl @@ -95,15 +95,21 @@ std::string StoreSummary(const StoreJson& item) { } return value; } -int StoreTabLine(const std::vector& labels, int selected, float width, const char* id) { +int StoreTabLine(const std::vector& labels, int selected, float width, const char* id, + bool prefer_single_row = false) { if (labels.empty()) return 0; selected = std::clamp(selected, 0, int(labels.size()) - 1); + float normal_width = 8.F * static_cast(labels.size() - 1); + if (prefer_single_row) + for (const auto& label : labels) + normal_width += PaddockSectionTabWidth(label.c_str()); + const bool compact = prefer_single_row && normal_width > width; ImGui::PushID(id); const auto start = ImGui::GetCursorScreenPos(); float x = 0, y = 0, row_height = 0; for (int i = 0; i < int(labels.size()); ++i) { - const float size = std::min(width, PaddockSectionTabWidth(labels[i].c_str())); + const float size = std::min(width, PaddockSectionTabWidth(labels[i].c_str(), compact)); if (x > 0 && x + size > width) { x = 0; y += row_height + 8; @@ -111,12 +117,12 @@ int StoreTabLine(const std::vector& labels, int selected, float wid } ImGui::SetCursorScreenPos({start.x + x, start.y + y}); ImGui::PushID(i); - if (PaddockSectionTab((labels[i] + "###tab").c_str(), i == selected, size)) + if (PaddockSectionTab((labels[i] + "###tab").c_str(), i == selected, size, compact)) selected = i; StoreControlFocus(); row_height = std::max(row_height, ImGui::GetItemRectSize().y); ImGui::PopID(); - x += size + 8; + x += size + (compact ? 4.F : 8.F); } ImGui::SetCursorScreenPos({start.x, start.y + y + row_height + 16}); ImGui::PopID(); diff --git a/runtime-recomp/src/game/mod_store_ui.inl b/runtime-recomp/src/game/mod_store_ui.inl index 10849395..2c6eeac0 100644 --- a/runtime-recomp/src/game/mod_store_ui.inl +++ b/runtime-recomp/src/game/mod_store_ui.inl @@ -62,6 +62,7 @@ void StoreControlFocus() { g_mod_store.page_focus = id; } SDL_Renderer* g_mod_store_renderer = nullptr; +SDL_Texture* g_speedrunning_preview_texture = nullptr; bool g_store_in_game = false; constexpr std::array kStoreCategoryNames = { "All", "Tracks", "Characters", "Vehicles", "Custom Magic Codes", "Texture packs"}; @@ -167,6 +168,8 @@ int StoreCombo(const char* id, int current, const std::vector& raw_ #include "store_polish_controls.inl" void ReleaseModStoreTextures() { ReleaseVehicleTextures(); + if (g_speedrunning_preview_texture) + SDL_DestroyTexture(std::exchange(g_speedrunning_preview_texture, nullptr)); for (auto& [url, texture] : g_mod_store.textures) if (texture) SDL_DestroyTexture(texture); diff --git a/runtime-recomp/src/game/mods/legacy_mod_launch.cpp b/runtime-recomp/src/game/mods/legacy_mod_launch.cpp index dd5ab267..7dc9a4dd 100644 --- a/runtime-recomp/src/game/mods/legacy_mod_launch.cpp +++ b/runtime-recomp/src/game/mods/legacy_mod_launch.cpp @@ -1,6 +1,7 @@ #include "session_content/policy.hpp" #include "../shared_saves.hpp" #include "legacy_mod_launch.hpp" +#include "personal_adventure_paths.hpp" #include "vehicle_binding.hpp" #include "legacy_track_catalog.hpp" #include "../dkr_save_codec.hpp" @@ -65,12 +66,16 @@ std::shared_ptr prepare_mod_launch(const std::filesyste const DetailedLaunchProgress& detailed) { auto out = std::make_shared(); out->content_enabled = dkr::session_content::preparing(); - if (!online && !out->content_enabled) - return out; // The offline catalog is never consulted for online launches. The lobby's // separately verified, frozen RuntimeResources supply online assets. if (online) return out; + namespace saves = dkr::runtime::saves; + out->save_subfolder = saves::personal_adventure_subfolder(out->content_enabled); + out->save_path = saves::personal_adventure_path(config, out->content_enabled); + out->pak_directory = config; + if (!out->content_enabled) + return out; std::string personal_error; if (!dkr::runtime::saves::shared::prepare(config, personal_error)) throw Error(personal_error); @@ -117,9 +122,6 @@ std::shared_ptr prepare_mod_launch(const std::filesyste const auto identity = "dkr-offline-code-session-1\n" + out->fingerprint + "\n" + out->code->identity; out->fingerprint = sha256(View(reinterpret_cast(identity.data()), identity.size())); } - out->save_subfolder.clear(); - out->save_path = config / "saves" / "dkr.us.v77.bin"; - out->pak_directory = config; std::string save_error; if (!dkr::runtime::saves::shared::prepare(config, save_error)) throw Error(save_error); diff --git a/runtime-recomp/src/game/mods/sdk2_tools_ui.inl b/runtime-recomp/src/game/mods/sdk2_tools_ui.inl index 40ab3852..32ff36e5 100644 --- a/runtime-recomp/src/game/mods/sdk2_tools_ui.inl +++ b/runtime-recomp/src/game/mods/sdk2_tools_ui.inl @@ -85,7 +85,8 @@ void DrawSdk2Tools() { ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, {0.5F, 0.5F}); ImGui::SetNextWindowSize({std::max(320.F, display.x - 48.F), std::max(240.F, display.y - 48.F)}, ImGuiCond_Appearing); - if (!ImGui::Begin("CUSTOM MAGIC CODE TOOLS", &open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar)) { + if (!dkr::runtime::ui::begin_dialog_window("CUSTOM MAGIC CODE TOOLS", &open, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar)) { ImGui::End(); ImGui::PopStyleVar(); if (!open) { diff --git a/runtime-recomp/src/game/netplay/session_chat/ui.inl b/runtime-recomp/src/game/netplay/session_chat/ui.inl index 57fcfdd3..8aea6d8c 100644 --- a/runtime-recomp/src/game/netplay/session_chat/ui.inl +++ b/runtime-recomp/src/game/netplay/session_chat/ui.inl @@ -59,7 +59,7 @@ void SessionChatKeyboard() { void SessionChatOptions(const dkr::chat::View& view) { if (OlButton("...##chat-options", OlTone::Plain, 38.F, "Chat options")) ImGui::OpenPopup("session-chat-options"); - if (ImGui::BeginPopup("session-chat-options")) { + if (dkr::runtime::ui::begin_dialog_popup("session-chat-options")) { if (view.host) { bool allow = dkr::chat::host_enabled.load(); if (ImGui::Checkbox("Allow lobby chat", &allow)) { diff --git a/runtime-recomp/src/game/online_nameplates_rt64.cpp b/runtime-recomp/src/game/online_nameplates_rt64.cpp index 02e070d0..572ea713 100644 --- a/runtime-recomp/src/game/online_nameplates_rt64.cpp +++ b/runtime-recomp/src/game/online_nameplates_rt64.cpp @@ -4,6 +4,7 @@ #include "local_scenery_policy.hpp" #include "generated/selawik_font.h" #include "presentation_identity.hpp" +#include "time_trial/session.hpp" #include "gbi/rt64_gbi_rdp.h" #define STBTT_STATIC #define STB_TRUETYPE_IMPLEMENTATION @@ -56,6 +57,10 @@ struct Nameplates::Impl { std::array names{}; std::array, 4> named{}; std::array position{}; + std::string ghost_name; + Label ghost{}; + Label ghost_outline{}; + bool outline = false; std::vector pixels; Plan plan; std::uint32_t scene = 0; @@ -65,6 +70,8 @@ struct Nameplates::Impl { float left, top, right, bottom; }; std::array boxes{}; + void draw_label(RT64::State&, const Label&, const hlslpp::float4x4&, IdentitySelector, + float x, float y, float z, float object_scale, float opacity, unsigned owner); Label raster(const stbtt_fontinfo& font, std::string_view text) { constexpr unsigned Width = 512; std::array alpha{}; @@ -137,6 +144,9 @@ void Nameplates::prepare(const Session& session, const Plan& plan, std::span decoder, + std::uint32_t scene) noexcept { + auto& p = *impl_; + p.plan = {}; + p.scene = scene ^ 0x47484F53U; + p.ready = false; + if ((name.empty() && !outline) || decoder.size() < kLabelTextureEnd) + return; + try { + if (p.ghost_name != name || p.outline != outline || p.pixels.empty()) { + p.built = false; + p.ghost_name.clear(); + p.pixels.clear(); + stbtt_fontinfo font{}; + if (!stbtt_InitFont(&font, reinterpret_cast(dkr_selawik_semibold_font), 0)) + return; + p.ghost = name.empty() ? Label{} : p.raster(font, name); + p.ghost_outline = outline ? p.raster(font, "<>") : Label{}; + p.ghost_name = name; + p.outline = outline; + } + if (!p.ghost.tiles && !p.ghost_outline.tiles) + return; + std::memcpy(decoder.data() + kLabelTextureBegin, p.pixels.data(), p.pixels.size()); + p.ready = true; + } catch (...) { + // Ghost names are optional, including when texture allocation fails. + } +} void Nameplates::begin_view(unsigned view) { impl_->view = view; impl_->occupied = 0; @@ -175,14 +214,32 @@ void Nameplates::draw(RT64::State& s, const dkr_owned_draw_event& e, const hlslp if (!p.ready || !select || e.token != p.view || owner == p.view || owner >= 4 || rank < 1 || rank > 8 || (p.plan.focus && p.view != p.plan.owner) || !dkr_owned_draw_event_valid(&e)) return; + const auto& label = p.plan.labels == Labels::NameAndPosition ? p.named[owner][rank - 1] : p.position[rank - 1]; + p.draw_label(s, label, camera, select, std::bit_cast(e.parameters[2]), + std::bit_cast(e.parameters[3]), std::bit_cast(e.parameters[4]), + std::bit_cast(e.parameters[5]), 1.F, owner); +} +void Nameplates::draw_ghost(RT64::State& s, const time_trial::GhostNameplate& ghost, const hlslpp::float4x4& camera, + IdentitySelector select) { + auto& p = *impl_; + if (!p.ready || !select) + return; + if (ghost.outline) + p.draw_label(s, p.ghost_outline, camera, select, ghost.position[0], ghost.position[1], ghost.position[2], + ghost.scale, ghost.opacity, 1); + p.draw_label(s, p.ghost, camera, select, ghost.position[0], ghost.position[1], ghost.position[2], + ghost.scale, ghost.opacity, 0); +} +void Nameplates::Impl::draw_label(RT64::State& s, const Label& label, const hlslpp::float4x4& camera, + IdentitySelector select, float x, float y, float z, float object_scale, + float opacity, unsigned owner) { + if (!label.tiles) + return; auto& rsp = *s.rsp; auto& rdp = *s.rdp; if (rdp.colorCombinerStackSize >= RDP_EXTENDED_STACK_SIZE || rdp.primColorStackSize >= RDP_EXTENDED_STACK_SIZE || rdp.envColorStackSize >= RDP_EXTENDED_STACK_SIZE) return; - const float x = std::bit_cast(e.parameters[2]), y = std::bit_cast(e.parameters[3]), - z = std::bit_cast(e.parameters[4]); - const float object_scale = std::bit_cast(e.parameters[5]); if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z) || !std::isfinite(object_scale) || std::abs(x) > 32768 || std::abs(y) > 32768 || std::abs(z) > 32768 || object_scale <= 0 || object_scale > 64) return; @@ -194,13 +251,10 @@ void Nameplates::draw(RT64::State& s, const dkr_owned_draw_event& e, const hlslp if (!std::isfinite(nx) || !std::isfinite(ny) || !std::isfinite(nz) || std::abs(nx) > 4 || std::abs(ny) > 1.15F || nz < 0 || nz > 1) return; - const auto& label = p.plan.labels == Labels::NameAndPosition ? p.named[owner][rank - 1] : p.position[rank - 1]; - if (!label.tiles) - return; const auto& viewport = rsp.viewportStack[rsp.viewportStackSize - 1]; if (std::abs(float(viewport.scale.x)) < 1 || std::abs(float(viewport.scale.y)) < 1) return; - const float pixel_scale = 4.5F * float(p.plan.label_size) * .01F / FontHeight; + const float pixel_scale = 4.5F * float(plan.label_size) * .01F / FontHeight; const float half_width = float(label.width) * pixel_scale * .5F; const float screen_x = nx * float(viewport.scale.x) + float(viewport.translate.x); float screen_y = -ny * float(viewport.scale.y) + float(viewport.translate.y) - float(Height) * pixel_scale; @@ -208,8 +262,8 @@ void Nameplates::draw(RT64::State& s, const dkr_owned_draw_event& e, const hlslp // Bounded local placement, not a change to the actor's transform or rank. for (unsigned attempt = 0; attempt < 4; ++attempt) { bool overlap = false; - for (unsigned i = 0; i < p.occupied; ++i) { - const auto& b = p.boxes[i]; + for (unsigned i = 0; i < occupied; ++i) { + const auto& b = boxes[i]; overlap |= screen_x + half_width > b.left && screen_x - half_width < b.right && screen_y + height > b.top && screen_y < b.bottom; } @@ -217,10 +271,10 @@ void Nameplates::draw(RT64::State& s, const dkr_owned_draw_event& e, const hlslp break; screen_y -= height + 1; } - if (p.occupied < p.boxes.size()) - p.boxes[p.occupied++] = {screen_x - half_width, screen_y, screen_x + half_width, screen_y + height}; + if (occupied < boxes.size()) + boxes[occupied++] = {screen_x - half_width, screen_y, screen_x + half_width, screen_y + height}; anchor.y = (float(viewport.translate.y) - screen_y) / float(viewport.scale.y) * w; - const auto alpha = std::uint32_t(std::clamp((6000.F - w) / 1000.F, 0.F, 1.F) * 255.F); + const auto alpha = std::uint32_t(std::clamp((6000.F - w) / 1000.F, 0.F, 1.F) * opacity * 255.F); if (!alpha) return; NativeDrawScope restore(s); @@ -236,8 +290,8 @@ void Nameplates::draw(RT64::State& s, const dkr_owned_draw_event& e, const hlslp billboard[3] = anchor; // Native scenery owns placement bytes 1..128. Labels use 241..244, // retaining the native high bit and never matching canonical game draws. - select(rsp, local_scenery::native_identity(presentation::normalise_identity(p.scene ^ 0x4E414D45U), 0xF0U + owner, - p.view)); + select(rsp, local_scenery::native_identity(presentation::normalise_identity(scene ^ 0x4E414D45U), 0xF0U + owner, + view)); rsp.modelMatrixStack[2] = billboard; rsp.modelMatrixStackSize = 3; rsp.modelMatrixPhysicalAddressStack[2] = rsp.modelMatrixSegmentedAddressStack[2] = local_scenery::kVertexScratch; diff --git a/runtime-recomp/src/game/online_nameplates_rt64.hpp b/runtime-recomp/src/game/online_nameplates_rt64.hpp index 370da85c..7332428c 100644 --- a/runtime-recomp/src/game/online_nameplates_rt64.hpp +++ b/runtime-recomp/src/game/online_nameplates_rt64.hpp @@ -6,6 +6,9 @@ namespace RT64 { struct State; struct RSP; } // namespace RT64 +namespace dkr::runtime::time_trial { +struct GhostNameplate; +} namespace dkr::runtime::online_view { inline constexpr std::uint32_t kLabelTextureBegin = 0x00D00000U, kLabelTextureEnd = 0x00E00000U; class Nameplates final { @@ -14,8 +17,10 @@ class Nameplates final { Nameplates(); ~Nameplates(); void prepare(const Session&, const Plan&, std::span, std::uint32_t scene) noexcept; + void prepare_ghost(std::string_view, bool outline, std::span, std::uint32_t scene) noexcept; void begin_view(unsigned view); void draw(RT64::State&, const dkr_owned_draw_event&, const hlslpp::float4x4& camera, IdentitySelector); + void draw_ghost(RT64::State&, const time_trial::GhostNameplate&, const hlslpp::float4x4& camera, IdentitySelector); private: struct Impl; diff --git a/runtime-recomp/src/game/online_view_rt64.cpp b/runtime-recomp/src/game/online_view_rt64.cpp index db926828..e1b2cde2 100644 --- a/runtime-recomp/src/game/online_view_rt64.cpp +++ b/runtime-recomp/src/game/online_view_rt64.cpp @@ -4,6 +4,7 @@ #include "hud_projection_rt64.hpp" #include "hud_reference_layout.hpp" #include "presentation_identity.hpp" +#include "time_trial/session.hpp" #include "hle/rt64_state.h" #include #include @@ -25,6 +26,7 @@ struct Pass::Impl { hud::LayoutMode hud_mode = hud::LayoutMode::Original; hlslpp::float4x4 camera{}; Nameplates names; + std::optional ghost; IdentitySelector select = nullptr; std::array widgets{}; std::array widget_elements{}; @@ -67,6 +69,7 @@ void Pass::prepare(const Session& session, std::span std::span decoder, std::uint32_t scene, float aspect, std::uint32_t framebuffer, hud::LayoutMode hud_mode) noexcept { auto& p = *impl_; + p.ghost.reset(); const auto eligibility = dkr::online_stability::view_eligibility(session.owner, session.players, events); p.race_type = eligibility.race_type; p.plan = dkr::online_stability::focus_plan(online_view::plan(session, events), eligibility, session.owner, @@ -102,6 +105,30 @@ void Pass::prepare(const Session& session, std::span p.names.prepare(session, p.plan, decoder, p.plan.focus ? presentation::normalise_identity(scene ^ 0x46554C4CU ^ session.owner) : scene); } +void Pass::prepare_ghost(time_trial::GhostNameplate ghost, std::span decoder, + std::uint32_t scene) noexcept { + auto& p = *impl_; + p.plan = {}; + p.phase = Impl::Phase::Shared; + p.camera_valid = false; + p.framebuffer = ghost.framebuffer; + p.names.prepare_ghost(ghost.name ? std::string_view(*ghost.name) : std::string_view{}, ghost.outline, decoder, scene); + p.ghost = std::move(ghost); +} +void Pass::ghost_world_boundary(RT64::State& s, unsigned view, bool end) { + auto& p = *impl_; + if (!p.ghost || view != 0) + return; + if (!end) { + p.phase = Impl::Phase::World; + p.camera_valid = false; + p.names.begin_view(view); + return; + } + if (p.phase == Impl::Phase::World && p.camera_valid && p.main_image(s)) + p.names.draw_ghost(s, *p.ghost, p.camera, p.select); + p.phase = Impl::Phase::Shared; +} void Pass::selector(IdentitySelector value) noexcept { impl_->select = value; } @@ -240,7 +267,7 @@ void Pass::after_command(RT64::State& s, bool scissor, bool viewport) { } void Pass::camera_root(RT64::RSP& rsp, unsigned matrix) { auto& p = *impl_; - if (!p.plan.eligible || p.phase != Impl::Phase::World || matrix > 2) + if ((!p.plan.eligible && !p.ghost) || p.phase != Impl::Phase::World || matrix > 2) return; p.camera = rsp.modelMatrixStack[matrix]; p.camera_valid = true; diff --git a/runtime-recomp/src/game/online_view_rt64.hpp b/runtime-recomp/src/game/online_view_rt64.hpp index c5bf1289..c0bb6765 100644 --- a/runtime-recomp/src/game/online_view_rt64.hpp +++ b/runtime-recomp/src/game/online_view_rt64.hpp @@ -6,6 +6,9 @@ namespace RT64 { struct State; struct RSP; } // namespace RT64 +namespace dkr::runtime::time_trial { +struct GhostNameplate; +} namespace dkr::runtime::online_view { // One instance per owned renderer. No reference to live/replay RAM is retained. class Pass final { @@ -16,6 +19,8 @@ class Pass final { Pass& operator=(const Pass&) = delete; void prepare(const Session&, std::span, std::span decoder, std::uint32_t scene, float aspect, std::uint32_t framebuffer, hud::LayoutMode hud_mode) noexcept; + void prepare_ghost(time_trial::GhostNameplate, std::span decoder, std::uint32_t scene) noexcept; + void ghost_world_boundary(RT64::State&, unsigned view, bool end); bool focused() const noexcept; bool focused_hud() const noexcept; bool widget_active() const noexcept; diff --git a/runtime-recomp/src/game/personal_adventure_paths.hpp b/runtime-recomp/src/game/personal_adventure_paths.hpp new file mode 100644 index 00000000..6019c47e --- /dev/null +++ b/runtime-recomp/src/game/personal_adventure_paths.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +namespace dkr::runtime::saves { +inline constexpr std::string_view kModdedAdventureFolder = "modded"; +inline constexpr std::string_view kModdedAdventureDirectory = "saves/modded/"; + +inline std::filesystem::path personal_adventure_subfolder(bool modded) { + return modded ? std::filesystem::path(kModdedAdventureFolder) : std::filesystem::path{}; +} + +inline std::filesystem::path personal_adventure_path(const std::filesystem::path& root, bool modded) { + return root / "saves" / personal_adventure_subfolder(modded) / "dkr.us.v77.bin"; +} +} // namespace dkr::runtime::saves diff --git a/runtime-recomp/src/game/presentation_identity.cpp b/runtime-recomp/src/game/presentation_identity.cpp index b8d33b48..9c24669f 100644 --- a/runtime-recomp/src/game/presentation_identity.cpp +++ b/runtime-recomp/src/game/presentation_identity.cpp @@ -17,6 +17,7 @@ #include "runtime_hud_layout.hpp" #include "runtime_netplay.hpp" #include "vehicle_context_policy.hpp" +#include "time_trial/session.hpp" #include #include @@ -210,6 +211,7 @@ thread_local dkr::runtime::presentation::RetainedMetadataTable g_active_matrix_map; thread_local std::unordered_map> g_active_marker_map; @@ -551,7 +553,8 @@ void NoteFree(std::uint32_t object) { } void RegisterCameraMatrix(std::uint8_t* rdram, std::uint32_t matrix_reference, std::uint8_t matrix_role) { - if (!dkr::runtime::enhancements::modern_presentation_enabled()) { + const bool modern = dkr::runtime::enhancements::modern_presentation_enabled(); + if (!modern && (matrix_role != 1U || !dkr::runtime::time_trial::ghost_nameplate_active())) { return; } if (!ValidRange(matrix_reference, 4U)) { @@ -566,6 +569,13 @@ void RegisterCameraMatrix(std::uint8_t* rdram, std::uint32_t matrix_reference, s } std::scoped_lock lock(g_identity_mutex); + if (!modern) { + // Accurate mode needs the ghost label's camera root without interpolation metadata. + MatrixBinding root{}; + root.camera_root = true; + g_matrix_maps[g_recording_buffer & 1U].insert_or_assign(Physical(matrix_address), root); + return; + } const std::uint32_t scene = g_scene_generation.load(std::memory_order_relaxed); std::uint32_t camera_id = 0U; if (!ActiveLogicalCamera(rdram, camera_id)) { @@ -642,6 +652,11 @@ void RegisterCameraMatrix(std::uint8_t* rdram, std::uint32_t matrix_reference, s dkr::runtime::presentation::MatrixInterpolation dkr::runtime::presentation::matrix_interpolation(std::uint32_t physical_matrix_address) { const std::uint32_t address = physical_matrix_address & kRdramMask; + if (g_active_replay) { + const auto& matrices = g_active_replay->matrices; + const auto found = std::ranges::lower_bound(matrices, address, {}, &OwnedMatrixBinding::address); + return found != matrices.end() && found->address == address ? found->interpolation : MatrixInterpolation{}; + } const MatrixBinding* binding = nullptr; if (g_active_owned_task) binding = g_active_owned_matrices.find(address); @@ -828,6 +843,18 @@ dkr::runtime::presentation::shadow_presentation_key(std::uint8_t* rdram, std::ui }; } +namespace { +const dkr::runtime::presentation::OwnedShadowBinding* ReplayShadow(std::uint64_t key) { + using dkr::runtime::presentation::OwnedShadowBinding; + if ((key >> 16U) != g_active_replay->scene) + return nullptr; + const auto& shadows = g_active_replay->shadows; + const auto token = static_cast(key); + const auto found = std::ranges::lower_bound(shadows, token, {}, &OwnedShadowBinding::token); + return found != shadows.end() && found->token == token ? &*found : nullptr; +} +} // namespace + bool dkr::runtime::presentation::shadow_owner_uses_rigid_actor_proxy(std::uint64_t shadow_history_key) { if (shadow_history_key == 0U) return false; @@ -835,6 +862,8 @@ bool dkr::runtime::presentation::shadow_owner_uses_rigid_actor_proxy(std::uint64 const auto* found = g_active_owned_shadow_policies.find(shadow_history_key); return found && found->required(); } + if (g_active_replay) + return shadow_owner_rigid_policy(shadow_history_key).required(); std::scoped_lock lock(g_identity_mutex); return g_rigid_actor_shadow_keys.contains(shadow_history_key); } @@ -846,6 +875,8 @@ bool dkr::runtime::presentation::shadow_owner_is_taj_carpet_actor(std::uint64_t const auto* found = g_active_owned_shadow_policies.find(shadow_history_key); return found && found->terrain_conforming_actor(); } + if (g_active_replay) + return shadow_owner_rigid_policy(shadow_history_key).magic_carpet(); std::scoped_lock lock(g_identity_mutex); return g_taj_carpet_shadow_keys.contains(shadow_history_key); } @@ -858,6 +889,10 @@ dkr::runtime::presentation::shadow_owner_rigid_policy(std::uint64_t shadow_histo const auto* found = g_active_owned_shadow_policies.find(shadow_history_key); return found ? *found : RigidShadowOwnerPolicy{}; } + if (g_active_replay) { + const auto* binding = ReplayShadow(shadow_history_key); + return binding ? binding->policy : RigidShadowOwnerPolicy{}; + } std::scoped_lock lock(g_identity_mutex); const auto found = g_rigid_shadow_owner_policies.find(shadow_history_key); return found != g_rigid_shadow_owner_policies.end() ? found->second @@ -872,13 +907,18 @@ dkr::runtime::presentation::shadow_owner_motion_sample(std::uint64_t shadow_hist const auto* found = g_active_owned_shadow_motion.find(shadow_history_key); return found ? *found : ShadowOwnerMotionSample{}; } + if (g_active_replay) { + const auto* binding = ReplayShadow(shadow_history_key); + return binding ? binding->motion : ShadowOwnerMotionSample{}; + } const auto found = g_active_shadow_owner_motion.find(shadow_history_key); return found != g_active_shadow_owner_motion.end() ? found->second : dkr::runtime::presentation::ShadowOwnerMotionSample{}; } dkr::runtime::presentation::TaskIdentityScope::TaskIdentityScope(std::uint8_t* rdram_snapshot, - std::uint32_t display_list_address) { + std::uint32_t display_list_address, + const ReplayPresentation* replay) { g_active_task_presentation_time = 0.0; g_active_matrix_map.clear(); g_active_marker_map.clear(); @@ -888,6 +928,17 @@ dkr::runtime::presentation::TaskIdentityScope::TaskIdentityScope(std::uint8_t* r g_active_task_scene_generation = 0U; g_active_owned_task = false; g_active_owned_shadow_policies.clear(); + g_active_replay = replay; + if (replay) { + for (const auto& located : replay->markers) + g_active_marker_map[located.address].push_back(located.marker); + // Archive playback normally presents authored pictures. Video export + // has a sequential timeline and can use the archived motion identities. + g_active_task_interpolation_allowed = time_trial::exporting_video() && replay->scene != 0U; + g_active_task_scene_generation = replay->scene; + g_active_task_presentation_time = replay->time; + return; + } if (rdram_snapshot == nullptr) { return; } @@ -937,6 +988,7 @@ dkr::runtime::presentation::TaskIdentityScope::TaskIdentityScope(std::uint8_t* r } dkr::runtime::presentation::TaskIdentityScope::~TaskIdentityScope() { + g_active_replay = nullptr; g_active_matrix_map.clear(); g_active_marker_map.clear(); g_active_detail.clear(); @@ -965,6 +1017,7 @@ dkr::runtime::presentation::TaskIdentityScope::TaskIdentityScope(std::span= 0 ? time : 0; if (markers.size() > 8192 || matrices.size() > 8192 || shadows.size() > 8192) { g_active_owned_matrices.clear(); @@ -1157,7 +1210,10 @@ bool dkr::runtime::presentation::record_presentation_marker(std::uint32_t comman std::uint16_t token, std::uint8_t variant, PresentationMarkerKind kind, hud::groups::Transform hud_transform) { - if (!dkr::runtime::enhancements::modern_presentation_enabled()) { + const bool world_boundary = kind == PresentationMarkerKind::CameraWorldBegin || + kind == PresentationMarkerKind::CameraWorldEnd; + if (!dkr::runtime::enhancements::modern_presentation_enabled() && + !(world_boundary && dkr::runtime::time_trial::ghost_nameplate_active())) { return false; } const std::uint32_t physical = Physical(command_address); @@ -1436,7 +1492,50 @@ extern "C" void dkr_presentation_task_submitted(std::uint8_t* rdram, recomp_cont } dkr::runtime::graphics_handoff::capture(rdram, static_cast(context->r4), static_cast(context->r5)); - if (!dkr::runtime::enhancements::modern_presentation_enabled()) { + if (dkr::runtime::time_trial::watching()) { + std::shared_ptr sidecar; + if (dkr::runtime::enhancements::modern_presentation_enabled()) + sidecar = std::make_shared(); + { + std::scoped_lock lock(g_identity_mutex); + const auto buffer = g_recording_buffer & 1U; + if (sidecar && g_marker_integrity[buffer].valid) { + for (const auto& [address, markers] : g_marker_maps[buffer]) + for (const auto& marker : markers) + sidecar->markers.push_back({address, marker}); + sidecar->scene = g_scene_generation.load(std::memory_order_relaxed); + sidecar->time = double(g_presentation_ticks.load(std::memory_order_relaxed)) / 60.0; + const bool capture_motion = dkr::runtime::time_trial::exporting_video(); + for (const auto& [address, binding] : g_matrix_maps[buffer]) { + if (!capture_motion && binding.world_projection.authored_fov <= 0.0F && !binding.camera_root) + continue; + sidecar->matrices.push_back({ + address, + {binding.matrix_identity, capture_motion && binding.interpolate_vertices, + capture_motion && binding.interpolate_texcoords, capture_motion && binding.interpolate_tiles, + capture_motion && binding.procedural_water, + capture_motion ? binding.water_scroll_tag : std::uint8_t{0}, + binding.world_projection, binding.camera_root}}); + } + for (const auto& [key, motion] : g_shadow_owner_motion_maps[buffer]) { + const auto policy = g_rigid_shadow_owner_policies.find(key); + if ((key >> 16U) == sidecar->scene && policy != g_rigid_shadow_owner_policies.end()) + sidecar->shadows.push_back({static_cast(key), policy->second, motion}); + } + std::ranges::sort(sidecar->matrices, {}, &dkr::runtime::presentation::OwnedMatrixBinding::address); + std::ranges::sort(sidecar->shadows, {}, &dkr::runtime::presentation::OwnedShadowBinding::token); + } + g_matrix_maps[buffer].clear(); + g_marker_maps[buffer].clear(); + g_detail_maps[buffer].clear(); + g_shadow_owner_motion_maps[buffer].clear(); + } + dkr::runtime::time_trial::theatre_graphics_submitted(rdram, static_cast(context->r4), + std::move(sidecar)); + return; + } + if (!dkr::runtime::enhancements::modern_presentation_enabled() && + !dkr::runtime::time_trial::ghost_nameplate_active()) { return; } SubmittedFrame frame{}; diff --git a/runtime-recomp/src/game/presentation_identity.hpp b/runtime-recomp/src/game/presentation_identity.hpp index f7884cd2..becf9879 100644 --- a/runtime-recomp/src/game/presentation_identity.hpp +++ b/runtime-recomp/src/game/presentation_identity.hpp @@ -2084,6 +2084,7 @@ struct LocatedPresentationMarker { std::uint32_t address; PresentationMarker marker; }; + std::vector camera_world_boundaries(); struct OwnedMatrixBinding { std::uint32_t address; @@ -2096,6 +2097,15 @@ struct OwnedShadowBinding { ShadowOwnerMotionSample motion; }; +// Presentation metadata retained with the same RDRAM snapshot as the replay frame. +struct ReplayPresentation { + std::vector markers; + std::vector matrices; + std::vector shadows; + std::uint32_t scene = 0; + double time = 0.0; +}; + // DKR flips gSPTaskNum immediately after gfxtask_run_xbus returns. A renderer // snapshot may therefore contain the parity of the next display-list buffer, // not the task being decoded. The frozen task's scene and data_ptr are the @@ -2121,7 +2131,8 @@ PresentationMarkerList active_presentation_markers(std::uint32_t command_address // the same N64 display-list buffer. class TaskIdentityScope { public: - TaskIdentityScope(std::uint8_t* rdram_snapshot, std::uint32_t display_list_address); + TaskIdentityScope(std::uint8_t* rdram_snapshot, std::uint32_t display_list_address, + const ReplayPresentation* replay = nullptr); // Private copied-image decode only. Does not consume the stable producer's // submission queue or install metadata from rewindable/live CPU globals. explicit TaskIdentityScope(std::span owned_markers); diff --git a/runtime-recomp/src/game/record_store.inl b/runtime-recomp/src/game/record_store.inl index 352cde21..ec0fe45a 100644 --- a/runtime-recomp/src/game/record_store.inl +++ b/runtime-recomp/src/game/record_store.inl @@ -44,7 +44,7 @@ bool persist(const std::filesystem::path& path, std::span by error = "The custom-record store is full; export a copy before adding more records."; return false; } - return storage::write_atomic(path, encode(merged), ReadRecords, error); + return storage::write_progress(path, encode(merged), ReadRecords, error); } bool begin(const std::filesystem::path& path, bool restore, std::string& error) { if (!finish(error)) diff --git a/runtime-recomp/src/game/rt64_renderer.cpp b/runtime-recomp/src/game/rt64_renderer.cpp index 05e83272..97612a43 100644 --- a/runtime-recomp/src/game/rt64_renderer.cpp +++ b/runtime-recomp/src/game/rt64_renderer.cpp @@ -8,6 +8,8 @@ #include "online_stability/battle_view.hpp" #include "vehicle_binding.hpp" #include "rt64_renderer.hpp" +#include "time_trial/session.hpp" +#include "time_trial/theatre_frames.hpp" #include "camera_rt64.hpp" #include "revision_addresses.hpp" #include "netplay/online_input_broker.hpp" @@ -524,7 +526,7 @@ dkr::runtime::RT64Renderer::RT64Renderer(std::uint8_t* rdram, ultramodern::rende // PresentEarly uses historical VIs during DL decode and ignores the // explicit updateScreen below. That native scheduler policy must not // choose an obsolete buffer after an owned scene/rollback boundary. - application_->enhancementConfig.presentation.mode = PresentationMode(owned_mode_); + application_->enhancementConfig.presentation.mode = PresentationMode(owned_mode_ || time_trial::exporting_video()); dkr::runtime::startup_performance::report("rt64-application-create", application_started_at); }; create_application(); @@ -707,7 +709,7 @@ bool dkr::runtime::RT64Renderer::update_config(const ultramodern::renderer::Grap void dkr::runtime::RT64Renderer::enable_instant_present() { std::scoped_lock presentation_lock(presentation_mutex_); if (application_ != nullptr) { - application_->enhancementConfig.presentation.mode = PresentationMode(owned_mode_); + application_->enhancementConfig.presentation.mode = PresentationMode(owned_mode_ || time_trial::exporting_video()); application_->updateEnhancementConfig(); } } @@ -722,9 +724,29 @@ void dkr::runtime::RT64Renderer::send_dl(const OSTask* task, std::uint8_t* rdram #else std::scoped_lock presentation_lock(presentation_mutex_); #endif - if (application_ == nullptr || rdram_snapshot == nullptr) { + if (application_ == nullptr || rdram_snapshot == nullptr) return; + if (time_trial::watching()) { + if (const auto stamp = time_trial::theatre_graphics_stamp(task->t.data_ptr)) { + if (!theatre_frames_) + theatre_frames_ = std::make_unique(time_trial::exporting_full_game_video()); + if (theatre_frames_->append(*task, *stamp, + std::span( + rdram_snapshot, time_trial::TheatreFrames::ImageBytes))) { + time_trial::theatre_buffered(stamp->progress.updates); + } else { + time_trial::theatre_archive_error(); + } + return; + } + if (theatre_frames_) + return; } + render_dl_locked(task, rdram_snapshot); +} + +void dkr::runtime::RT64Renderer::render_dl_locked(const OSTask* task, std::uint8_t* rdram_snapshot, + const presentation::ReplayPresentation* replay) { ApplyDisplayRequest(*application_, true); dkr::runtime::telemetry::record_graphics_task(); RT64::MipWaitFeedbackScope mipFeedback([this] { present_mipmap_loading(*application_); }); @@ -733,7 +755,7 @@ void dkr::runtime::RT64Renderer::send_dl(const OSTask* task, std::uint8_t* rdram // them. DKR relies on that during scene transitions and can free texture // allocations while the host graphics queue is still pending. Parse this // task from the submission-time snapshot, then restore live RDRAM for VI. - dkr::runtime::presentation::TaskIdentityScope identity_scope(rdram_snapshot, task->t.data_ptr); + dkr::runtime::presentation::TaskIdentityScope identity_scope(rdram_snapshot, task->t.data_ptr, replay); const bool detail_requested = enhancements::maximum_detail_enabled() && !detail::ordinary_events().empty(); std::uint8_t* decode_bytes = rdram_snapshot; const bool camera_requested = bool(camera::activation()); @@ -749,6 +771,15 @@ void dkr::runtime::RT64Renderer::send_dl(const OSTask* task, std::uint8_t* rdram render_provenance::Scope provenance( {rdram_snapshot, 0x800000}, {decode_bytes, decode_bytes == rdram_snapshot ? 0x800000U : camera_decoder_.size()}, task->t.data_ptr); + online_view::Pass* ghost_names = nullptr; + if (!replay) { + if (auto ghost = time_trial::ghost_nameplate(rdram_snapshot)) { + if (!ghost_nameplate_pass_) + ghost_nameplate_pass_ = std::make_unique(); + ghost_nameplate_pass_->prepare_ghost(std::move(*ghost), camera_decoder_, presentation::task_scene_generation()); + ghost_names = ghost_nameplate_pass_.get(); + } + } static std::atomic_flag provenance_notice = ATOMIC_FLAG_INIT; if (!provenance_notice.test_and_set(std::memory_order_relaxed)) std::fprintf( @@ -803,18 +834,18 @@ void dkr::runtime::RT64Renderer::send_dl(const OSTask* task, std::uint8_t* rdram #if defined(__ANDROID__) { android_frame_budget::Scope decodeTiming(android_frame_budget::Region::Decoder); - f3ddkr_.process(*application_, *task, nullptr, nullptr, detail_requested ? &ordinary_models : nullptr, + f3ddkr_.process(*application_, *task, nullptr, ghost_names, detail_requested ? &ordinary_models : nullptr, camera_requested ? camera_pass_.get() : nullptr); } android_frame_budget::report(); #else - f3ddkr_.process(*application_, *task, nullptr, nullptr, detail_requested ? &ordinary_models : nullptr, + f3ddkr_.process(*application_, *task, nullptr, ghost_names, detail_requested ? &ordinary_models : nullptr, camera_requested ? camera_pass_.get() : nullptr); #endif record_track_performance(rdram_snapshot, start); } else { track_capture_.count = 0; // A later opt-in capture must not span the idle gap. - f3ddkr_.process(*application_, *task, nullptr, nullptr, detail_requested ? &ordinary_models : nullptr, + f3ddkr_.process(*application_, *task, nullptr, ghost_names, detail_requested ? &ordinary_models : nullptr, camera_requested ? camera_pass_.get() : nullptr); } #if defined(__ANDROID__) @@ -892,6 +923,84 @@ void dkr::runtime::RT64Renderer::record_track_performance(std::uint8_t* snapshot capture.count = 0U; } +bool dkr::runtime::RT64Renderer::present_theatre_frame(std::chrono::steady_clock::time_point now) { + if (!theatre_frames_ || !theatre_frames_->last() || !time_trial::watching()) + return false; + if (time_trial::theatre_take_audio_reset()) + platform::clear_theatre_audio(); + const auto next = time_trial::theatre_next_frame(now); + if (!next) + return false; + const auto* packet = theatre_frames_->load(*next); + if (!packet) { + time_trial::theatre_archive_error(); + return false; + } + const auto previous = time_trial::progress().updates; + if (!time_trial::theatre_presented(packet->stamp.progress, *next)) + return false; + + auto& origin = *application_->core.VI_ORIGIN_REG; + const auto live = origin; + if (time_trial::exporting_video()) { + if (!ui::draw_replay_video_inputs(*application_)) { + time_trial::theatre_archive_error(); + return false; + } + + // Bind the archived display list and exact VI to this capture interval. + // Let the dedicated present thread hand off each swap independently. + origin = presentation::retail_ntsc_vi_origin(packet->stamp.framebuffer); + const auto vi = [&] { + CanonicalViPresentationScope vi_scope(*application_); + return application_->core.decodeVI(); + }(); + origin = live; + struct Capture { + unsigned frame; + unsigned pictures = 0; + bool ok = true; + } result{*next}; + RT64::PresentQueue::OfflineCapture capture{ + *next * 2 - 1, &result, + [](void* context, std::uint32_t index) { + auto& result = *static_cast(context); + result.ok = result.ok && index == result.pictures && time_trial::export_video_picture(result.frame, index); + ++result.pictures; + }}; + auto& queue = *application_->presentQueue; + queue.offlineCapture.store(&capture, std::memory_order_release); + application_->state->offlineCaptureVI = &vi; + render_dl_locked(&packet->task, theatre_frames_->image(), packet->stamp.sidecar.get()); + application_->state->updateScreen(vi, true); + queue.waitForPresentId(application_->state->presentId); + queue.waitForIdle(); + application_->state->offlineCaptureVI = nullptr; + queue.offlineCapture.store(nullptr, std::memory_order_release); + + if (!result.ok || !result.pictures || !time_trial::export_video_audio(*next, time_trial::theatre_take_audio())) { + time_trial::theatre_archive_error(); + return false; + } + return true; + } + + render_dl_locked(&packet->task, theatre_frames_->image(), packet->stamp.sidecar.get()); + origin = presentation::retail_ntsc_vi_origin(packet->stamp.framebuffer); + { + CanonicalViPresentationScope vi_scope(*application_); + application_->updateScreen(); + } + origin = live; + dkr::runtime::ui::draw(*application_); + if (time_trial::theatre_take_audio_reset()) + platform::clear_theatre_audio(); + auto samples = time_trial::theatre_take_audio(); + if (!samples.empty() && *next > previous) + platform::queue_theatre_audio(samples, time_trial::theatre().speed, previous, *next); + return true; +} + void dkr::runtime::RT64Renderer::update_screen() { #if defined(__ANDROID__) if (dkr::runtime::graphics_health::failed()) @@ -915,6 +1024,7 @@ void dkr::runtime::RT64Renderer::update_screen() { application_->sharedQueueResources->totalPresentations.load(std::memory_order_relaxed); if (completed > 0 && !first_successful_presentation_reported_) { first_successful_presentation_reported_ = true; + dkr::runtime::platform::startup_frame_presented(); #if defined(__ANDROID__) dkr::runtime::graphics_health::first_presentation.store(true); #endif @@ -960,6 +1070,10 @@ void dkr::runtime::RT64Renderer::update_screen() { // the settings UI from mutating renderer-owned caches concurrently. dkr::runtime::texture_packs::apply_pending(*application_, dkr::runtime::enhancements::modern_presentation_enabled()); + if (theatre_frames_ && theatre_frames_->last() && time_trial::watching()) { + present_theatre_frame(std::chrono::steady_clock::now()); + return; + } { CanonicalViPresentationScope vi_scope(*application_); application_->updateScreen(); @@ -971,7 +1085,8 @@ void dkr::runtime::RT64Renderer::update_screen() { // next overlay frame after the game present keeps UI work out of the // original graphics-completion critical section. dkr::runtime::ui::draw(*application_); - last_wait_presentation_ = std::chrono::steady_clock::now(); + if (!time_trial::theatre_holding_frame()) + last_wait_presentation_ = std::chrono::steady_clock::now(); observed_wait_generation_ = dkr::runtime::netplay::online_wait_generation(); observed_overlay_visible_ = dkr::runtime::ui::overlay_visible(); } @@ -982,7 +1097,10 @@ void dkr::runtime::RT64Renderer::service_online_wait_presentation() { return; #endif constexpr auto kWaitPresentationInterval = std::chrono::milliseconds(33); - if (!dkr::runtime::netplay::online_wait_active()) { + const bool waiting = dkr::runtime::netplay::online_wait_active(); + const bool replay = time_trial::watching(); + const bool restart = time_trial::restart_confirmation_pending(); + if (!waiting && !replay && !restart) { wait_replay_deferred_logged_ = false; return; } @@ -990,6 +1108,12 @@ void dkr::runtime::RT64Renderer::service_online_wait_presentation() { std::unique_lock presentation_lock(presentation_mutex_, std::try_to_lock); if (!presentation_lock.owns_lock()) return; + if (application_ && present_theatre_frame(std::chrono::steady_clock::now())) + return; + if (time_trial::exporting_video()) + return; + if (replay && !waiting && !time_trial::theatre_holding_frame() && !time_trial::theatre().buffering) + return; const bool queue_ready = application_ != nullptr && application_->state != nullptr && application_->workloadQueue != nullptr && application_->presentQueue != nullptr && application_->framebufferGraphicsWorker != nullptr && @@ -1053,7 +1177,7 @@ void dkr::runtime::RT64Renderer::service_online_wait_presentation() { application_->state->debuggerInspector.paused = previous_pause; const auto replay_elapsed = std::chrono::duration_cast(std::chrono::steady_clock::now() - replay_started); - if (replay_elapsed >= std::chrono::milliseconds(50) && replay_elapsed > slowest_wait_replay_) { + if (waiting && replay_elapsed >= std::chrono::milliseconds(50) && replay_elapsed > slowest_wait_replay_) { slowest_wait_replay_ = replay_elapsed; netplay::failure_recorder().record(netplay::FailureEventKind::ProgressWatchdog, 0U, static_cast(replay_elapsed.count()), 0U, diff --git a/runtime-recomp/src/game/rt64_renderer.hpp b/runtime-recomp/src/game/rt64_renderer.hpp index 4ca919a3..d6c9362b 100644 --- a/runtime-recomp/src/game/rt64_renderer.hpp +++ b/runtime-recomp/src/game/rt64_renderer.hpp @@ -26,6 +26,15 @@ class Registration; } // namespace dkr::runtime::netplay::experimental namespace dkr::runtime { +namespace presentation { +struct ReplayPresentation; +} +namespace time_trial { +class TheatreFrames; +} +namespace online_view { +class Pass; +} struct OwnedDecodeScratch; namespace camera { class RenderPass; @@ -63,6 +72,10 @@ class RT64Renderer final : public ultramodern::renderer::RendererContext { #endif private: + void render_dl_locked(const OSTask* task, std::uint8_t* rdram_snapshot, + const presentation::ReplayPresentation* replay = nullptr); + bool present_theatre_frame(std::chrono::steady_clock::time_point now); + std::unique_ptr theatre_frames_; void record_track_performance(std::uint8_t* snapshot, track_performance::Clock::time_point start); track_performance::Capture track_capture_{}; std::chrono::steady_clock::time_point last_android_report_{}; @@ -70,6 +83,7 @@ class RT64Renderer final : public ultramodern::renderer::RendererContext { std::unique_ptr application_; F3DDKRRT64Bridge f3ddkr_; std::unique_ptr camera_pass_; + std::unique_ptr ghost_nameplate_pass_; std::vector camera_decoder_; std::uint64_t present_count_ = 0; std::uint64_t interpolated_present_count_ = 0; diff --git a/runtime-recomp/src/game/runtime_camera_tuning_ui.inl b/runtime-recomp/src/game/runtime_camera_tuning_ui.inl index 5a45fe99..bb82b4fc 100644 --- a/runtime-recomp/src/game/runtime_camera_tuning_ui.inl +++ b/runtime-recomp/src/game/runtime_camera_tuning_ui.inl @@ -59,7 +59,7 @@ void DrawCameraTuningPanel() { const auto display = ImGui::GetIO().DisplaySize; ImGui::SetNextWindowSize({std::min(1120.F, display.x - 32.F), std::min(760.F, display.y - 32.F)}, ImGuiCond_Appearing); - if (!ImGui::Begin("MODERN CAMERA++", &open, ImGuiWindowFlags_NoCollapse)) { + if (!dkr::runtime::ui::begin_dialog_window("MODERN CAMERA++", &open, ImGuiWindowFlags_NoCollapse)) { ImGui::End(); if (!open) camplus::editor_open.store(false); diff --git a/runtime-recomp/src/game/runtime_hud_layout.cpp b/runtime-recomp/src/game/runtime_hud_layout.cpp index 6d7306fc..0e24a160 100644 --- a/runtime-recomp/src/game/runtime_hud_layout.cpp +++ b/runtime-recomp/src/game/runtime_hud_layout.cpp @@ -15,6 +15,7 @@ #include "hud_layout_config.hpp" #include "hud_basic_settings.hpp" #include "hud_reference_layout.hpp" +#include "time_trial/session.hpp" #include #include @@ -295,9 +296,11 @@ bool BeginHudPassForHolder(std::uint8_t* rdram, std::uint32_t holder) { const auto& state = g_frame_state; if (!g_group_frame || !state) return false; - const float host_aspect = state->viewport_height > 0 ? static_cast(state->viewport_width) / - static_cast(state->viewport_height) - : 4.0F / 3.0F; + // Keep the replay's sprite projection at its authored clip ratio. + // The texture-rectangle decoder widens the clip for repositioned text. + const float host_aspect = dkr::runtime::time_trial::watching() || state->viewport_height <= 0 + ? 4.0F / 3.0F + : static_cast(state->viewport_width) / state->viewport_height; return RecordHudMarker(rdram, holder, kHudPassMarkerBeginMode, dkr::runtime::hud::encode_hud_viewport_cover(host_aspect), dkr::runtime::hud::reference::kPassVariant); @@ -382,19 +385,29 @@ bool BeginWidget(std::uint8_t* rdram, std::uint32_t holder, dkr::runtime::hud::W : 4.0F / 3.0F; const bool v80 = dkr::runtime::revision_addresses::current().CurrentHud == dkr::runtime::revision_addresses::kUsV80.CurrentHud; + const auto mode = aspect > 4.0F / 3.0F && dkr::runtime::time_trial::watching() + ? dkr::runtime::hud::LayoutMode::FitToViewport + : state.mode; const auto transform = dkr::runtime::hud::reference::transform( - state.mode, aspect, + mode, aspect, dkr::runtime::hud::reference::anchor(element, widget, g_scenario, g_frame_layout == 1, g_general_pass_active, authored_x), static_cast(MEM_W(0, RdramAddress(dkr::runtime::hud_layout_symbols::for_revision(v80).hud_offset_x))), slides); - if (transform.identity()) + // The face model and its hands have separate fixed topology. Give + // each an identity for interpolation in sequential video playback. + const std::uint16_t stopwatch_token = + widget == dkr::runtime::hud::Widget::Stopwatch && element < dkr::runtime::hud::kElements.size() && + dkr::runtime::time_trial::exporting_video() + ? static_cast(1 + element + owner * dkr::runtime::hud::kElements.size()) + : 0; + if (transform.identity() && stopwatch_token == 0) return false; const auto command = static_cast(MEM_W(0, RdramAddress(holder))); if (!IsRdramPointer(command, 8)) return false; return dkr::runtime::presentation::record_presentation_marker( - command, 1, 0, 0, dkr::runtime::presentation::PresentationMarkerKind::HudWidget, transform); + command, 1, stopwatch_token, 0, dkr::runtime::presentation::PresentationMarkerKind::HudWidget, transform); } void EndWidget(std::uint8_t* rdram, std::uint32_t holder, bool& active) { if (active && rdram && IsRdramPointer(holder, 4)) { diff --git a/runtime-recomp/src/game/runtime_legacy_mods.cpp b/runtime-recomp/src/game/runtime_legacy_mods.cpp index fb542103..4a206a5b 100644 --- a/runtime-recomp/src/game/runtime_legacy_mods.cpp +++ b/runtime-recomp/src/game/runtime_legacy_mods.cpp @@ -9,6 +9,7 @@ #include "custom_records.hpp" #include "runtime_legacy_mods.hpp" #include "achievements.hpp" +#include "time_trial/session.hpp" #include "vehicle_binding.hpp" #include "vehicle_world.hpp" #include "vehicle_lighting/road_wheels.h" @@ -1950,7 +1951,7 @@ void install(legacy::ModWorld& world, std::uint8_t* ram) { extern "C" void dkr_achievements_observe(std::uint8_t* ram, unsigned revision) noexcept { using namespace dkr::runtime; - if (achievements::online_session()) + if (achievements::online_session() || time_trial::preparing_ghost()) return; try { auto sample = achievements::capture(ram, legacy::guest_memory_size(), revision); diff --git a/runtime-recomp/src/game/runtime_messages_ui.inl b/runtime-recomp/src/game/runtime_messages_ui.inl index 09f99591..32a876e1 100644 --- a/runtime-recomp/src/game/runtime_messages_ui.inl +++ b/runtime-recomp/src/game/runtime_messages_ui.inl @@ -11,7 +11,9 @@ void DrawTechnicalDetails(std::string_view diagnostic, const char* label = "Deta const auto caption = dkr::localisation::label(label); if (ImGui::CollapsingHeader(caption.c_str())) { const float height = std::clamp(ImGui::GetIO().DisplaySize.y * 0.22F, 70.0F, 180.0F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {12.0F, 10.0F}); ImGui::BeginChild("##technical-text", {0.0F, height}, true); + ImGui::PopStyleVar(); PaddockText(PaddockReading(14.0F, false, 1.5F), PaddockRgb(0xB0C9CC), diagnostic, std::max(ImGui::GetContentRegionAvail().x, 1.0F)); ImGui::EndChild(); diff --git a/runtime-recomp/src/game/runtime_mipmap_modal.hpp b/runtime-recomp/src/game/runtime_mipmap_modal.hpp index f107521a..cde0ed7d 100644 --- a/runtime-recomp/src/game/runtime_mipmap_modal.hpp +++ b/runtime-recomp/src/game/runtime_mipmap_modal.hpp @@ -1,4 +1,5 @@ #pragma once +#include "dialog_style.hpp" #include "render/rt64_generated_mip_config.h" #include "imgui.h" #include @@ -13,9 +14,9 @@ inline void draw_mipmap_loading_modal() { ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2{0.5F, 0.5F}); ImGui::SetNextWindowSize(ImVec2{std::max(160.0F, std::min(560.0F, viewport->WorkSize.x - 40.0F)), 0.0F}, ImGuiCond_Always); - if (ImGui::BeginPopupModal(title, nullptr, - ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoSavedSettings)) { + if (begin_dialog_modal(title, nullptr, + ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoSavedSettings)) { if (!visible) ImGui::CloseCurrentPopup(); else { diff --git a/runtime-recomp/src/game/runtime_netplay.cpp b/runtime-recomp/src/game/runtime_netplay.cpp index e0852e20..0a0801ca 100644 --- a/runtime-recomp/src/game/runtime_netplay.cpp +++ b/runtime-recomp/src/game/runtime_netplay.cpp @@ -22,6 +22,7 @@ #include "online_roster_policy.hpp" #include "magic_code_policy.hpp" #include "presentation_random_policy.hpp" +#include "time_trial/session.hpp" #include "revision_addresses.hpp" #include "runtime_magic_codes.hpp" #include "runtime_platform.hpp" @@ -1962,7 +1963,8 @@ bool physical_input_poll_allowed() { void begin_presentation_random_scope() { const RuntimeSessionView view = g_session.runtime_view(); - if (host_authority_requested(view) && g_rollback_gameplay_ready.load(std::memory_order_acquire)) { + if (time_trial::active() || + (host_authority_requested(view) && g_rollback_gameplay_ready.load(std::memory_order_acquire))) { ++g_presentation_random_scope_depth; } } diff --git a/runtime-recomp/src/game/runtime_online_mods_ui.inl b/runtime-recomp/src/game/runtime_online_mods_ui.inl index e0548744..59b236e4 100644 --- a/runtime-recomp/src/game/runtime_online_mods_ui.inl +++ b/runtime-recomp/src/game/runtime_online_mods_ui.inl @@ -103,7 +103,8 @@ bool CreateOnlineLobby() { g_online_mod_notice.clear(); if (g_online_mod_sync) g_online_mod_sync->cancel(); - return FinishOnlineLobby(request, {}, 0); + g_online_mod_host_request = std::move(request); + return true; } std::vector labs; for (const auto& track : dkr::runtime::custom_tracks::tracks()) @@ -173,15 +174,25 @@ void PumpOnlineMods() { if (view.phase == SyncPhase::Failed && !network.compatibility_sync_offer) ReportOnlinePreparationFailure(view.error); if (g_online_mod_host_request) { - if (network.state != ConnectionState::Offline || - g_online_mod_host_request->manifest.canonical_rom_hash != g_online_mod_identity.canonical_xxh3 || - g_online_mod_host_request->manifest.magic_codes_hash != dkr::runtime::magic_codes::selected_mask()) { + auto& pending = *g_online_mod_host_request; + if (session().active() || + pending.manifest.canonical_rom_hash != g_online_mod_identity.canonical_xxh3 || + (pending.content_enabled && pending.manifest.magic_codes_hash != dkr::runtime::magic_codes::selected_mask())) { g_online_mod_sync->cancel(); g_online_mod_host_request.reset(); g_online_action_status = "Preparation cancelled because the lobby, ROM or Magic Codes changed."; - } else if (view.phase == SyncPhase::HostReady) { - const bool modded = view.manifest && has_mods(*view.manifest); - const auto request = *g_online_mod_host_request; + } else if (!pending.content_enabled || view.phase == SyncPhase::HostReady) { + if (SharedSaveBusy()) + return; + if (!pending.cloud_account) { + pending.cloud_account = EnabledCloudSaveAccount(); + if (!pending.cloud_account->empty() && RunCloudSaveSync(*pending.cloud_account)) { + g_online_action_status = "Syncing Cloud Saves before creating the lobby..."; + return; + } + } + const bool modded = pending.content_enabled && view.manifest && has_mods(*view.manifest); + const auto request = std::move(pending); g_online_mod_host_request.reset(); if (modded && (!view.profile || !view.runtime)) { g_online_action_status = "Couldn't prepare the host's mods."; @@ -191,6 +202,9 @@ void PumpOnlineMods() { modded ? static_cast(encode(*view.manifest).size()) : 0)) { ReportOnlinePreparationFailure(g_online_action_status); g_online_mod_sync->cancel(); + } else if (!request.cloud_account->empty() && + dkr::store::service().view()->cloud_sync != dkr::cloud_saves::SyncStatus::Synced) { + g_online_action_status = "Cloud Saves could not finish. The lobby is using the local save."; } } else if (view.phase == SyncPhase::Failed) { g_online_action_status = view.error; diff --git a/runtime-recomp/src/game/runtime_online_ui.inl b/runtime-recomp/src/game/runtime_online_ui.inl index 600e92de..eae0806b 100644 --- a/runtime-recomp/src/game/runtime_online_ui.inl +++ b/runtime-recomp/src/game/runtime_online_ui.inl @@ -435,6 +435,7 @@ struct OlInputOptions { bool disabled = false; ImGuiInputTextFlags flags = 0; ImGuiInputTextCallback callback = nullptr; + float height = 44.0F; }; // A text field (.online-page input[type=text]). A controller cannot type into @@ -451,7 +452,7 @@ OlInputResult OlInput(const char* id, const char* label, char* buffer, std::size ImGui::PushFont(type.font); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8.0F); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0F); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {12.0F, std::max((44.0F - font_size) * 0.5F, 0.0F)}); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {12.0F, std::max((options.height - font_size) * 0.5F, 0.0F)}); ImGui::PushStyleColor(ImGuiCol_FrameBg, PaddockRgb(0x061D2C)); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, PaddockRgb(0x061D2C)); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, PaddockRgb(0x061D2C)); @@ -495,7 +496,7 @@ OlInputResult OlInput(const char* id, const char* label, char* buffer, std::size } ImGui::SameLine(0, 8); ImGui::BeginDisabled(options.disabled); - const bool keyboard = PaddockKeyboardButton(); + const bool keyboard = PaddockKeyboardButton(options.height); ImGui::EndDisabled(); ImGui::EndGroup(); ImGui::PopID(); @@ -1573,8 +1574,9 @@ void DrawOlHostCard(ImVec2 at, float width, float height, const OnlineFrame& fra g_online_page.section = OlSection::Settings; ImGui::EndGroup(); ImGui::SetCursorScreenPos({x, at.y + height - 2.0F - board.pad_bottom - 52.0F}); - if (OlCta("CREATE LOBBY", OlCtaColour::Green, inner, - !frame.launcher || !frame.rom_ready || frame.active || OnlineModSelectionLocked() || + const bool preparing_host = OnlineModSelectionLocked(); + if (OlCta(preparing_host ? "PREPARING LOBBY..." : "CREATE LOBBY", OlCtaColour::Green, inner, + !frame.launcher || !frame.rom_ready || frame.active || preparing_host || (dkr::online::view()->feature_enabled && !dkr::online::view()->connected) || (dkr::online::view()->public_desired && !dkr::online::view()->connected))) { g_online_page.join_attempted = false; @@ -3118,7 +3120,7 @@ void DrawOlStartBar(float width, const OnlineFrame& frame) { } if (view.host) { ImGui::SetCursorScreenPos(pair ? ImVec2{at.x + button + 10.0F, at.y} : ImVec2{at.x, at.y + 52.0F + 10.0F}); - const bool can_start = !frame.busy && total >= 2U && ready == total && saves_ready; + const bool can_start = !frame.busy && !SharedSaveBusy() && total >= 2U && ready == total && saves_ready; if (OlCta("START RACE", OlCtaColour::Red, button, !can_start)) { std::string error; if (!online.request_start(error)) diff --git a/runtime-recomp/src/game/runtime_platform.cpp b/runtime-recomp/src/game/runtime_platform.cpp index cec72d6e..aec5c7e2 100644 --- a/runtime-recomp/src/game/runtime_platform.cpp +++ b/runtime-recomp/src/game/runtime_platform.cpp @@ -1,3 +1,4 @@ +#include "time_trial/session.hpp" #include "controller_feedback/service.hpp" #include "library_ui/surface_policy.hpp" #include "look_behind/policy.hpp" @@ -68,6 +69,9 @@ extern "C" bool dkr_handle_fullscreen_event(const SDL_Event* event); namespace { +#if DKR_RUNTIME_HAS_RT64 +void close_startup_cover(); +#endif std::atomic g_audio_buffers{0}; constexpr std::size_t kControllerCount = 4; std::array, kControllerCount> g_buttons{}; @@ -1322,6 +1326,7 @@ void dkr::runtime::platform::shutdown() { CancelSdl3InputProbe(); g_sdl3_input_client.stop(); std::scoped_lock lock(g_platform_mutex); + close_startup_cover(); if (g_cursor_hidden) { SDL_ShowCursor(SDL_ENABLE); g_cursor_hidden = false; @@ -1442,6 +1447,60 @@ ultramodern::renderer::WindowHandle dkr::runtime::platform::create_window() { #endif } +namespace { +SDL_Window* startup_cover = nullptr; +bool startup_cover_returning = false; +std::atomic startup_cover_ready{false}; +std::chrono::steady_clock::time_point startup_cover_timeout; + +void close_startup_cover() { + if (startup_cover) { + SDL_DestroyWindow(startup_cover); + startup_cover = nullptr; + } + startup_cover_returning = false; +} +} // namespace + +void dkr::runtime::platform::show_startup_cover(void* surface, bool returning) { +#if defined(_WIN32) || (defined(__linux__) && !defined(__ANDROID__)) + close_startup_cover(); + if (!surface || !g_window) + return; + int x, y, width, height; + SDL_GetWindowPosition(g_window, &x, &y); + SDL_GetWindowSize(g_window, &width, &height); + startup_cover = SDL_CreateWindow(returning ? "DKR-R Returning" : "DKR-R Starting", x, y, width, height, + SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALWAYS_ON_TOP | SDL_WINDOW_SKIP_TASKBAR | + SDL_WINDOW_TOOLTIP | SDL_WINDOW_HIDDEN); + if (!startup_cover) + return; + if (auto* pixels = SDL_GetWindowSurface(startup_cover)) { + if (SDL_BlitScaled(static_cast(surface), nullptr, pixels, nullptr) == 0) { + startup_cover_ready.store(false, std::memory_order_relaxed); + startup_cover_returning = returning; + startup_cover_timeout = std::chrono::steady_clock::now() + std::chrono::seconds(15); + SDL_ShowWindow(startup_cover); + if (SDL_UpdateWindowSurface(startup_cover) == 0) + return; + } + } + close_startup_cover(); +#else + (void)surface; + (void)returning; +#endif +} + +void dkr::runtime::platform::finish_run_return_cover() { + if (startup_cover_returning) + close_startup_cover(); +} + +void dkr::runtime::platform::startup_frame_presented() { + startup_cover_ready.store(true, std::memory_order_release); +} + ultramodern::renderer::WindowHandle dkr::runtime::platform::prepare_window_for_game() { #if defined(_WIN32) if (g_window && g_retire_launcher_window_for_game) { @@ -1500,6 +1559,8 @@ ultramodern::renderer::WindowHandle dkr::runtime::platform::prepare_window_for_g } void* dkr::runtime::platform::prepare_window_for_launcher(bool retire_game_surface) { + if (!startup_cover_returning) + close_startup_cover(); #if defined(_WIN32) if (retire_game_surface && g_window) { // Called only after both owned runtime workers and their GPU owners @@ -1550,6 +1611,9 @@ void* dkr::runtime::platform::prepare_window_for_launcher(bool retire_game_surfa } void dkr::runtime::platform::pump_window_events(void*) { + if (startup_cover && (startup_cover_ready.load(std::memory_order_acquire) || + std::chrono::steady_clock::now() >= startup_cover_timeout)) + close_startup_cover(); pump_input_backend_events(); if (dkr::runtime::ui::lifecycle_request() != dkr::runtime::ui::LifecycleRequest::None) { ultramodern::quit(); @@ -1557,6 +1621,11 @@ void dkr::runtime::platform::pump_window_events(void*) { } SDL_Event event{}; while (SDL_PollEvent(&event) != 0) { + if (startup_cover && event.type == SDL_WINDOWEVENT && event.window.windowID == SDL_GetWindowID(startup_cover)) { + if (event.window.event == SDL_WINDOWEVENT_EXPOSED) + SDL_UpdateWindowSurface(startup_cover); + continue; + } #if defined(DKR_IOS) if (event.type == SDL_APP_DIDENTERFOREGROUND) dkr::runtime::ios::import_inbox(); @@ -1875,9 +1944,8 @@ void dkr::runtime::platform::update_ui_gamepad_navigation() { #endif -void dkr::runtime::platform::queue_audio(std::int16_t* samples, std::size_t sample_count) { - if (!dkr::runtime::netplay::external_side_effects_allowed()) - return; +namespace { +void queue_audio_output(const std::int16_t* samples, std::size_t sample_count, bool mix_track_recording = true) { dkr::runtime::telemetry::record_audio_buffer(sample_count); const auto index = ++g_audio_buffers; #if DKR_RUNTIME_HAS_RT64 @@ -1945,7 +2013,7 @@ void dkr::runtime::platform::queue_audio(std::int16_t* samples, std::size_t samp } // Mixed before the equaliser and master volume, so it is heard // exactly as the game's own music would be. - const bool custom_music_active = dkr::runtime::custom_music::active(); + const bool custom_music_active = mix_track_recording && dkr::runtime::custom_music::active(); if (custom_music_active) { g_custom_music_buffer.assign(sample_count, 0.0F); dkr::runtime::custom_music::render(g_custom_music_buffer.data(), sample_count / 2U, g_audio_frequency); @@ -2000,6 +2068,85 @@ void dkr::runtime::platform::queue_audio(std::int16_t* samples, std::size_t samp #endif } +} // namespace + +void dkr::runtime::platform::queue_audio(std::int16_t* samples, std::size_t sample_count) { + if (time_trial::preparing_ghost()) + return; + if (!dkr::runtime::netplay::external_side_effects_allowed()) + return; +#if DKR_RUNTIME_HAS_RT64 + if (time_trial::watching() && sample_count != 0 && sample_count <= 8192 && (sample_count & 1U) == 0 && + custom_music::active()) { + std::scoped_lock lock(g_platform_mutex); + // Archive the host-rendered track recording on the same update as + // the guest's DMA audio. The DMA stereo pairs stay in R,L order. + g_custom_music_buffer.assign(sample_count, 0.0F); + custom_music::render(g_custom_music_buffer.data(), sample_count / 2U, g_audio_frequency); + g_audio_swap_buffer.resize(sample_count); + for (std::size_t i = 0; i < sample_count; ++i) { + const float mixed = samples[i] + g_custom_music_buffer[i ^ 1U]; + g_audio_swap_buffer[i] = static_cast(std::lround(std::clamp(mixed, -32768.0F, 32767.0F))); + } + if (time_trial::theatre_capture_audio(g_audio_swap_buffer)) + return; + } +#endif + if (!time_trial::theatre_capture_audio({samples, sample_count})) + queue_audio_output(samples, sample_count); +} + +void dkr::runtime::platform::queue_theatre_audio(std::span samples, unsigned speed, + unsigned previous, unsigned frame) { +#if DKR_RUNTIME_HAS_RT64 + unsigned rate; + { + std::scoped_lock lock(g_platform_mutex); + rate = g_audio_frequency; + } + const auto frames = samples.size() / 2; + const auto sample_at = [rate, speed](unsigned update) { + return std::uint64_t(rate) * update * 100 / (30 * speed); + }; + const auto output_frames = static_cast(sample_at(frame) - sample_at(previous)); + if (!frames || !output_frames) + return; + if (frames == output_frames) { + queue_audio_output(samples.data(), samples.size(), false); + return; + } + // The mixer now supplies one block per authored update. Account for + // the N64's 16-sample alignment and apply the selected viewing speed. + std::vector converted(output_frames * 2); + for (std::size_t i = 0; i < output_frames; ++i) { + const auto position = i * frames; + const auto first = position / output_frames; + const auto second = std::min(frames - 1, first + 1); + const auto weight = static_cast(position % output_frames) / static_cast(output_frames); + for (std::size_t channel = 0; channel < 2; ++channel) + converted[2 * i + channel] = static_cast( + std::lerp(samples[2 * first + channel], samples[2 * second + channel], weight)); + } + queue_audio_output(converted.data(), converted.size(), false); +#else + (void)samples; + (void)speed; + (void)previous; + (void)frame; +#endif +} + +void dkr::runtime::platform::clear_theatre_audio() { +#if DKR_RUNTIME_HAS_RT64 + std::scoped_lock lock(g_platform_mutex); + if (g_audio_device != 0) { + SDL_ClearQueuedAudio(g_audio_device); + SDL_PauseAudioDevice(g_audio_device, 1); + g_audio_playback_started = false; + } +#endif +} + void dkr::runtime::platform::request_ui_tone(float frequency_hz, std::uint32_t duration_ms) { const float clamped_frequency = std::clamp(frequency_hz, 80.0F, 4000.0F); const std::uint32_t clamped_duration = std::clamp(duration_ms, 20U, 500U); @@ -2049,6 +2196,13 @@ void dkr::runtime::platform::set_treble_gain(float decibels) { } std::size_t dkr::runtime::platform::audio_frames_remaining() { + // One authored replay update covers 735 samples at 22,050 Hz. A + // virtual AI residual of 192 selects the nearest 16-sample quantum + // (736) on the US v1.1 mixer. SDL drains on the independent playback + // clock, so its queued samples cannot provide this feedback. + constexpr std::size_t theatre_ai_residual_frames = 192U; + if (time_trial::watching()) + return theatre_ai_residual_frames; #if DKR_RUNTIME_HAS_RT64 std::scoped_lock lock(g_platform_mutex); if (g_audio_device != 0) { diff --git a/runtime-recomp/src/game/runtime_platform.hpp b/runtime-recomp/src/game/runtime_platform.hpp index badc33d9..5ffb5022 100644 --- a/runtime-recomp/src/game/runtime_platform.hpp +++ b/runtime-recomp/src/game/runtime_platform.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include "ultramodern/input.hpp" #include "ultramodern/renderer_context.hpp" #include "controller_assignment_policy.hpp" @@ -27,6 +28,9 @@ bool input_backend_switch_pending(); #if DKR_RUNTIME_HAS_RT64 ultramodern::renderer::WindowHandle create_window(); ultramodern::renderer::WindowHandle prepare_window_for_game(); +void show_startup_cover(void* surface, bool returning = false); +void finish_run_return_cover(); +void startup_frame_presented(); void* prepare_window_for_launcher(bool retire_game_surface = false); void pump_window_events(void*); void* sdl_window(); @@ -38,6 +42,8 @@ void pump_input_backend_events(); #endif void queue_audio(std::int16_t* samples, std::size_t sample_count); +void queue_theatre_audio(std::span samples, unsigned speed, unsigned previous, unsigned frame); +void clear_theatre_audio(); // Requests a short, presentation-only synthesized UI cue. Launcher cues use a // host-only audio path; in-game cues are mixed into the next host audio block. // Neither path advances or mutates DKR's emulated audio state. diff --git a/runtime-recomp/src/game/runtime_play_ui.inl b/runtime-recomp/src/game/runtime_play_ui.inl index 95aa4be4..b7895562 100644 --- a/runtime-recomp/src/game/runtime_play_ui.inl +++ b/runtime-recomp/src/game/runtime_play_ui.inl @@ -699,7 +699,7 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live ImGui::PopStyleColor(); ImGui::SetCursorScreenPos({content_left, y + actions_height + 14.F}); ImGui::BeginGroup(); - DrawPlaySaveSummary(content_inner, live); + DrawPlaySaveSummary(content_inner, live, launch_modal); ImGui::EndGroup(); const float resume_bottom = ImGui::GetItemRectMax().y; @@ -712,7 +712,7 @@ void DrawPlayPage(float available_width, const PlayPageContext& play, bool live const float tools_y = std::max(resume_bottom, ImGui::GetItemRectMax().y) + 8.F; const float tools_width = std::max(1.F, width - 36.F); ImGui::SetCursorScreenPos({at.x + 18.F, tools_y + 10.F}); - DrawPlayTools(tools_width); + DrawPlayTools(tools_width, live); const float final_height = ImGui::GetItemRectMax().y + 18.F - at.y; draw->AddLine({at.x + 18.F, tools_y}, {at.x + width - 18.F, tools_y}, PaddockCol(0x325365)); if (side) diff --git a/runtime-recomp/src/game/runtime_quick_restart.cpp b/runtime-recomp/src/game/runtime_quick_restart.cpp index 0fbe4545..39c2f698 100644 --- a/runtime-recomp/src/game/runtime_quick_restart.cpp +++ b/runtime-recomp/src/game/runtime_quick_restart.cpp @@ -4,6 +4,7 @@ #include "game_payload.hpp" #include "runtime_enhancements.hpp" #include "runtime_input.hpp" +#include "time_trial/session.hpp" #include "revision_addresses.hpp" #include "recomp.h" @@ -63,6 +64,9 @@ extern "C" void dkr_quick_restart_poll(std::uint8_t* rdram, recomp_context* cont return; } + if (dkr::runtime::time_trial::request_restart()) + return; + const dkr::runtime::GamePayload* payload = dkr::runtime::active_payload(); if (payload == nullptr || payload->get_settings == nullptr || payload->leveltable_type == nullptr || payload->sound_clear_delayed == nullptr || payload->reset_delayed_text == nullptr || diff --git a/runtime-recomp/src/game/runtime_save_routing.cpp b/runtime-recomp/src/game/runtime_save_routing.cpp index 08639a7e..189abcb0 100644 --- a/runtime-recomp/src/game/runtime_save_routing.cpp +++ b/runtime-recomp/src/game/runtime_save_routing.cpp @@ -3,6 +3,7 @@ #include "netplay/netplay_types.hpp" #include "save_manager.hpp" #include "save_storage.hpp" +#include "shared_saves.hpp" #include "ultramodern/ultramodern.hpp" @@ -17,7 +18,8 @@ dkr::runtime::saves::RuntimeOnlineSaveStatus g_runtime_save_status; struct SaveContext { std::filesystem::path path, paks; std::shared_ptr lease; - bool online = false, host = false, loaded = false, incomplete = false, development = false; + bool online = false, host = false, loaded = false, incomplete = false, development = false, time_trial = false; + dkr::runtime::saves::ReplaySave replay_save = dkr::runtime::saves::ReplaySave::Blank; std::uint64_t match = 0, hash = 0; std::string failure; }; @@ -104,7 +106,7 @@ bool dkr::runtime::saves::prepare_runtime_save_context(const std::filesystem::pa std::uint64_t match, std::uint64_t hash, std::string& error, bool development) { std::scoped_lock lock(g_runtime_save_mutex); - if (g_context.lease) { + if (g_context.lease || g_context.time_trial) { error = "The previous save owner has not retired."; return false; } @@ -144,6 +146,19 @@ bool dkr::runtime::saves::prepare_runtime_save_context(const std::filesystem::pa error.clear(); return true; } + +bool dkr::runtime::saves::prepare_time_trial_save_context(std::string& error, ReplaySave seed) { + std::scoped_lock lock(g_runtime_save_mutex); + if (g_context.lease || g_context.time_trial) { + error = "The previous save owner has not retired."; + return false; + } + g_context = {}; + g_context.time_trial = true; + g_context.replay_save = seed; + return true; +} + void dkr::runtime::saves::retire_runtime_save_context() { std::scoped_lock lock(g_runtime_save_mutex); g_context = {}; @@ -152,6 +167,8 @@ void dkr::runtime::saves::retire_runtime_save_context() { } bool dkr::runtime::saves::runtime_save_context_ready() { std::scoped_lock lock(g_runtime_save_mutex); + if (g_context.time_trial) + return g_context.loaded && ultramodern::get_save_file_path().empty(); if (!g_context.lease || !g_context.loaded || !g_context.failure.empty()) return false; // Verify what init_saving actually loaded, not a second proposed route. @@ -189,6 +206,24 @@ dkr::runtime::saves::RuntimeSaveSelection dkr::runtime::saves::runtime_save_sele } bool dkr::runtime::saves::load_runtime_save(const std::filesystem::path& path, std::vector& buffer) { std::scoped_lock lock(g_runtime_save_mutex); + if (g_context.time_trial) { + if (!path.empty()) { + g_context.failure = "Time Trial cannot load a file-backed save."; + return false; + } + if (g_context.replay_save == ReplaySave::MissingAdventure) { + // Match the runtime's missing-file boot. Reads and writes stay in memory. + buffer.assign(codec::kImageSize, 0); + } else { + auto image = codec::blank_image(); + if (g_context.replay_save == ReplaySave::CompletedAdventure) + shared::complete(image, 0); + const auto bytes = codec::encode(image); + buffer.assign(bytes.begin(), bytes.end()); + } + g_context.loaded = true; + return true; + } std::vector bytes; if (!g_context.lease || storage::absolute(path) != g_context.path) { g_context.failure = "The runtime tried to load a save outside its launch scope."; @@ -217,6 +252,8 @@ bool dkr::runtime::saves::load_runtime_save(const std::filesystem::path& path, s } bool dkr::runtime::saves::commit_runtime_save(const std::filesystem::path& path, const std::vector& buffer) { std::scoped_lock lock(g_runtime_save_mutex); + if (g_context.time_trial) + return false; if (!g_context.lease || !g_context.loaded || storage::absolute(path) != g_context.path) { g_context.failure = "A stale save write was refused outside its launch scope."; return false; @@ -237,7 +274,7 @@ bool dkr::runtime::saves::commit_runtime_save(const std::filesystem::path& path, return true; } std::string error; - if (!storage::write_atomic(path, bytes, ValidRuntimeImage, error)) { + if (!storage::write_progress(path, bytes, ValidRuntimeImage, error)) { g_context.failure = error; std::fprintf(stderr, "[save][commit] %s\n", error.c_str()); return false; diff --git a/runtime-recomp/src/game/runtime_save_routing.hpp b/runtime-recomp/src/game/runtime_save_routing.hpp index c90dc051..91bdeb8f 100644 --- a/runtime-recomp/src/game/runtime_save_routing.hpp +++ b/runtime-recomp/src/game/runtime_save_routing.hpp @@ -23,6 +23,8 @@ bool prepare_runtime_save_context(const std::filesystem::path& root, const std:: const std::filesystem::path& offline_paks, bool online, bool host, std::uint64_t match_id, std::uint64_t expected_hash, std::string& error, bool development = false); +enum class ReplaySave { Blank, MissingAdventure, CompletedAdventure }; +bool prepare_time_trial_save_context(std::string& error, ReplaySave seed); void retire_runtime_save_context(); bool runtime_save_context_ready(); bool runtime_save_writes_allowed(); diff --git a/runtime-recomp/src/game/runtime_saves_ui.inl b/runtime-recomp/src/game/runtime_saves_ui.inl index b4eb76f0..3628c47d 100644 --- a/runtime-recomp/src/game/runtime_saves_ui.inl +++ b/runtime-recomp/src/game/runtime_saves_ui.inl @@ -3,25 +3,20 @@ // repairs, resets and the Save Builder go through dkr::runtime::saves exactly // as before. // -// SAVE MANAGER in the look of tools/launcher-html (pages/saves.js, -// styles/saves.css): the current save, then Overview / Edit progress / -// Transfer & Paks. Edits stay in a draft until they are applied, and every -// replacing action asks first. +// The slot list and editor share each scope's draft. File operations and +// quick actions keep the same confirmation and backup flow. + +enum class SaveEditorSection { Progress, Unlocks, Files }; struct SavesPageState { ImGuiContext* context = nullptr; int last_frame = -100; - int section = 0; // Overview, Edit progress, Transfer & Paks - int scope = 0; // Offline, Online, Modded, Recovery - int tab = 0; // Slot 1-3, Unlocks, Records - std::array courses_open{}; - std::array records_open{}; - bool all_backups = false; - // The save as it was loaded into the builder, to tell a draft's changes. - std::optional original; - // The slot summaries on Overview, read again with the view cache. - std::optional summary; - std::chrono::steady_clock::time_point summary_at{}; + SaveEditorSection section = SaveEditorSection::Progress; + int scope = 0; // Vanilla, Online, Modded, Recovery + bool personal_modded = false; + bool import_modded = false; + int selected_slot = 0; + bool scroll_editor_to_top = false; // The confirmation in flight. enum class Ask { None, @@ -45,9 +40,8 @@ struct SavesPageState { SavesPageState g_saves_page; constexpr unsigned kSavesAccent = 0x1AC2A3; -constexpr unsigned kSavesError = 0xFFAAA0; -enum class SavesTone { Plain, Primary, Danger }; +enum class SavesTone { Plain, Primary, Featured, Danger }; // .saves-button: a race button on the page's quiet #123e50, or the accent // primary, or the danger red. @@ -60,6 +54,9 @@ bool SavesRaceButton(const char* label, float width = 0.0F, SavesTone tone = Sav look.border = kSavesAccent; look.text = 0x062C30; look.text_shadow = false; + } else if (tone == SavesTone::Featured) { + look.fill = 0xAD481C; + look.border = kSetWarm; } else if (tone == SavesTone::Danger) { look.fill = 0x73171A; look.border = 0xD97773; @@ -116,76 +113,13 @@ std::string SavesBackupTime(const std::filesystem::path& path) { return text; } -bool SavesDraftDirty() { +bool SavesDraftDirty(const AdventureDraft& draft) { using dkr::runtime::saves::codec::encode; - return g_save_builder_image && g_saves_page.original && - encode(*g_save_builder_image) != encode(*g_saves_page.original); -} - -void SavesForgetDraft() { - g_save_builder_image.reset(); - g_saves_page.original.reset(); - g_saves_page.summary.reset(); + return draft.image && draft.original && encode(*draft.image) != encode(*draft.original); } // ------------------------------------------------------------ editor -// A row of quiet tabs over a hairline (.saves-tabs). -int SavesEditorTabs(const std::vector& labels, int current, float width) { - const PaddockType type = PaddockSign(17.0F, 1.2F, 0.0F); - const ImVec2 at = ImGui::GetCursorScreenPos(); - ImDrawList* draw = ImGui::GetWindowDrawList(); - float natural = 8.0F + 4.0F * static_cast(labels.size() - 1U); - std::vector widths; - for (const char* label : labels) { - widths.push_back(std::ceil(PaddockMeasure(type, label) + 28.0F)); - natural += widths.back(); - } - // flex: 1 0 auto shares the spare room between the tabs. - const float spare = std::max(width - natural, 0.0F) / static_cast(labels.size()); - int picked = -1; - float x = at.x + 4.0F; - for (std::size_t index = 0; index < labels.size(); ++index) { - const float tab_width = widths[index] + spare; - ImGui::SetCursorScreenPos({x, at.y + 4.0F}); - ImGui::PushID(static_cast(index)); - const PaddockPress press = PaddockBeginPress("##tab", {tab_width, 44.0F}); - ImGui::PopID(); - if (press.pressed) - picked = static_cast(index); - const bool selected = static_cast(index) == current; - const PaddockRadii radii{6.0F, 6.0F, 0.0F, 0.0F}; - if (selected) { - PaddockFill(draw, press.min, press.max, radii, PaddockCol(0x123E50)); - } else if (press.hover > 0.0F) { - PaddockFill(draw, press.min, press.max, radii, - PaddockApply(PaddockMix(PaddockRgb(0x174C60, 0U), PaddockRgb(0x174C60), press.hover))); - } - if (selected) { - draw->AddRectFilled({press.min.x, press.max.y - 3.0F}, press.max, PaddockCol(kSetWarm)); - } - const unsigned ink = selected ? 0xFFF0C2U : press.hover > 0.5F ? kSetText : kSetMuted; - const float text_width = PaddockMeasure(type, labels[index]); - PaddockDrawRun(draw, type, - {std::round(press.min.x + (tab_width - text_width) * 0.5F), - std::round(press.min.y + (44.0F - 3.0F - type.line) * 0.5F)}, - PaddockCol(ink), labels[index], labels[index] + std::strlen(labels[index])); - PaddockEndPress(press, 6.0F, 1.0F, false); - if (press.focused) { - draw->AddRect({press.min.x + 1.5F, press.min.y + 1.5F}, {press.max.x - 1.5F, press.max.y - 1.5F}, - PaddockCol(kSetFocus), 6.0F, 0, 3.0F); - } - x += tab_width + 4.0F; - } - const float bottom = at.y + 4.0F + 44.0F; - draw->AddRectFilled({at.x, bottom}, {at.x + width, bottom + 1.0F}, PaddockCol(kSetBorder)); - ImGui::SetCursorScreenPos(at); - ImGui::Dummy({width, bottom + 1.0F - at.y}); - return picked; -} - -// A grid of settings (.saves-setting-grid): three columns, two below 780 px of -// panel and one below 540 px. struct SavesGrid { int count = 0; ImVec2 origin{}; @@ -195,7 +129,7 @@ struct SavesGrid { float row_bottom = 0.0F; SavesGrid(float width, float panel) : origin(ImGui::GetCursorScreenPos()) { - per_row = panel <= 540.0F ? 1 : panel <= 780.0F ? 2 : 3; + per_row = panel < 375.0F ? 1 : panel < 545.0F ? 2 : 3; column = std::floor((width - 16.0F * static_cast(per_row - 1)) / static_cast(per_row)); row_top = row_bottom = origin.y; } @@ -219,14 +153,27 @@ struct SavesGrid { } }; -void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int slot_index) { +void DrawSavesSlotEditor(SavesPageState& state, float outer, int slot_index) { using namespace dkr::runtime::saves::codec; - AdventureSlot& slot = g_save_builder_image->slots[static_cast(slot_index)]; + AdventureSlot& slot = g_adventure_drafts[state.personal_modded].image->slots[static_cast(slot_index)]; ImGui::PushID(slot_index); - PaddockText(PaddockSign(19.0F, 1.45F, 0.0F), PaddockRgb(kSetText), "Racer initials", width); - PaddockGap(13.0F); + const auto paint = [](ImDrawList* draw, ImVec2 min, ImVec2 max) { + PaddockPanel(draw, min, max, {PaddockRound(9.0F), PaddockRgb(0x102E40), PaddockRgb(kSetBorder), 1.0F}); + }; + const auto title = [](const char* caption, float width) { + PaddockText(PaddockSign(19.0F, 1.2F, 0.0F), PaddockRgb(kSetText), caption, width); + PaddockGap(8.0F); + }; + + PaddockBox balloon_box(outer, {10.0F, 10.0F}); + const float width = balloon_box.Inner(); + title("Golden balloons", width); + const auto summary = ImGui::GetCursorScreenPos(); + const float initials_width = std::min(width, 290.0F); + PaddockText(PaddockReading(16.0F, true, 1.25F), PaddockRgb(kSetText), "Racer initials", initials_width); + PaddockGap(6.0F); { - // Three letter pickers, 280 px wide together (.saves-initials). + // Three letter pickers sized for the widest initial (.saves-initials). static const std::vector kLetters = [] { std::vector letters; for (char letter = 'A'; letter <= 'Z'; ++letter) @@ -238,7 +185,7 @@ void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int sl }(); std::string padded = sanitise_name(slot.name); padded.resize(3U, ' '); - const float cell = std::floor((std::min(width, 280.0F) - 16.0F) / 3.0F); + const float cell = std::floor((initials_width - 16.0F) / 3.0F); const ImVec2 at = ImGui::GetCursorScreenPos(); for (int character = 0; character < 3; ++character) { ImGui::SetCursorScreenPos({at.x + (cell + 8.0F) * static_cast(character), at.y}); @@ -261,26 +208,26 @@ void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int sl } ImGui::SetCursorScreenPos({at.x, at.y + 52.0F}); ImGui::Dummy({width, 0.0F}); - PaddockGap(20.0F); } - - SavesSeparator("Golden Balloons", width, false); + const float letters_bottom = ImGui::GetCursorScreenPos().y; + const bool inline_total = width >= initials_width + 170.0F; + const float total_width = inline_total ? width - initials_width - 16.0F : width; + if (inline_total) + ImGui::SetCursorScreenPos({summary.x + initials_width + 16.0F, summary.y + 24.0F}); + else + PaddockGap(8.0F); int hub = static_cast(hub_balloons(slot)); const unsigned bonus = bonus_balloons(slot); - SavesNote(bonus > 0U ? "Up to 7 on the central island and 8 in each world. Remove the bonus balloons before " - "lowering the central island." - : "Up to 7 on the central island and 8 in each world. The total updates automatically.", - width); { // The total (.saves-progress): a dark bar that fills amber. const ImVec2 at = ImGui::GetCursorScreenPos(); ImDrawList* draw = ImGui::GetWindowDrawList(); - PaddockFill(draw, at, {at.x + width, at.y + 32.0F}, PaddockRound(6.0F), PaddockCol(0x153E50)); + PaddockFill(draw, at, {at.x + total_width, at.y + 32.0F}, PaddockRound(6.0F), PaddockCol(0x153E50)); const float t = std::min(1.0F, static_cast(slot.balloons[0]) / static_cast(kMaximumTotalBalloons)); if (t > 0.0F) { - draw->PushClipRect(at, {at.x + width * t, at.y + 32.0F}, true); - PaddockFill(draw, at, {at.x + width, at.y + 32.0F}, PaddockRound(6.0F), PaddockCol(0x806000)); + draw->PushClipRect(at, {at.x + total_width * t, at.y + 32.0F}, true); + PaddockFill(draw, at, {at.x + total_width, at.y + 32.0F}, PaddockRound(6.0F), PaddockCol(0x806000)); draw->PopClipRect(); } std::string total = std::to_string(slot.balloons[0] - bonus) + " / " + std::to_string(kMaximumTotalBalloons); @@ -289,15 +236,18 @@ void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int sl const PaddockType type = PaddockReading(16.0F, true, 1.0F); const float text_width = PaddockMeasure(type, total); PaddockDrawRun(draw, type, - {std::round(at.x + (width - text_width) * 0.5F), std::round(at.y + (32.0F - type.line) * 0.5F)}, + {std::round(at.x + (total_width - text_width) * 0.5F), std::round(at.y + (32.0F - type.line) * 0.5F)}, PaddockCol(kSetText), total.data(), total.data() + total.size()); - ImGui::Dummy({width, 32.0F}); + ImGui::Dummy({total_width, 32.0F}); + const float total_bottom = ImGui::GetItemRectMax().y; + ImGui::SetCursorScreenPos({summary.x, std::max(letters_bottom, total_bottom)}); + ImGui::Dummy({width, 0.0F}); PaddockGap(18.0F); } constexpr std::array kAreas{ - {"DKR-R", "Dino Domain", "Sherbet Island", "Snowflake Mountain", "Dragon Forest", "Future Fun Land"}}; + {"Central island", "Dino Domain", "Sherbet Island", "Snowflake Mountain", "Dragon Forest", "Future Fun Land"}}; const auto count = [](int value) { return SettingsRangeValue{std::to_string(value), ""}; }; - SavesGrid balloons(width, panel); + SavesGrid balloons(width, width); for (std::size_t area = 0; area < kWorldCount; ++area) { balloons.Begin(); ImGui::PushID(static_cast(area)); @@ -318,26 +268,49 @@ void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int sl } balloons.Finish(width); - SavesSeparator("Bonus balloons", width, false); - SavesNote("Extra balloons from the Free Balloon magic code. They need a full central island.", width); - SavesGrid extra(width, panel); - extra.Begin(); + const auto bonus_row = ImGui::GetCursorScreenPos(); + const float remove_width = SettingsButtonWidth("Remove bonus balloons"); + const bool inline_bonus = width >= remove_width + 180.0F; int bonus_value = static_cast(bonus_balloons(slot)); const int bonus_limit = static_cast(maximum_bonus_balloons(slot)); - if (SettingsRange("##bonus-balloons", "Bonus balloons", &bonus_value, 0, bonus_limit, extra.column, count, {}, - bonus_limit == 0)) { + if (SettingsRange("##bonus-balloons", "Bonus balloons", &bonus_value, 0, bonus_limit, + inline_bonus ? width - remove_width - 9.0F : width, count, {}, bonus_limit == 0)) { set_balloon_total(slot, hub_balloons(slot), static_cast(bonus_value)); } - extra.End(); - extra.Finish(width); - if (SavesRaceButton("REMOVE BONUS BALLOONS", 0.0F, SavesTone::Plain, bonus_balloons(slot) == 0U, - "This slot has no bonus balloons.")) { + const float bonus_bottom = ImGui::GetCursorScreenPos().y; + if (inline_bonus) + ImGui::SetCursorScreenPos({bonus_row.x + width - remove_width, bonus_row.y}); + if (SettingsButton("Remove bonus balloons", remove_width, bonus_balloons(slot) == 0U)) set_balloon_total(slot, hub_balloons(slot), 0U); + ImGui::SetCursorScreenPos({bonus_row.x, std::max(bonus_bottom, ImGui::GetItemRectMax().y)}); + ImGui::Dummy({width, 0.0F}); + balloon_box.End(paint); + + PaddockGap(9.0F); + PaddockBox trophy_box(outer, {10.0F, 10.0F}); + title("Trophy races", width); + constexpr std::array kTrophies{ + "Dino Domain", "Sherbet Island", "Snowflake Mountain", "Dragon Forest", "Future Fun Land"}; + SavesGrid trophies(width, width); + for (std::size_t world = 0; world < kTrophies.size(); ++world) { + trophies.Begin(); + ImGui::PushID(static_cast(world)); + const unsigned shift = static_cast(world) * 2; + int place = (slot.trophies >> shift) & 3; + if (SettingsDropdown("##trophy", kTrophies[world], &place, {"None", "Bronze", "Silver", "Gold"}, + trophies.column)) + slot.trophies = static_cast((slot.trophies & ~(3U << shift)) | + (static_cast(place) << shift)); + ImGui::PopID(); + trophies.End(); } - PaddockGap(20.0F); + trophies.Finish(width); - SavesSeparator("Amulets and keys", width, false); - SavesGrid keys(width, panel); + trophy_box.End(paint); + PaddockGap(9.0F); + PaddockBox keys_box(outer, {10.0F, 10.0F}); + title("Amulets and keys", width); + SavesGrid keys(width, width); keys.Begin(); int tt = slot.tt_amulet; if (SettingsRange("##tt-amulet", "T.T. amulet pieces", &tt, 0, kMaximumAmuletPieces, keys.column, count)) { @@ -369,36 +342,41 @@ void DrawSavesSlotEditor(SavesPageState& state, float width, float panel, int sl } keys.Finish(width); - bool& courses_open = state.courses_open[static_cast(slot_index)]; - if (SavesRaceButton(courses_open ? "HIDE COURSE PROGRESS (34)" : "SHOW COURSE PROGRESS (34)")) { - courses_open = !courses_open; - } - PaddockGap(16.0F); - if (courses_open) { - const auto& names = course_names(); - SavesGrid courses(width, panel); - for (std::size_t course = 0; course < kCourseCount; ++course) { + keys_box.End(paint); + PaddockGap(9.0F); + PaddockBox courses_box(outer, {10.0F, 10.0F}); + title("Course progress", width); + constexpr std::array kCourses{ + 3, 1, 20, 5, 6, 8, 2, 21, 10, 4, 7, 19, 14, 13, 15, 22, 12, 23, 11, 24, + 9, 17, 18, 16, 26, 29, 27, 31, 0, 30, 28, 32, 25, 33}; + const auto& names = course_names(); + for (std::size_t group = 0; group <= kTrophies.size(); ++group) { + const char* title = group < kTrophies.size() ? kTrophies[group] : "Challenges and bosses"; + PaddockText(PaddockReading(16.0F, true), PaddockRgb(kSetWarm), title, width); + PaddockGap(8.0F); + SavesGrid courses(width, width); + // Course IDs index the Adventure save's course status array. + const std::size_t last = group < kTrophies.size() ? (group + 1) * 4 : kCourses.size(); + for (std::size_t index = group * 4; index < last; ++index) { + const int course = kCourses[index]; courses.Begin(); - ImGui::PushID(static_cast(course)); + ImGui::PushID(course); int status = slot.course_status[course]; if (SettingsDropdown("course", names[course], &status, - {"Not started", "Race won", "Silver Coins won", "Complete"}, courses.column)) { + {"Not started", "Race won", "Silver Coins won", "Complete"}, courses.column)) slot.course_status[course] = static_cast(status); - } ImGui::PopID(); courses.End(); } courses.Finish(width); + PaddockGap(14.0F); } - if (SavesRaceButton("MAX OUT THIS ADVENTURE")) { - state.ask = SavesPageState::Ask::MaxOut; - state.slot = slot_index; - } + courses_box.End(paint); ImGui::PopID(); } void DrawSavesUnlocks(SavesPageState& state, float width, float panel) { - auto& settings = g_save_builder_image->settings; + auto& settings = g_adventure_drafts[state.personal_modded].image->settings; SavesGrid grid(width, panel); grid.Begin(); SettingsCheck("##adventure-two", "Adventure Two", &settings.adventure_two, grid.column); @@ -436,234 +414,68 @@ void DrawSavesUnlocks(SavesPageState& state, float width, float panel) { state.ask = SavesPageState::Ask::UnlockAll; } -void DrawSavesRecords(SavesPageState& state, float width) { - using namespace dkr::runtime::saves::codec; - PaddockText(PaddockSign(19.0F, 1.45F, 0.0F), PaddockRgb(kSetText), - "Personal records are view-only. Race in Time Trial mode to set or improve them.", width); - PaddockGap(13.0F); - const std::array*>, 2> kLists{{ - {"Fastest laps", &g_save_builder_image->fastest_laps}, - {"Course times", &g_save_builder_image->course_times}, - }}; - for (std::size_t list = 0; list < kLists.size(); ++list) { - ImGui::PushID(static_cast(list)); - // The summary (.saves-records summary): a quiet bar with a marker. - const PaddockPress press = PaddockBeginPress("##records", {width, 44.0F}); - bool& open = state.records_open[list]; - if (press.pressed) - open = !open; - ImDrawList* draw = ImGui::GetWindowDrawList(); - PaddockFill(draw, press.min, press.max, PaddockRound(8.0F), - PaddockApply(PaddockMix(PaddockRgb(0x123E50), PaddockRgb(0x174C60), press.hover))); - const PaddockType type = PaddockSign(19.0F, 1.2F, 0.0F); - const ImVec2 marker{press.min.x + 16.0F + 4.0F, (press.min.y + press.max.y) * 0.5F}; - if (open) { - draw->AddTriangleFilled({marker.x - 4.5F, marker.y - 3.0F}, {marker.x + 4.5F, marker.y - 3.0F}, - {marker.x, marker.y + 4.0F}, PaddockCol(kSetText)); - } else { - draw->AddTriangleFilled({marker.x - 3.0F, marker.y - 4.5F}, {marker.x + 4.0F, marker.y}, - {marker.x - 3.0F, marker.y + 4.5F}, PaddockCol(kSetText)); - } - PaddockDrawRun(draw, type, {press.min.x + 36.0F, std::round(press.min.y + (44.0F - type.line) * 0.5F)}, - PaddockCol(kSetText), kLists[list].first, kLists[list].first + std::strlen(kLists[list].first)); - PaddockEndPress(press, 8.0F, 1.0F); - if (open) { - const auto& records = *kLists[list].second; - for (std::size_t index = 0; index < records.size(); ++index) { - const ImVec2 at = ImGui::GetCursorScreenPos(); - PaddockGap(12.0F); - PaddockText(PaddockReading(16.0F, false, 1.4F), PaddockRgb(kSetText), record_names()[index], width); - PaddockGap(4.0F); - std::string detail = "Time: " + (records[index].time != 0U ? FormatRecordTime(records[index].time) - : std::string("No personal record yet")); - if (records[index].time != 0U) { - detail += " Racer: " + - (records[index].initials.empty() ? std::string("---") : records[index].initials); - } - PaddockText(PaddockReading(16.0F, false, 1.45F), PaddockRgb(kSetMuted), detail, width); - PaddockGap(12.0F); - const float bottom = ImGui::GetCursorScreenPos().y; - draw->AddRectFilled({at.x, bottom - 1.0F}, {at.x + width, bottom}, PaddockCol(kSetBorder)); - } - } - PaddockGap(12.0F); - ImGui::PopID(); +bool LoadSavesEditorDraft(SavesPageState& state, bool valid) { + auto& draft = g_adventure_drafts[state.personal_modded]; + if (draft.image || !valid) + return draft.image.has_value(); + dkr::runtime::saves::codec::SaveImage image; + std::string error; + if (!dkr::runtime::saves::shared::load_draft(image, draft.revision, error, state.personal_modded)) { + g_save_manager_status = error; + return false; } + draft.original = image; + draft.image = std::move(image); + return true; } -void DrawSavesEditor(SavesPageState& state, float width, float panel, bool editable, bool exists) { - using namespace dkr::runtime::saves; - if (!editable) { - SavesSeparator("A valid save is needed", width, false); - SavesNote(exists ? "Restore a valid backup or import a working save from Overview before editing." - : "Start an adventure in the game, import a save, or create a fresh adventure from Overview.", - width); - if (SavesRaceButton("GO TO OVERVIEW")) - state.section = 0; - return; - } - if (!g_save_builder_image) { - codec::SaveImage image{}; - std::string error; - if (load_adventure(image, error)) { - // Opening the editor must not silently normalise existing progress. - g_save_builder_image = image; - state.original = image; - g_shared_draft_revision = dkr::runtime::saves::shared::revision(); - } else { - g_save_manager_status = error; - return; - } - } - if (!state.original) - state.original = *g_save_builder_image; - SavesNote("Manual edits use Apply Changes. Completion and unlock buttons save when confirmed.", width); - const int picked = SavesEditorTabs({"SLOT 1", "SLOT 2", "SLOT 3", "UNLOCKS", "RECORDS"}, state.tab, width); - if (picked >= 0) - state.tab = picked; - PaddockGap(20.0F); - if (state.tab < 3) - DrawSavesSlotEditor(state, width, panel, state.tab); - else if (state.tab == 3) - DrawSavesUnlocks(state, width, panel); - else - DrawSavesRecords(state, width); +struct SavesFooterLayout { + float discard_width; + float apply_width; + bool stacked; + float height; +}; - // The draft bar (.saves-draft-bar): it rides the bottom of the panel - // while the editor scrolls under it. - PaddockGap(20.0F); - const bool dirty = SavesDraftDirty(); - const ImVec2 natural = ImGui::GetCursorScreenPos(); +SavesFooterLayout MeasureSavesFooter(float width) { const float discard_width = PaddockRaceButtonWidth("DISCARD CHANGES"); const float apply_width = PaddockRaceButtonWidth("APPLY CHANGES"); - const bool wraps = width - discard_width - apply_width - 24.0F < 180.0F; - const float bar_height = 1.0F + 16.0F + (wraps ? 49.0F + 12.0F + 44.0F : std::max(49.0F, 44.0F)) + 16.0F; + const bool stacked = width - discard_width - apply_width - 24.0F < 150.0F; + return {discard_width, apply_width, stacked, stacked ? 106.0F : 66.0F}; +} + +void DrawSavesDraftBar(const SavesPageState& state, float width, float top, const SavesFooterLayout& layout, + bool dirty, bool locked, SavesPageState::Ask& ask) { ImGuiWindow* window = ImGui::GetCurrentWindow(); - const float visible_bottom = PanelFooterBounds(window).Max.y; - const float top = std::min(natural.y, visible_bottom - bar_height); + const auto panel = PanelFooterBounds(window); + const float left = ImGui::GetCursorScreenPos().x; DrawPanelFooterBackground(window, top, PaddockCol(0x0A202C), PaddockCol(kSetBorder)); - if (SaveDraftLayoutCheck()) - g_save_draft_geometry = { - PanelFooterBounds(window), - {{window->Pos.x + window->WindowBorderSize, window->Pos.y + window->WindowBorderSize}, - {window->Pos.x + window->Size.x - window->WindowBorderSize - window->ScrollbarSizes.x, - window->Pos.y + window->Size.y - window->WindowBorderSize - window->ScrollbarSizes.y}}, - top, - dirty}; - // Its own child window, so it stays above the editor it covers for both - // drawing and the pointer. - ImGui::SetCursorScreenPos({natural.x, top}); - ImGui::BeginChild("##draft-bar", {width, bar_height}, false, - ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | - ImGuiWindowFlags_NavFlattened | ImGuiWindowFlags_NoBackground); - ImGui::SetCursorScreenPos({natural.x, top + 17.0F}); - ImGui::BeginGroup(); - const float text_width = wraps ? width : width - discard_width - apply_width - 24.0F; - PaddockText(PaddockReading(17.0F, false, 1.5F), PaddockRgb(kSetText), - dirty ? "Unapplied changes" : "No pending changes", text_width); - PaddockText(PaddockReading(14.0F, false, 1.45F), PaddockRgb(kSetMuted), "Applying creates a backup first.", - text_width); - ImGui::EndGroup(); - const float buttons_y = wraps ? top + 17.0F + 49.0F + 12.0F : top + 17.0F + (49.0F - 44.0F) * 0.5F; - ImGui::SetCursorScreenPos({wraps ? natural.x : natural.x + width - apply_width - 12.0F - discard_width, buttons_y}); - if (SavesRaceButton("DISCARD CHANGES", discard_width, SavesTone::Plain, !dirty, - "There are no changes to discard.")) { - state.ask = SavesPageState::Ask::Discard; - } - ImGui::SameLine(0.0F, 12.0F); - if (SavesRaceButton("APPLY CHANGES", apply_width, SavesTone::Primary, !dirty, "There are no changes to apply.")) { - state.ask = SavesPageState::Ask::Apply; + if (SaveDraftLayoutCheck()) { + g_save_draft_geometry.panel = panel; + g_save_draft_geometry.bounds = { + {window->Pos.x + window->WindowBorderSize, window->Pos.y + window->WindowBorderSize}, + {window->Pos.x + window->Size.x - window->WindowBorderSize - window->ScrollbarSizes.x, + window->Pos.y + window->Size.y - window->WindowBorderSize - window->ScrollbarSizes.y}}; + g_save_draft_geometry.top = top; + g_save_draft_geometry.dirty = dirty; } - ImGui::EndChild(); - ImGui::SetCursorScreenPos({natural.x, natural.y + bar_height}); - ImGui::Dummy({width, 0.0F}); -} - -// ------------------------------------------------------------ overview + ImGui::SetCursorScreenPos({left, top + (layout.stacked ? 10.0F : 17.0F)}); + const float text_width = layout.stacked ? width : width - layout.discard_width - layout.apply_width - 24.0F; + const std::string_view status = state.personal_modded ? (dirty ? "Modded Adventure · Unsaved changes" : "Modded Adventure") + : (dirty ? "Vanilla Adventure · Unsaved changes" : "Vanilla Adventure"); + PaddockText(PaddockReading(16.0F, true, 1.25F), PaddockRgb(kSetText), status, text_width); -void DrawSavesOverview(SavesPageState& state, float width, float panel, const SaveManagerViewCache& view, - bool editable) { - using namespace dkr::runtime::saves; - SavesNote( - "One personal save for normal play, with or without mods. Three Adventure slots, shared unlocks and records.", - width); - const bool busy = SharedSaveBusy(); - const auto button = [&](const char* label, bool disabled = false, SavesTone tone = SavesTone::Plain) { - return SavesRaceButton(label, 0, tone, busy || disabled); - }; - if (button("BACK UP SAVE", !editable, SavesTone::Primary)) - BeginSharedSaveJob( - [](std::string& error) { - std::filesystem::path created; - return backup_adventure(created, error); - }, - "Personal save backed up."); - PaddockGap(8); - if (button("EXPORT SAVE", !editable)) - ExportAdventureWithDialog(); - PaddockGap(8); - if (button("IMPORT SAVE")) - ImportAdventureWithDialog(); - PaddockGap(14); - if (!view.adventure.exists) { - if (button("CREATE PERSONAL SAVE")) - state.ask = SavesPageState::Ask::Reset; - return; - } - if (editable) { - if (!state.summary && view.image) - state.summary = view.image; - if (state.summary) { - SavesSeparator("Adventure slots", width); - for (unsigned i = 0; i < 3; ++i) { - const auto& slot = state.summary->slots[i]; - SavesNote("Slot " + std::to_string(i + 1) + " - " + (slot.name.empty() ? "---" : slot.name) + " - " + - std::to_string(slot.balloons[0] - codec::bonus_balloons(slot)) + " / 47 balloons" + - (codec::bonus_balloons(slot) > 0U - ? " + " + std::to_string(codec::bonus_balloons(slot)) + " bonus" - : ""), - width, 18, kSetText); - } - const auto& settings = state.summary->settings; - SavesNote(std::string("Drumstick: ") + (settings.drumstick ? "unlocked" : "locked") + " | T.T.: " + - (std::all_of(settings.tt_trials.begin(), settings.tt_trials.end(), [](bool x) { return x; }) - ? "unlocked" - : "locked") + - " | Adventure Two: " + (settings.adventure_two ? "unlocked" : "locked"), - width); - } - if (button("MAX OUT ENTIRE SAVE", false, SavesTone::Primary)) { - state.slot = -1; - state.ask = SavesPageState::Ask::MaxOut; - } - PaddockGap(8); - if (button("UNLOCK ALL RACERS AND MODES")) - state.ask = SavesPageState::Ask::UnlockAll; - SavesSeparator("Development tools", width); - SavesNote( - "Dev Menu uses a separate copy, not this personal save. New development copies start from your saved progress. You can refresh an existing copy below; its previous progress is kept.", - width); - if (button("COPY PERSONAL SAVE TO DEVELOPMENT")) - state.ask = SavesPageState::Ask::DevelopmentCopy; - } - SavesSeparator("Older progress and backups", width); - SavesNote( - "Older mod-set saves are kept. Choose one from Backups & Recovery if it contains the progress you want to keep. Nothing is merged or deleted automatically.", - width); - if (button("OPEN BACKUPS & RECOVERY")) { - state.scope = 3; - state.ask = SavesPageState::Ask::None; - } - PaddockGap(20); - if (button("RESET PERSONAL SAVE", false, SavesTone::Danger)) - state.ask = SavesPageState::Ask::Reset; - (void)panel; + const float buttons_y = top + (layout.stacked ? 48.0F : 11.0F); + const float actions_width = layout.discard_width + layout.apply_width + 12.0F; + ImGui::SetCursorScreenPos({left + std::max(0.0F, width - actions_width), buttons_y}); + if (SavesRaceButton("DISCARD CHANGES", layout.discard_width, SavesTone::Plain, locked || !dirty)) + ask = SavesPageState::Ask::Discard; + ImGui::SameLine(0.0F, 12.0F); + if (SavesRaceButton("APPLY CHANGES", layout.apply_width, SavesTone::Primary, locked || !dirty)) + ask = SavesPageState::Ask::Apply; + LibraryNavigationPinnedAction(!locked && dirty ? ImGui::GetItemID() : 0); } -// ------------------------------------------------------------ transfer - -// Complete manager actions and stored-save recovery. This replaces the old -// split-profile UI, but keeps the proven slot/record editor above unchanged. +// File tools shared by both Adventure saves. void SharedPakDialog(int port, bool importing) { if (SharedSaveBusy()) return; @@ -704,55 +516,153 @@ void SharedRawExportDialog(const std::filesystem::path& source) { } NFD_Quit(); } -void DrawSavesTransfer(float width, float panel, const SaveManagerViewCache& view) { +struct SavesFileActions { + float width; + float used = 0.0F; + + bool Button(const char* label, bool disabled = false, SettingsButtonTone tone = SettingsButtonTone::Plain) { + constexpr float gap = 8.0F; + const float size = std::min(width, SettingsButtonWidth(label)); + if (used > 0.0F && used + gap + size <= width) { + ImGui::SameLine(0.0F, gap); + used += gap; + } else { + if (used > 0.0F) + PaddockGap(gap); + used = 0.0F; + } + used += size; + return SettingsButton(label, size, disabled, tone); + } +}; + +void DrawSavesFiles(SavesPageState& state, float width, const AdventureView& adventure, + const SaveManagerViewCache& view) { using namespace dkr::runtime::saves; - SavesNote( - "Move your personal Adventure, custom-course records and Controller Paks together. Older save bundles can still be imported.", - width); - if (SavesRaceButton("EXPORT SAVE BUNDLE", 0, SavesTone::Plain, SharedSaveBusy())) - ExportSaveBundleWithDialog(); - PaddockGap(8); - if (SavesRaceButton("IMPORT SAVE BUNDLE", 0, SavesTone::Plain, SharedSaveBusy())) - ImportSaveBundleWithDialog(); - SavesSeparator("Controller Paks", width); - SavesNote("DKR-R virtual memory cards. Use DKR-R-format .mpk files, not an unrelated emulator format.", width); + const bool modded = state.personal_modded; + const bool busy = SharedSaveBusy(); + const bool valid = adventure.info.valid; + const auto heading = [](const char* label, float available) { + PaddockText(PaddockSign(20.0F, 1.2F, 0.0F), PaddockRgb(kSetText), label, available); + PaddockGap(9.0F); + }; + + constexpr float gap = 12.0F; + const bool side_by_side = width >= 460.0F; + const float column = side_by_side ? std::floor((width - gap) * 0.5F) : width; + const ImVec2 top = ImGui::GetCursorScreenPos(); + constexpr std::string_view adventure_help = "Back up, export or replace this Adventure."; + constexpr std::string_view bundle_help = "Transfer this Adventure with shared custom-course records and Controller Paks."; + const auto note_type = PaddockReading(16.0F, false, 1.45F); + const float note_height = std::max(PaddockTextHeight(note_type, adventure_help, column), + PaddockTextHeight(note_type, bundle_help, column)); + const auto transfer_note = [&](std::string_view note) { + SavesNote(note, column); + if (side_by_side) + PaddockGap(note_height - PaddockTextHeight(note_type, note, column)); + }; + ImGui::BeginGroup(); + heading("Adventure save", column); + transfer_note(adventure_help); + SavesFileActions adventure_actions{column}; + if (adventure_actions.Button("Back up save", busy || !valid)) + BeginSharedSaveJob( + [modded](std::string& error) { + std::filesystem::path created; + return backup_adventure(created, error, modded); + }, + "Adventure backed up."); + if (adventure_actions.Button("Export save", busy || !valid)) + ExportAdventureWithDialog(adventure.info.path); + if (adventure_actions.Button("Import save", busy)) + ImportAdventureWithDialog(modded); + if (!adventure.info.exists && adventure_actions.Button("Create personal save", busy)) + state.ask = SavesPageState::Ask::Reset; + if (adventure.info.exists && !valid && adventure.info.size == 512 && + adventure_actions.Button("Back up & repair checksums", busy)) + state.ask = SavesPageState::Ask::Repair; + ImGui::EndGroup(); + const float first_bottom = ImGui::GetItemRectMax().y; + ImGui::SetCursorScreenPos(side_by_side ? ImVec2{top.x + column + gap, top.y} + : ImVec2{top.x, first_bottom + 16.0F}); + ImGui::BeginGroup(); + heading("Save bundle", column); + transfer_note(bundle_help); + SavesFileActions bundle_actions{column}; + if (bundle_actions.Button("Export save bundle", busy)) + ExportSaveBundleWithDialog(modded); + if (bundle_actions.Button("Import save bundle", busy)) + ImportSaveBundleWithDialog(modded); + ImGui::EndGroup(); + ImGui::SetCursorScreenPos({top.x, std::max(first_bottom, ImGui::GetItemRectMax().y)}); + ImGui::Dummy({width, 0.0F}); + + SavesSeparator("Controller Paks", width, false); + SavesNote("Use DKR-R-format .mpk files for these virtual memory cards.", width); for (int port = 0; port < 4; ++port) { ImGui::PushID(port); const auto& pak = view.controller_paks[port]; - SavesNote("Controller " + std::to_string(port + 1) + ": " + - (!pak.exists ? "not created" - : pak.valid ? "ready" - : "needs recovery"), - width, 18, kSetText); - if (SavesRaceButton("BACK UP PAK", 0, SavesTone::Plain, SharedSaveBusy() || !pak.valid)) + const std::string label = "Controller " + std::to_string(port + 1) + ": " + + (!pak.exists ? "not created" : pak.valid ? "ready" : "needs recovery"); + const float actions_width = SettingsButtonWidth("Back up Pak") + SettingsButtonWidth("Export Pak") + + SettingsButtonWidth("Import Pak") + 16.0F; + constexpr float label_width = 192.0F; + const bool inline_actions = width >= label_width + gap + actions_width; + const ImVec2 row = ImGui::GetCursorScreenPos(); + SavesNote(label, inline_actions ? label_width : width, 16.0F, kSetText); + if (inline_actions) + ImGui::SetCursorScreenPos({row.x + label_width + gap, row.y}); + ImGui::BeginGroup(); + SavesFileActions pak_actions{inline_actions ? width - label_width - gap : width}; + if (pak_actions.Button("Back up Pak", busy || !pak.valid)) BeginSharedSaveJob( [port](std::string& error) { std::filesystem::path created; return backup_controller_pak(port, created, error); }, "Controller Pak backed up."); - PaddockGap(8); - if (SavesRaceButton("EXPORT PAK", 0, SavesTone::Plain, SharedSaveBusy() || !pak.valid)) + if (pak_actions.Button("Export Pak", busy || !pak.valid)) SharedPakDialog(port, false); - PaddockGap(8); - if (SavesRaceButton("IMPORT PAK", 0, SavesTone::Plain, SharedSaveBusy())) + if (pak_actions.Button("Import Pak", busy)) SharedPakDialog(port, true); - PaddockGap(18); + ImGui::EndGroup(); + ImGui::SetCursorScreenPos({row.x, ImGui::GetItemRectMax().y + 9.0F}); + ImGui::Dummy({width, 0.0F}); ImGui::PopID(); } - (void)panel; + + SavesSeparator("Recovery and development", width, false); + SavesNote("Dev Menu uses a separate copy. Refreshing it keeps a backup of its previous progress.", width); + SavesFileActions recovery_actions{width}; + if (recovery_actions.Button("Open Backups & Recovery", busy)) { + state.scope = 3; + state.ask = SavesPageState::Ask::None; + } + if (recovery_actions.Button("Copy personal save to development", busy || !valid)) + state.ask = SavesPageState::Ask::DevelopmentCopy; + if (adventure.info.exists) { + SavesSeparator("Reset Adventure", width, false); + if (SavesRaceButton("RESET ADVENTURE", 0.0F, SavesTone::Danger, busy)) + state.ask = SavesPageState::Ask::Reset; + } } + void DrawSavesConfirmations(SavesPageState& state) { using namespace dkr::runtime::saves; using Ask = SavesPageState::Ask; static Ask shown = Ask::None; - if (state.ask == Ask::None) + if (state.ask == Ask::None) { + shown = Ask::None; return; + } if (shown != state.ask) { shown = state.ask; ImGui::OpenPopup("##saves-confirm"); } std::string heading = "Confirm save change", detail, confirm = "CONFIRM"; + const bool modded = state.ask == Ask::Import || state.ask == Ask::Bundle ? state.import_modded : state.personal_modded; + auto& draft = g_adventure_drafts[modded]; + const std::string adventure = modded ? "Modded Adventure" : "Vanilla Adventure"; bool replace = true; static std::filesystem::path preview_source; static std::string preview_text; @@ -762,18 +672,18 @@ void DrawSavesConfirmations(SavesPageState& state) { } switch (state.ask) { case Ask::Repair: - heading = "Repair personal save?"; + heading = "Repair " + adventure + "?"; detail = "Only checksums can be repaired. Damaged progress cannot be reconstructed. An unchanged original is preserved."; confirm = "REPAIR & KEEP ORIGINAL"; break; case Ask::Reset: - heading = "Reset personal save?"; - detail = "Reset all three slots, unlocks and records. Your current Adventure is backed up first."; + heading = "Reset " + adventure + "?"; + detail = "Reset all three slots, unlocks and built-in records in this Adventure. The current Adventure is backed up first."; confirm = "BACK UP & RESET"; break; case Ask::Restore: - heading = "Use this as your personal save?"; + heading = "Restore into " + adventure + "?"; detail = preview_text; confirm = "BACK UP & USE THIS SAVE"; break; @@ -792,24 +702,24 @@ void DrawSavesConfirmations(SavesPageState& state) { break; case Ask::Discard: heading = "Discard editor changes?"; - detail = "Reload your current personal save. Nothing on disk will be replaced."; + detail = "Reload " + adventure + " from disk."; confirm = "DISCARD DRAFT"; replace = false; break; case Ask::Apply: heading = "Apply editor changes?"; - detail = "Save the draft to your personal Adventure. A backup is created first."; + detail = "Save the draft to " + adventure + ". A backup is created first."; confirm = "BACK UP & APPLY"; break; case Ask::Import: - heading = "Import personal save?"; + heading = "Import into " + adventure + "?"; detail = preview_text; confirm = "BACK UP & IMPORT"; break; case Ask::Bundle: - heading = "Import save bundle?"; + heading = "Import bundle into " + adventure + "?"; detail = - "Replace the personal Adventure and Controller Paks included in this bundle. Originals are preserved in a recoverable transaction."; + "Import the Adventure into " + adventure + " and replace any shared records and Controller Paks included in the bundle. Originals are kept in Recovery."; confirm = "BACK UP & IMPORT BUNDLE"; break; case Ask::Pak: @@ -850,37 +760,43 @@ void DrawSavesConfirmations(SavesPageState& state) { if (!state.restore.empty() && (state.ask == Ask::Import || state.ask == Ask::Restore || state.ask == Ask::RepairUse || state.ask == Ask::Host)) SavesNote(PathUtf8(state.restore), inner, 14); - if (replace && state.ask != Ask::Host) - SavesNote("Normal play and mods use this personal save. Online and development saves stay separate.", inner); - if (SavesDraftDirty() && state.ask != Ask::Apply && state.ask != Ask::MaxOut && state.ask != Ask::UnlockAll) + if (replace && state.ask != Ask::Host && state.ask != Ask::Pak) + SavesNote("Selected save: " + adventure, inner); + if (replace && state.ask != Ask::Host && state.ask != Ask::Pak && SavesDraftDirty(draft) && + state.ask != Ask::Apply && state.ask != Ask::MaxOut && state.ask != Ask::UnlockAll) SavesNote("Your unapplied editor draft will be discarded after this succeeds.", inner); - const float height = 44; - const bool stack = PaddockRaceButtonWidth(confirm.c_str()) + PaddockRaceButtonWidth("CANCEL") + 12 > inner; - const float cell = stack ? inner : (inner - 12) * 0.5f; - bool close = false; - if (SavesRaceButton("CANCEL", cell)) - close = true; - if (!stack) - ImGui::SameLine(0, 12); + constexpr float gap = 12.0F; + const float cancel_width = PaddockRaceButtonWidth("CANCEL"); + const float confirm_width = PaddockRaceButtonWidth(confirm.c_str()); + const float actions_width = cancel_width + gap + confirm_width; + const bool stack = actions_width > inner; + if (!stack) { + const ImVec2 at = ImGui::GetCursorScreenPos(); + ImGui::SetCursorScreenPos({at.x + inner - actions_width, at.y}); + } + bool close = SavesRaceButton("CANCEL", std::min(inner, cancel_width)); + if (stack) + PaddockGap(8.0F); else - PaddockGap(10); - if (SavesRaceButton(confirm.c_str(), cell, SavesTone::Primary, SharedSaveBusy())) { + ImGui::SameLine(0.0F, gap); + const bool confirmed = confirm_width > inner + ? SettingsButton(confirm.c_str(), inner, SharedSaveBusy(), SettingsButtonTone::Selected) + : SavesRaceButton(confirm.c_str(), confirm_width, SavesTone::Primary, SharedSaveBusy()); + if (confirmed) { const auto source = state.restore; const auto port = state.slot; if (state.ask == Ask::Discard) { - SavesForgetDraft(); - g_shared_draft_revision.clear(); + draft = {}; } else if (state.ask == Ask::MaxOut || state.ask == Ask::UnlockAll || state.ask == Ask::Apply) { codec::SaveImage image; std::string error; - std::string expected = g_shared_draft_revision; + std::string expected = draft.revision; bool ready = false; - if (g_save_builder_image) { - image = *g_save_builder_image; + if (draft.image) { + image = *draft.image; ready = true; } else { - expected = shared::revision(); - ready = load_adventure(image, error); + ready = shared::load_draft(image, expected, error, modded); } if (ready) { if (state.ask == Ask::MaxOut) @@ -888,18 +804,18 @@ void DrawSavesConfirmations(SavesPageState& state) { if (state.ask == Ask::UnlockAll) shared::unlock(image); BeginSharedSaveJob( - [image = std::move(image), expected](std::string& error) { - return shared::apply(image, expected, error); + [image = std::move(image), expected, modded](std::string& error) { + return shared::apply(image, expected, error, modded); }, - "Personal save updated and read-back verified. Existing Dev Menu copies are separate; use Copy Personal Save to Development to refresh one."); + adventure + " saved and verified.", modded); } else g_save_manager_status = error; } else if (state.ask == Ask::Reset) - BeginSharedSaveJob([](std::string& error) { return shared::reset(error); }, - "Personal save reset. Previous progress and custom records are kept in Recovery."); + BeginSharedSaveJob([modded](std::string& error) { return shared::reset(error, modded); }, + adventure + " reset. Its previous progress is kept in Recovery.", modded); else if (state.ask == Ask::Bundle) - BeginSharedSaveJob([source](std::string& error) { return import_bundle(source, error); }, - "Save bundle imported. Original images are kept in the transaction archive."); + BeginSharedSaveJob([source, modded](std::string& error) { return import_bundle(source, error, modded); }, + "Save bundle imported. Original images are kept in the transaction archive.", modded); else if (state.ask == Ask::Pak) BeginSharedSaveJob( [source, port](std::string& error) { @@ -911,22 +827,22 @@ void DrawSavesConfirmations(SavesPageState& state) { "Online Adventure selected. Personal progress was not changed."); else if (state.ask == Ask::DevelopmentCopy) BeginSharedSaveJob( - [](std::string& error) { return shared::queue_development_copy(error); }, + [modded](std::string& error) { return shared::queue_development_copy(error, modded); }, "Personal save snapshot queued for the next offline development launch. Existing development progress will be preserved."); else if (state.ask == Ask::Repair) BeginSharedSaveJob( - [](std::string& error) { + [modded](std::string& error) { bool changed; std::filesystem::path original; return shared::prepare(g_config_directory, error) && - repair_adventure_checksums(changed, original, error); + repair_adventure_checksums(changed, original, error, modded); }, - "Checksum repair complete. Check your progress; the original was retained."); + "Checksum repair complete. The original was retained.", modded); else { const bool repair = state.ask == Ask::RepairUse; BeginSharedSaveJob( - [source, repair](std::string& error) { return shared::adopt(source, repair, error); }, - "Personal save replaced. Both the selected original and previous progress were retained."); + [source, repair, modded](std::string& error) { return shared::adopt(source, repair, error, modded); }, + adventure + " replaced. Both the selected original and previous progress were retained.", modded); } close = true; } @@ -936,7 +852,6 @@ void DrawSavesConfirmations(SavesPageState& state) { state.restore.clear(); } EndSettingsDialog(); - (void)height; } struct SharedSaveInventory { @@ -967,7 +882,7 @@ void DrawStoredSaves(SavesPageState& state, float width, bool locked) { std::map, std::size_t> groups; std::vector compact; for (auto& record : inventory.records) { - const auto bucket = record.scope == 0 ? 0 : record.scope == 1 ? 1 : 3; + const auto bucket = record.scope; const auto key = std::tuple{bucket, int(record.kind), record.content_hash}; const auto [it, added] = groups.emplace(key, compact.size()); if (added) @@ -982,14 +897,17 @@ void DrawStoredSaves(SavesPageState& state, float width, bool locked) { } if (pending.valid()) SavesNote("Reading saved progress...", width); - SavesNote( - state.scope == 1 - ? "Online Adventures are separate. The host can continue with different mods without switching saves." - : "Choose an older save to use as your personal Adventure. Original mod-set copies and backups are never removed automatically.", - width); + if (state.scope == 1) { + SavesNote("The host can continue the same Online Adventure with different mods.", width); + } else { + SavesNote("Choose which Adventure should receive the backup.", width); + const int target = SettingsSectionSigns({"RESTORE TO VANILLA", "RESTORE TO MODDED"}, state.personal_modded, width); + if (target >= 0) + state.personal_modded = target == 1; + } bool found = false; for (const auto& record : inventory.records) { - if (state.scope == 1 ? (record.scope != 1) : (record.scope == 0 || record.scope == 1)) + if (record.scope != state.scope) continue; found = true; ImGui::PushID(PathUtf8(record.info.path).c_str()); @@ -999,7 +917,6 @@ void DrawStoredSaves(SavesPageState& state, float width, bool locked) { : record.kind == StoredSaveKind::ControllerPak ? "Controller Pak backup" : record.kind == StoredSaveKind::ExperimentalPaks ? "Online Controller Paks" : state.scope == 1 ? "Online Adventure" - : record.scope == 2 ? "Older mod-set Adventure" : "Adventure backup"; SavesNote(label, inner, 17, kSetText); SavesNote(record.preview, inner); @@ -1012,7 +929,7 @@ void DrawStoredSaves(SavesPageState& state, float width, bool locked) { if (development) SavesNote("Development image - contains tool-session progress, not ordinary play.", inner, 14, kSetWarm); if (adventure && !locked) { - if (SavesRaceButton(record.info.valid ? (state.scope == 1 ? "USE FOR HOSTING" : "USE AS PERSONAL SAVE") + if (SavesRaceButton(record.info.valid ? (state.scope == 1 ? "USE FOR HOSTING" : "RESTORE BACKUP") : "REPAIR & USE COPY", 0, SavesTone::Primary, SharedSaveBusy() || (!record.info.valid && record.info.size != 512))) { @@ -1050,6 +967,170 @@ void DrawStoredSaves(SavesPageState& state, float width, bool locked) { } } +#include "cloud_saves/ui.inl" + +void PaintSaveWorkspacePanel(ImDrawList* draw, ImVec2 min, ImVec2 max) { + PaddockPanel(draw, min, max, {PaddockRound(14), PaddockRgb(0x0B2B3B), PaddockRgb(kSetBorder), 1.0F}); +} + +float DrawSavesSlotList(SavesPageState& state, float width, float height, bool stacked, + const dkr::runtime::saves::codec::SaveImage* image) { + constexpr float gap = 8.0F, pad = 12.0F; + PaddockBox box(width, {pad, pad}, stacked ? 0.0F : height); + PaddockText(PaddockReading(17.0F, true, 1.25F), PaddockRgb(kSetText), "Adventure slots", box.Inner()); + PaddockGap(gap); + constexpr int count = static_cast(dkr::runtime::saves::codec::kAdventureSlotCount); + const float item_width = stacked ? (box.Inner() - gap * (count - 1)) / count : box.Inner(); + const auto row = ImGui::GetCursorScreenPos(); + const float heading_height = row.y - box.Origin().y; + const float row_height = stacked ? 68.0F + : std::clamp((height - heading_height - pad - gap * (count - 1)) / count, 60.0F, 72.0F); + for (int index = 0; index < count; ++index) { + if (stacked) + ImGui::SetCursorScreenPos({row.x + static_cast(index) * (item_width + gap), row.y}); + ImGui::PushID(index); + const auto press = PaddockBeginPress("##adventure-slot", {item_width, row_height}); + const bool active = index == state.selected_slot; + PaddockPanel(ImGui::GetWindowDrawList(), press.min, press.max, + {PaddockRound(9), PaddockRgb(active ? 0xA33620 : press.hovered ? 0x1C4F65 : 0x12394B), + PaddockRgb(active ? kSetWarm : kSetBorder), 1.0F}); + const auto* slot = image ? &image->slots[static_cast(index)] : nullptr; + const bool named = slot && slot->name.find_first_not_of(' ') != std::string::npos; + const bool occupied = slot && (named || slot->balloons[0] || slot->trophies); + const std::string name = named ? slot->name + : std::string(dkr::localisation::source(occupied ? "Unnamed" : "Empty")); + const std::string progress = occupied + ? std::to_string(slot->balloons[0]) + " " + + std::string(dkr::localisation::source("balloons")) + : std::string{}; + const auto slot_label = std::string(dkr::localisation::source("Slot")) + " " + std::to_string(index + 1); + const auto small_text = PaddockReading(13.0F, false, 1.2F); + const auto large = PaddockReading(16.0F, true, 1.15F); + auto* draw = ImGui::GetWindowDrawList(); + const float text_width = item_width - 18.0F; + const float x = press.min.x + 9.0F; + const PaddockTextStyle muted{PaddockCol(active ? 0xFFE1C5 : kSetMuted)}; + const PaddockTextStyle ink{PaddockCol(kSetText)}; + PaddockTextAt(draw, small_text, {x, press.min.y + 6.0F}, text_width, slot_label, muted); + PaddockTextAt(draw, large, {x, press.min.y + 25.0F}, text_width, name, ink); + PaddockTextAt(draw, small_text, {x, press.max.y - 20.0F}, text_width, progress, muted); + PaddockEndPress(press, 9.0F, 1.0F, true); + if (press.pressed) { + state.selected_slot = index; + state.section = SaveEditorSection::Progress; + state.scroll_editor_to_top = true; + } + ImGui::PopID(); + if (!stacked && index + 1 < count) + PaddockGap(gap); + } + return box.End(PaintSaveWorkspacePanel); +} + +void DrawSavesWorkspace(SavesPageState& state, float width, const SaveManagerViewCache& view, + const AdventureView& adventure, bool locked) { + constexpr float pad = 12.0F, gap = 12.0F; + const bool valid = adventure.info.valid; + const bool loaded = LoadSavesEditorDraft(state, valid); + const auto& draft = g_adventure_drafts[state.personal_modded]; + const auto* image = loaded ? &*draft.image : nullptr; + const auto footer = MeasureSavesFooter(width); + const auto start = ImGui::GetCursorScreenPos(); + const float bottom = PanelFooterBounds(ImGui::GetCurrentWindow()).Max.y; + const float footer_top = bottom - footer.height; + const bool stacked = width < 530.0F; + const float list_width = stacked ? width : std::clamp(width * 0.28F, 154.0F, 292.0F); + const float right_width = stacked ? width : width - list_width - gap; + const float workspace_height = std::max(180.0F, footer_top - start.y - gap); + + ImGui::PushID(state.personal_modded ? "modded-adventure" : "vanilla-adventure"); + const float list_height = DrawSavesSlotList(state, list_width, workspace_height, stacked, image); + const ImVec2 editor = {stacked ? start.x : start.x + list_width + gap, + stacked ? start.y + list_height + gap : start.y}; + const float editor_height = std::max(100.0F, start.y + workspace_height - editor.y); + PaintSaveWorkspacePanel(ImGui::GetWindowDrawList(), editor, {editor.x + right_width, editor.y + editor_height}); + ImGui::SetCursorScreenPos({editor.x + pad, editor.y + pad}); + const float inner = right_width - pad * 2.0F; + const int section = SettingsSectionSigns({"PROGRESS", "UNLOCKS", "FILES"}, int(state.section), inner, true); + if (section >= 0 && section != int(state.section)) { + state.section = static_cast(section); + state.scroll_editor_to_top = true; + } + if (SaveDraftLayoutCheck()) { + g_save_draft_geometry.slots = {start, {start.x + list_width, start.y + list_height}}; + g_save_draft_geometry.editor = {editor, {editor.x + right_width, editor.y + editor_height}}; + g_save_draft_geometry.selected_slot = state.selected_slot; + g_save_draft_geometry.modded = state.personal_modded; + } + PaddockGap(8.0F); + if (state.section == SaveEditorSection::Progress && valid && loaded) { + constexpr const char* all_label = "MAX OUT THIS SAVE"; + constexpr const char* slot_label = "Max out this slot"; + const float all_width = PaddockRaceButtonWidth(all_label); + const float slot_width = SettingsButtonWidth(slot_label); + const auto summary_type = PaddockReading(15.0F, true, 1.25F); + const std::string summary = + std::string(dkr::localisation::source(state.personal_modded ? "Modded Adventure" : "Vanilla Adventure")) + + " / Slot " + std::to_string(state.selected_slot + 1); + const float summary_width = PaddockMeasure(summary_type, summary) + 2.0F; + const float action_width = all_width + slot_width + gap; + const ImVec2 header = {editor.x + pad, ImGui::GetCursorScreenPos().y}; + const bool inline_summary = summary_width + action_width + gap <= inner; + ImGui::SetCursorScreenPos({header.x, header.y + (inline_summary ? 11.0F : 0.0F)}); + PaddockText(summary_type, PaddockRgb(kSetText), summary, inner); + const ImVec2 actions = {header.x + (inline_summary ? inner - action_width : 0.0F), + inline_summary ? header.y : ImGui::GetItemRectMax().y + 5.0F}; + ImGui::SetCursorScreenPos(actions); + if (SavesRaceButton(all_label, std::min(inner, all_width), SavesTone::Featured, locked)) { + state.slot = -1; + state.ask = SavesPageState::Ask::MaxOut; + } + if (action_width <= inner) + ImGui::SameLine(0.0F, gap); + else + ImGui::SetCursorScreenPos({actions.x, actions.y + 50.0F}); + if (SettingsButton(slot_label, std::min(inner, slot_width), locked)) { + state.slot = state.selected_slot; + state.ask = SavesPageState::Ask::MaxOut; + } + PaddockGap(10.0F); + } + const float body_top = ImGui::GetCursorScreenPos().y; + const float height = std::max(24.0F, editor.y + editor_height - pad - body_top); + ImGui::SetCursorScreenPos({editor.x + pad, body_top}); + const bool visible = ImGui::BeginChild("##adventure-editor", {inner, height}, false, + ImGuiWindowFlags_NavFlattened | ImGuiWindowFlags_NoBackground); + LibraryNavigationScrollWindow(ImGui::GetCurrentWindow()); + if (std::exchange(state.scroll_editor_to_top, false) || (SaveDraftLayoutCheck() && g_launcher_layout_step == 0)) + ImGui::SetScrollY(0.0F); + if (SaveDraftLayoutCheck()) { + g_save_draft_geometry.editor_scroll = ImGui::GetScrollY(); + g_save_draft_geometry.editor_body = ImGui::GetCurrentWindow()->OuterRectClipped; + } + if (visible) { + const float content_width = ImGui::GetContentRegionAvail().x - 4.0F; + ImGui::BeginDisabled(locked); + if (state.section == SaveEditorSection::Files) { + DrawSavesFiles(state, content_width, adventure, view); + } else if (!valid || !loaded) { + SavesNote(adventure.info.exists ? "This Adventure needs recovery." : "No Adventure save yet.", content_width, + 17.0F, kSetWarm); + if (SavesRaceButton("OPEN FILES")) + state.section = SaveEditorSection::Files; + } else if (state.section == SaveEditorSection::Progress) { + DrawSavesSlotEditor(state, content_width, state.selected_slot); + } else if (state.section == SaveEditorSection::Unlocks) { + DrawSavesUnlocks(state, content_width, content_width); + } + ImGui::EndDisabled(); + PaddockGap(8.0F); + } + ImGui::EndChild(); + ImGui::PopID(); + ImGui::SetCursorScreenPos({start.x, editor.y + editor_height}); + DrawSavesDraftBar(state, width, footer_top, footer, SavesDraftDirty(draft), locked, state.ask); +} + void DrawSaveManagerPage(float available_width, bool live) { using namespace dkr::runtime::saves; auto& state = g_saves_page; @@ -1058,79 +1139,64 @@ void DrawSaveManagerPage(float available_width, bool live) { const auto frame = ImGui::GetFrameCount(); const bool entered = state.context != ImGui::GetCurrentContext() || state.last_frame != frame - 1; if (entered || generation != g_shared_save_generation) { - state.summary.reset(); InvalidateSaveManagerViewCache(); ++g_shared_save_generation; generation = g_shared_save_generation; - // Preserve a dirty draft, but compare its revision at commit time. - // A clean draft can be safely reloaded after gameplay/return. - if (!SavesDraftDirty()) - SavesForgetDraft(); + for (auto& draft : g_adventure_drafts) + if (!SavesDraftDirty(draft)) + draft = {}; } state.context = ImGui::GetCurrentContext(); state.last_frame = frame; PumpSharedSaveJob(); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); + const auto heading = ImGui::GetCursorScreenPos(); DrawPageHeading("SAVE MANAGER"); - PaddockGap(14); + const auto after_heading = ImGui::GetCursorScreenPos(); + ImGui::SetCursorScreenPos({heading.x + width - 116.0F, heading.y + 12.0F}); + if (PaddockTextLink("Back to Play")) + g_page_navigation_request = kPagePlay; + ImGui::SetCursorScreenPos(after_heading); + PaddockGap(8); if (!g_save_manager_status.empty()) DrawFriendlyStatus(g_save_manager_status, width, dkr::runtime::copy::Area::Saves); const bool lobby = dkr::runtime::netplay::session().active(); const bool locked = live || lobby || SharedSaveBusy(); - const int current = state.scope == 0 ? 0 : state.scope == 1 ? 2 : 1; - const int picked = SettingsSectionSigns({"YOUR SAVE", "BACKUPS & RECOVERY", "ONLINE SAVES"}, current, width); - if (picked >= 0) { - state.scope = picked == 0 ? 0 : picked == 2 ? 1 : 3; + constexpr std::array scopes{0, 2, 1, 3, 4}; + const int current = static_cast(std::ranges::find(scopes, state.scope) - scopes.begin()); + const int picked = + SettingsSectionSigns({"VANILLA SAVE", "MODDED SAVE", "ONLINE SAVES", "BACKUPS & RECOVERY", "CLOUD SAVES"}, + current, width, true); + if (picked >= 0 && picked != current) { + state.scope = scopes[static_cast(picked)]; state.ask = SavesPageState::Ask::None; state.restore.clear(); + state.scroll_editor_to_top = true; + ImGui::SetScrollY(0.0F); } - PaddockGap(20); - SavesNote("Return to the launcher and leave your lobby before changing saves.", width); - if (state.scope != 0) + if (state.scope == 0 || state.scope == 2) + state.personal_modded = state.scope == 2; + PaddockGap(8); + if (live || lobby) + SavesNote("Return to the launcher and leave your lobby before changing saves.", width); + if (state.scope == 4) + DrawCloudSaves(width, locked); + else if (state.scope != 0 && state.scope != 2) DrawStoredSaves(state, width, locked); else { const auto& view = CachedSaveManagerView(); - const auto& info = view.adventure; + const auto& adventure = view.adventures[state.personal_modded]; if (!view.valid) { - SavesNote("Reading your personal save...", width); + SavesNote("Reading your Adventure save...", width); ImGui::PopStyleVar(); return; } - const bool valid = info.exists && info.valid; - SavesNote(valid ? "YOUR PERSONAL ADVENTURE" - : info.exists ? "YOUR SAVE NEEDS RECOVERY" - : "NO PERSONAL SAVE YET", - width, 19, valid ? kSavesAccent : kSetWarm); - if (lobby) - SavesNote("Leave the lobby before changing saves. You can export your personal save.", width); - if (SharedSaveBusy()) - SavesNote("Finishing the save operation. Launch is temporarily held until it is safe.", width); - { - ImGui::BeginDisabled(locked); - if (!info.valid && info.exists && info.size == 512) { - if (SavesRaceButton("BACK UP & REPAIR CHECKSUMS", 0, SavesTone::Primary)) - state.ask = SavesPageState::Ask::Repair; - PaddockGap(12); - } - ImGui::EndDisabled(); - const auto section = - SettingsSectionSigns({"OVERVIEW", "EDIT PROGRESS", "TRANSFER & PAKS"}, state.section, width); - if (section >= 0) - state.section = section; - PaddockGap(18); - ImGui::BeginDisabled(locked); - if (state.section == 1) - DrawSavesEditor(state, width, width, valid, info.exists); - else if (state.section == 2) - DrawSavesTransfer(width, width, view); - else - DrawSavesOverview(state, width, width, view, valid); - ImGui::EndDisabled(); - } + DrawSavesWorkspace(state, width, view, adventure, locked); } if (!g_shared_save_import.path.empty() && !locked) { state.restore = std::move(g_shared_save_import.path); state.slot = g_shared_save_import.port; + state.import_modded = g_shared_save_import.modded; state.ask = g_shared_save_import.kind == 1 ? SavesPageState::Ask::Bundle : g_shared_save_import.kind == 2 ? SavesPageState::Ask::Pak : SavesPageState::Ask::Import; diff --git a/runtime-recomp/src/game/runtime_settings_ui.inl b/runtime-recomp/src/game/runtime_settings_ui.inl index 88288a5e..a013d402 100644 --- a/runtime-recomp/src/game/runtime_settings_ui.inl +++ b/runtime-recomp/src/game/runtime_settings_ui.inl @@ -43,6 +43,7 @@ float SettingsHelp(std::string_view text, float width, unsigned colour = kSetMut // ------------------------------------------------------------ drop-down using SettingsChoice = dkr::localisation::Choice; +constexpr float kSettingsDropdownHeight = 52.0F; // The open list (.picker): a dark panel under its field, with a check on // the current choice. Returns the picked index, or -1. @@ -65,7 +66,8 @@ int DrawSettingsPicker(const char* popup, ImVec2 anchor_min, ImVec2 anchor_max, const float above = anchor_min.y - 6.0F - 12.0F; const bool flip = natural > below && above > below; const float height = std::min(natural, std::max(flip ? above : below, 120.0F)); - const ImVec2 at{anchor_min.x, flip ? anchor_min.y - 6.0F - height : anchor_max.y + 6.0F}; + const float left = std::clamp(anchor_min.x, 0.0F, std::max(0.0F, display.x - width - 12.0F)); + const ImVec2 at{left, flip ? anchor_min.y - 6.0F - height : anchor_max.y + 6.0F}; ImGui::SetNextWindowPos(at); ImGui::SetNextWindowSize({width, height}); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {6.0F, 6.0F}); @@ -164,10 +166,12 @@ int DrawSettingsPicker(const char* popup, ImVec2 anchor_min, ImVec2 anchor_max, return picked; } +// The default dropdown for launcher pages, with its label above the field. // A labelled drop-down: the field shows the current choice and opens the // list (dropdownRow). Returns true when the choice changed. bool SettingsDropdown(const char* id, std::string_view label, int* value, const std::vector& choices, - float width, bool disabled = false, std::string_view help = {}) { + float width, bool disabled = false, std::string_view help = {}, + float height = kSettingsDropdownHeight) { SettingsLabel(label, width); *value = std::clamp(*value, 0, std::max(static_cast(choices.size()) - 1, 0)); ImGui::PushID(id); @@ -175,7 +179,7 @@ bool SettingsDropdown(const char* id, std::string_view label, int* value, const const bool open = ImGui::IsPopupOpen(popup); if (disabled) ImGui::BeginDisabled(); - const PaddockPress press = PaddockBeginPress("##field", {width, 52.0F}); + const PaddockPress press = PaddockBeginPress("##field", {width, height}); if (disabled) ImGui::EndDisabled(); if (press.pressed && !disabled) @@ -195,10 +199,10 @@ bool SettingsDropdown(const char* id, std::string_view label, int* value, const choices.empty() ? dkr::localisation::source("Unavailable") : choices[static_cast(*value)].display_label(), width - 14.0F - 14.0F - 12.0F - 16.0F); - PaddockDrawRun(draw, type, {press.min.x + 15.0F, std::round(press.min.y + (52.0F - type.line) * 0.5F)}, + PaddockDrawRun(draw, type, {press.min.x + 15.0F, std::round(press.min.y + (height - type.line) * 0.5F)}, PaddockRgb(0xFFFFFF), shown.data(), shown.data() + shown.size()); if (!disabled) { - PaddockChevron(draw, {press.max.x - 14.0F - 2.0F - 6.0F, press.min.y + 52.0F * 0.5F - 3.0F}, 45.0F, 10.0F, + PaddockChevron(draw, {press.max.x - 14.0F - 2.0F - 6.0F, press.min.y + height * 0.5F - 3.0F}, 45.0F, 10.0F, PaddockRgb(0xFFFFFF), 2.5F); } OlFade(draw, first, disabled ? 0.6F : 1.0F); @@ -555,8 +559,8 @@ enum class SettingsButtonTone { inline float SettingsButtonWidth(std::string_view label) { const auto caption = dkr::localisation::label(label); - label = caption.c_str(); - return std::ceil(PaddockMeasure(PaddockReading(14.0F, true, 1.35F), label) + 28.0F + 2.0F); + const char* begin = caption.c_str(); + return std::ceil(PaddockMeasure(PaddockReading(14.0F, true, 1.35F), begin, PaddockLabelEnd(begin)) + 30.0F); } // .settings-button: the quiet action of the settings pages. width <= 0 sizes @@ -693,25 +697,26 @@ int SettingsSecondaryNav(const char* id, const std::vector& labels, // A row of painted section signs (.mods-section-nav), wrapping, with the // heavy hairline under it. Returns the picked index, or -1. -int SettingsSectionSigns(const std::vector& labels, int current, float width) { +int SettingsSectionSigns(const std::vector& labels, int current, float width, bool compact = false) { const ImVec2 at = ImGui::GetCursorScreenPos(); - const float tab_height = PaddockSectionTabHeight(); + const float tab_height = PaddockSectionTabHeight(compact); + const float gap = compact ? 6.0F : 10.0F; float x = at.x; float y = at.y; int picked = -1; for (std::size_t index = 0; index < labels.size(); ++index) { - const float tab = PaddockSectionTabWidth(labels[index]); + const float tab = std::min(width, PaddockSectionTabWidth(labels[index], compact)); if (x > at.x && x + tab > at.x + width) { x = at.x; - y += tab_height + 10.0F; + y += tab_height + gap; } ImGui::SetCursorScreenPos({x, y}); - if (PaddockSectionTab(labels[index], static_cast(index) == current)) { + if (PaddockSectionTab(labels[index], static_cast(index) == current, tab, compact)) { picked = static_cast(index); } - x += tab + 10.0F; + x += tab + gap; } - const float bottom = y + tab_height + 16.0F; + const float bottom = y + tab_height + (compact ? 8.0F : 16.0F); ImGui::GetWindowDrawList()->AddRectFilled({at.x, bottom}, {at.x + width, bottom + 2.0F}, PaddockCol(0x24495B)); ImGui::SetCursorScreenPos(at); ImGui::Dummy({width, bottom + 2.0F - at.y}); diff --git a/runtime-recomp/src/game/runtime_stubs.cpp b/runtime-recomp/src/game/runtime_stubs.cpp index 78f2b0c3..784029be 100644 --- a/runtime-recomp/src/game/runtime_stubs.cpp +++ b/runtime-recomp/src/game/runtime_stubs.cpp @@ -15,6 +15,8 @@ #include "vi_presentation_policy.hpp" #include "widescreen_policy.hpp" #include "finish_presentation_policy.hpp" +#include "display_settings/policy.hpp" +#include "time_trial/session.hpp" #include "audio_event_queue.h" #include "track_select_draw_guest.h" #include "track_select_draw_policy.hpp" @@ -102,9 +104,10 @@ bool g_sky_cover_active = false; dkr::runtime::presentation::PostraceFrameGate g_postrace_frame_gate{}; bool g_postrace_world_framed = false; -float ExpandedCoverScale() { +float ExpandedCoverScale(bool use_replay_aspect = false) { using ultramodern::renderer::AspectRatio; - if (ultramodern::renderer::get_graphics_config().ar_option != AspectRatio::Expand) { + const bool replay = use_replay_aspect && dkr::runtime::time_trial::watching(); + if (!replay && ultramodern::renderer::get_graphics_config().ar_option != AspectRatio::Expand) { return 1.0F; } auto* window = static_cast(dkr::runtime::platform::sdl_window()); @@ -117,7 +120,9 @@ float ExpandedCoverScale() { if (width <= 0 || height <= 0) { return 1.0F; } - return std::max(1.0F, (static_cast(width) / static_cast(height)) / kOriginalAspect); + const float aspect = replay ? dkr::display::view_aspect(width, height) + : static_cast(width) / static_cast(height); + return std::max(1.0F, aspect / kOriginalAspect); } float ReadRdramFloat(std::uint8_t* rdram, std::uint32_t address) { @@ -402,9 +407,10 @@ extern "C" void dkr_split_screen_viewport_fill(std::uint8_t* rdram, recomp_conte rdram, context->r17, PresentationGroupMode::World, std::uint16_t(MEM_W(0, RdramAddress(dkr::runtime::revision_addresses::current().ActiveCameraId)) & 3U), 0U, PresentationMarkerKind::CameraWorldBegin); - const float cover = ExpandedCoverScale(); + const float cover = ExpandedCoverScale(true); const bool postrace = PostraceFullViewScope(rdram, cover); - g_postrace_world_framed = postrace && g_postrace_frame_gate.contracted_frame_submitted; + g_postrace_world_framed = postrace && g_postrace_frame_gate.contracted_frame_submitted && + !dkr::runtime::time_trial::watching(); if (postrace && !g_postrace_world_framed) { // Presentation-only viewport/scissor correction: leave the authored // viewport, camera, menu animation and shared simulation RAM intact. diff --git a/runtime-recomp/src/game/runtime_texture_packs.cpp b/runtime-recomp/src/game/runtime_texture_packs.cpp index 17d08812..59bd7097 100644 --- a/runtime-recomp/src/game/runtime_texture_packs.cpp +++ b/runtime-recomp/src/game/runtime_texture_packs.cpp @@ -1,3 +1,4 @@ +#include "time_trial/session.hpp" #include "storage/maintenance.hpp" #include "session_content/policy.hpp" #include "mod_store_install.hpp" @@ -1461,7 +1462,8 @@ void renderer_started() { } void apply_pending(RT64::Application& application, bool modern_profile) { - modern_profile = modern_profile && dkr::session_content::textures_allowed(); + // Recording restricts gameplay content. RT64 replacements only affect the picture. + modern_profile = modern_profile && (dkr::session_content::textures_allowed() || time_trial::recording()); std::vector replacements; std::vector previous_replacements; std::set replacement_ids; @@ -1492,6 +1494,12 @@ void apply_pending(RT64::Application& application, bool modern_profile) { directory = dkr::runtime::layout::windows_application_directory(directory / "DKR-R-Runtime.exe"); #endif const auto builtin = directory / "assets/ui/CustomTrackBackgrounds"; + if (time_trial::exporting_video()) { + const auto video_pack = directory / "assets/ui/RankedVideoTextures"; + std::error_code video_error; + if (std::filesystem::is_regular_file(video_pack / "rt64.json", video_error)) + replacements.emplace_back(video_pack); + } SDL_free(base); std::error_code error; if (std::filesystem::is_regular_file(builtin / "rt64.json", error)) diff --git a/runtime-recomp/src/game/runtime_ui.cpp b/runtime-recomp/src/game/runtime_ui.cpp index ce9f2bb5..355ffe04 100644 --- a/runtime-recomp/src/game/runtime_ui.cpp +++ b/runtime-recomp/src/game/runtime_ui.cpp @@ -2,6 +2,7 @@ #include "launcher_themes/corner_atlas.hpp" #include "library_ui/control_layout.hpp" #include "library_ui/surface_policy.hpp" +#include "dialog_style.hpp" #include "launcher_themes/button_pattern_ui.hpp" #include "library_ui/handoff.hpp" #include "library_ui/launcher_fade.hpp" @@ -39,6 +40,9 @@ #include "sound_settings/policy.hpp" #include "overlay_settings/policy.hpp" #include "session_content/policy.hpp" +#include "time_trial/session.hpp" +#include "time_trial/options.hpp" +#include "time_trial/ghost_file.hpp" #include "analog_driving/settings.hpp" #include "look_behind/policy.hpp" #include "file_picker/client.hpp" @@ -146,6 +150,8 @@ #include "runtime_texture_packs.hpp" #include "save_manager.hpp" #include "runtime_save_routing.hpp" +#include "personal_adventure_paths.hpp" +#include "cloud_saves/progress.hpp" #include "texture_pack_browser_policy.hpp" #include "ui_notification_policy.hpp" #include "virtual_pak.hpp" @@ -199,6 +205,7 @@ extern "C" bool dkr_show_metal_layer(void* ns_window_ptr, void* layer_ptr); #include #include #include +#include #include #include #include @@ -208,6 +215,13 @@ extern "C" bool dkr_show_metal_layer(void* ns_window_ptr, void* layer_ptr); #include #include +#if DKR_RUNTIME_HAS_RT64 +extern "C" { +extern const char SpeedrunningHudPreview[]; +extern const std::size_t SpeedrunningHudPreview_size; +} +#endif + namespace { // A single bounded checker texture replaces the old per-frame, per-strip @@ -459,6 +473,7 @@ struct OnlineHostRequest { dkr::runtime::netplay::CompatibilityManifest manifest; dkr::runtime::saves::OnlineSaveSeedMode save_mode; std::string room, name; + std::optional cloud_account; // Set once the pre-host check is scheduled. bool content_enabled = dkr::session_content::next_enabled.load(); }; std::optional g_online_mod_host_request; @@ -773,14 +788,15 @@ int g_shortcut_capture_count = 0; std::chrono::steady_clock::time_point g_shortcut_capture_deadline{}; std::string g_save_manager_status; bool g_play_offline_after_leave = false; +struct AdventureView { + dkr::runtime::saves::SaveInfo info; + std::optional image; +}; struct SaveManagerViewCache { bool valid = false; std::chrono::steady_clock::time_point next_refresh{}; - dkr::runtime::saves::SaveInfo adventure; + std::array adventures{}; std::array controller_paks{}; - std::vector adventure_backups; - std::optional image; - std::string preview; }; SaveManagerViewCache g_save_manager_view_cache; std::uint64_t g_save_cache_revision = 0; @@ -796,32 +812,26 @@ const SaveManagerViewCache& CachedSaveManagerView() { if (pending.valid() && pending.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { try { auto result = pending.get(); - if (result.first == g_save_cache_revision) { + if (result.first == g_save_cache_revision) g_save_manager_view_cache = std::move(result.second); - } } catch (const std::exception& e) { g_save_manager_status = e.what(); } } if (!pending.valid() && (!g_save_manager_view_cache.valid || now >= g_save_manager_view_cache.next_refresh)) { pending = std::async(std::launch::async, [generation = g_save_cache_revision] { + namespace saves = dkr::runtime::saves; SaveManagerViewCache view; - view.adventure = dkr::runtime::saves::adventure_info(); - dkr::runtime::saves::codec::SaveImage image; - std::string error; - if (view.adventure.valid && dkr::runtime::saves::load_adventure(image, error)) { - view.image = image; - for (unsigned i = 0; i < 3; ++i) { - if (i) - view.preview += " | "; - const auto& s = image.slots[i]; - view.preview += "Slot " + std::to_string(i + 1) + ": " + s.name + " (" + - std::to_string(s.balloons[0]) + " balloons)"; - } + for (const bool modded : {false, true}) { + auto& adventure = view.adventures[modded]; + adventure.info = saves::adventure_info(modded); + saves::codec::SaveImage image; + std::string error; + if (adventure.info.valid && saves::load_adventure(image, error, modded)) + adventure.image = std::move(image); } - for (int i = 0; i < 4; ++i) - view.controller_paks[i] = dkr::runtime::saves::controller_pak_info(i); - view.adventure_backups = dkr::runtime::saves::adventure_backups(); + for (int port = 0; port < saves::kControllerPakCount; ++port) + view.controller_paks[port] = saves::controller_pak_info(port); view.valid = true; view.next_refresh = std::chrono::steady_clock::now() + std::chrono::seconds(2); return std::pair{generation, std::move(view)}; @@ -835,8 +845,8 @@ bool g_online_compatibility_sync_requested = false; std::string g_controller_mapping_status; bool g_controller_mapping_popup_pending = false; bool g_controller_mapping_completion_saved = false; -std::optional g_save_builder_image; #include "shared_save_jobs.inl" +#include "cloud_saves/jobs.inl" bool HandleInputCaptureEvent(SDL_Event* event); @@ -1831,6 +1841,9 @@ void SaveSettings() { output << "online_local_view=" << unsigned(dkr::runtime::online_view::requested_layout.load()) << '\n'; output << "online_racer_labels=" << unsigned(dkr::runtime::online_view::requested_labels.load()) << '\n'; output << "online_label_size=" << dkr::runtime::online_view::requested_label_size.load() << '\n'; + namespace speed = dkr::runtime::speedrunning; + for (std::size_t i = 0; i < speed::settings.size(); ++i) + output << speed::prefix << speed::settings[i].key << '=' << speed::options.get(speed::Option(i)) << '\n'; output << "online_room_name=" << g_online_room_name << '\n'; output << "online_host_control=" << g_online_host_control << '\n'; output << "online_allow_spectators=" << (g_online_allow_spectators ? 1 : 0) << '\n'; @@ -1994,6 +2007,7 @@ bool LoadLegacyBindingSetting(const std::string& key, int number) { void LoadSettings() { dkr::library_ui::skip_launcher = false; + dkr::runtime::speedrunning::options.reset(); dkr::localisation::detect_system_language(); g_skip_intro = false; g_skip_intro_destination = 0; @@ -2085,6 +2099,8 @@ void LoadSettings() { dkr::runtime::online_view::requested_label_size = std::clamp(size, 75U, 150U); continue; } + if (dkr::runtime::speedrunning::options.parse(key, value)) + continue; bool controller_key = false; for (std::size_t player = 0; player < dkr::runtime::input::kPlayerCount; ++player) { const std::string expected = "player" + std::to_string(player + 1U) + ".controller_key"; @@ -3227,7 +3243,7 @@ void ImportMagicCodeWithDialog() { g_code_library.import_file(std::move(source)); } -bool ImportAdventureWithDialog() { +bool ImportAdventureWithDialog(bool modded) { if (SharedSaveBusy()) return false; if (NFD_Init() != NFD_OKAY) { @@ -3238,7 +3254,7 @@ bool ImportAdventureWithDialog() { const nfdfilteritem_t filters[] = {{"DKR Adventure save", "bin,eep"}}; const auto dialog = NFD_OpenDialogU8(&result, filters, 1, nullptr); if (dialog == NFD_OKAY) { - g_shared_save_import = {std::filesystem::u8path(result), 0, 0}; + g_shared_save_import = {std::filesystem::u8path(result), 0, 0, modded}; NFD_FreePathU8(result); } else if (dialog == NFD_ERROR) g_save_manager_status = NFD_GetError(); @@ -3283,7 +3299,7 @@ bool ExportAdventureWithDialog( return exported; } -bool ImportSaveBundleWithDialog() { +bool ImportSaveBundleWithDialog(bool modded) { if (SharedSaveBusy()) return false; if (NFD_Init() != NFD_OKAY) { @@ -3294,7 +3310,7 @@ bool ImportSaveBundleWithDialog() { const nfdfilteritem_t filters[] = {{"DKR-R save bundle", "dkrsave"}}; const auto dialog = NFD_OpenDialogU8(&result, filters, 1, nullptr); if (dialog == NFD_OKAY) { - g_shared_save_import = {std::filesystem::u8path(result), 1, 0}; + g_shared_save_import = {std::filesystem::u8path(result), 1, 0, modded}; NFD_FreePathU8(result); } else if (dialog == NFD_ERROR) g_save_manager_status = NFD_GetError(); @@ -3302,14 +3318,14 @@ bool ImportSaveBundleWithDialog() { return dialog == NFD_OKAY; } -bool ExportSaveBundleWithDialog() { +bool ExportSaveBundleWithDialog(bool modded) { if (NFD_Init() != NFD_OKAY) { g_save_manager_status = "The system file picker could not be initialized."; return false; } nfdchar_t* result = nullptr; const nfdfilteritem_t filters[] = {{"DKR-R save bundle", "dkrsave"}}; - const nfdresult_t dialog = NFD_SaveDialogU8(&result, filters, 1, nullptr, "dkr-port-save-garage.dkrsave"); + const nfdresult_t dialog = NFD_SaveDialogU8(&result, filters, 1, nullptr, modded ? "dkr-modded.dkrsave" : "dkr-vanilla.dkrsave"); bool exported = false; if (dialog == NFD_OKAY) { auto destination = std::filesystem::u8path(result); @@ -3319,7 +3335,7 @@ bool ExportSaveBundleWithDialog() { } std::string error; exported = BeginSharedSaveJob( - [destination](std::string& error) { return dkr::runtime::saves::export_bundle(destination, error); }, + [destination, modded](std::string& error) { return dkr::runtime::saves::export_bundle(destination, error, modded); }, "Save bundle exported."); g_save_manager_status = exported ? "Exporting save bundle..." : error; } else if (dialog == NFD_ERROR) { @@ -3399,8 +3415,6 @@ bool BeginPaddedModal(const char* name, ImGuiWindowFlags flags = 0, const ImVec2 return BeginPaddockModalWindow(name, flags | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); } #endif - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, padding); - ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 18.0F); // Fit smaller screens without changing normal-size layouts. Let the // dialog scroll if needed so its actions remain reachable by controller. #if !defined(__ANDROID__) && !defined(DKR_IOS) @@ -3409,9 +3423,10 @@ bool BeginPaddedModal(const char* name, ImGuiWindowFlags flags = 0, const ImVec2 ImGui::SetNextWindowSizeConstraints({0.0F, 0.0F}, {std::max(screen.x - 24.0F, 1.0F), std::max(screen.y - 40.0F, 1.0F)}); #endif - const bool visible = ImGui::BeginPopupModal(name, nullptr, flags); - ImGui::PopStyleVar(2); - return visible; + if (!ImGui::IsPopupOpen(name)) + return ImGui::BeginPopupModal(name, nullptr, flags); + const dkr::runtime::ui::ScopedDialogStyle style(padding, 18.0F); + return ImGui::BeginPopupModal(name, nullptr, flags); } void DrawTexturePackImportModal() { @@ -6270,6 +6285,21 @@ bool OnlineNotificationActive() { return InviteUiVisible() || g_online_notifications.current(std::chrono::steady_clock::now()) != nullptr; } +void DrawSavingProgress() { + const auto* viewport = ImGui::GetMainViewport(); + const ImVec2 position{viewport->WorkPos.x + 16.F, viewport->WorkPos.y + viewport->WorkSize.y - 52.F}; + const auto caption = dkr::localisation::source("Saving Progress"); + const auto type = PaddockReading(14.F, true, 1.3F); + auto* draw = ImGui::GetForegroundDrawList(); + draw->AddRectFilled(position, {position.x + PaddockMeasure(type, caption) + 43.F, position.y + 36.F}, + PaddockCol(0x092737, 224), 8.F); + const float angle = float(std::fmod(ImGui::GetTime(), 1.0)) * 6.2831853F; + draw->PathArcTo({position.x + 16.F, position.y + 18.F}, 6.F, angle, angle + 4.6F, 16); + draw->PathStroke(PaddockCol(0x67DCC3), 0, 1.8F); + PaddockDrawRun(draw, type, {position.x + 30.F, position.y + (36.F - type.line) * 0.5F}, + PaddockCol(0xFFF6DA), caption.data(), caption.data() + caption.size()); +} + void DrawOnlineNotification() { DrawInviteUi(); const auto now = std::chrono::steady_clock::now(); @@ -7825,6 +7855,7 @@ void EndSettingsDialog(); bool SettingsDropdown(const char*, std::string_view, int*, std::initializer_list, float, bool, std::string_view); void DrawPlayUpdateButton(float); +#include "cloud_saves/play_ui.inl" #include "runtime_play_ui.inl" #include "runtime_online_ui.inl" #include "invite_ui.inl" @@ -8164,6 +8195,21 @@ void dkr::runtime::ui::configure(const std::filesystem::path& config_directory) dkr::runtime::netplay::session().configure_artifact_directory(config_directory / "netplay" / "replays"); RefreshCrtFilters(); LoadSettings(); + if (trial::exporting_video()) { + using namespace ultramodern::renderer; + auto graphics = get_graphics_config(); + graphics.rr_option = RefreshRate::Manual; + graphics.rr_manual_value = 60; + dkr::runtime::enhancements::set_texture_lod_bias_hundredths(0); + dkr::runtime::enhancements::set_generated_mipmaps_requested(true); + dkr::runtime::enhancements::set_anisotropy_level(16); + dkr::runtime::enhancements::set_presentation_profile( + dkr::runtime::enhancements::PresentationProfile::Modern); + dkr::display::preference.aspect = dkr::display::Aspect::Wide; + dkr::display::preference.height = 0; + dkr::display::publish(); + set_graphics_config(graphics); + } if (!g_shared_online_policy_loaded) g_online_save_seed_mode = int(dkr::runtime::saves::OnlineSaveSeedMode::ContinuePreviousSession); dkr::store::installations().configure(g_config_directory, DKR_RELEASE_VERSION, mod_worker); @@ -8205,9 +8251,46 @@ void dkr::runtime::ui::persist_graphics_api_fallback() { std::fprintf(stderr, "[boot][settings] unavailable graphics API recovered to Automatic\n"); } +namespace { +using TransitionFrame = std::unique_ptr; +TransitionFrame run_return_frame(nullptr, SDL_FreeSurface); +bool run_return_cover_shown = false; + +TransitionFrame CaptureTransitionFrame(SDL_Renderer* renderer) { + TransitionFrame frame(nullptr, SDL_FreeSurface); + int width = 0, height = 0; + if (!SDL_GetRendererOutputSize(renderer, &width, &height) && width > 0 && width <= 8192 && height > 0 && + height <= 4320) { + frame.reset(SDL_CreateRGBSurfaceWithFormat(0, width, height, 32, SDL_PIXELFORMAT_RGBA32)); + if (frame && SDL_RenderReadPixels(renderer, nullptr, SDL_PIXELFORMAT_RGBA32, frame->pixels, frame->pitch)) + frame.reset(); + } + return frame; +} +} // namespace + +void dkr::runtime::ui::show_run_return_cover(bool force) { + if (!run_return_cover_shown && run_return_frame && (force || trial::launcher_return_opacity() >= 1.F)) { + dkr::runtime::platform::show_startup_cover(run_return_frame.get(), true); + run_return_cover_shown = true; + } +} + dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* window, const std::filesystem::path& preselected_rom, bool software_failure_recovery) { + if (trial::take_restart_request() && g_previous_time_trial_request) { + g_time_trial_request = std::exchange(g_previous_time_trial_request, std::nullopt); + } else { + if (g_previous_time_trial_request && g_previous_time_trial_request->mode == trial::Mode::Record) { + ApplyReplayRetention(trial::last_result()); + g_open_speedrunning_result = true; + if (!RunPreference(RunOption::RememberSetup)) + g_run_setup = {}; + } + g_previous_time_trial_request.reset(); + DeleteRankedPlayback(std::exchange(g_ranked_playback_file, {})); + } StartupResult result{}; dkr::runtime::startup::prepare_launch(false, false, false); if (window == nullptr) { @@ -8322,6 +8405,18 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* ImGui_ImplSDL2_InitForSDLRenderer(window, renderer); ImGui_ImplSDLRenderer2_Init(renderer); dkr::store::service().gameplay(false); + std::string cloud_sync_attempted; + const auto request_cloud_sync = [&](bool force, dkr::cloud_saves::SyncScope scope = dkr::cloud_saves::SyncScope::All) { + if (SharedSaveBusy()) + return false; + const auto account = EnabledCloudSaveAccount(); + if (account.empty() || (!force && cloud_sync_attempted == account) || !RunCloudSaveSync(account, scope)) + return false; + if (scope == dkr::cloud_saves::SyncScope::All) + cloud_sync_attempted = account; + return true; + }; + bool cloud_return_pending = !preselected_rom.empty(); g_mod_store_renderer = renderer; g_store_in_game = false; g_character_portrait_renderer = renderer; @@ -8411,6 +8506,8 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* } int page = 0; + if (!dkr::runtime::time_trial::last_result().message.empty()) + page = dkr::library_ui::LeaderboardsPage; int last_rendered_page = -1; int sidebar_selection = 0; bool focus_content = true; @@ -8419,6 +8516,18 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* dkr::library_ui::startup_screen_seen, !preselected_rom.empty(), software_failure_recovery); dkr::library_ui::LauncherFade launch_fade; + TransitionFrame trial_handoff_image(nullptr, SDL_FreeSurface); + TransitionFrame next_return_frame(nullptr, SDL_FreeSurface); + bool return_frame_captured = false; + std::unique_ptr return_fade( + run_return_cover_shown && run_return_frame ? SDL_CreateTextureFromSurface(renderer, run_return_frame.get()) + : nullptr, + SDL_DestroyTexture); + if (return_fade) + SDL_SetTextureBlendMode(return_fade.get(), SDL_BLENDMODE_BLEND); + run_return_frame.reset(); + run_return_cover_shown = false; + double return_fade_started = -1; dkr::library_ui::runtime_intro.clear(); bool online_start_pending = false; bool launch_requested = false; @@ -8429,7 +8538,13 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* bool request_restart_popup = false; while (running) { g_legacy_imports.tick(); - dkr::runtime::saves::set_online_save_protection(dkr::runtime::netplay::session().active()); + const bool lobby_active = dkr::runtime::netplay::session().active(); + dkr::runtime::saves::set_online_save_protection(lobby_active); + if (cloud_return_pending) { + using dkr::cloud_saves::SyncScope; + if (request_cloud_sync(true, lobby_active ? SyncScope::PublishHostedOnline : SyncScope::All)) + cloud_return_pending = false; + } if (g_play_offline_after_leave && !dkr::runtime::netplay::session().active()) { g_play_offline_after_leave = false; launch_requested = true; @@ -8625,10 +8740,9 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* g_online_mod_identity = rom_ready ? online_manifest_identity : dkr::runtime::rom::Identity{}; PumpOnlineMods(); PumpInviteLauncher(rom_ready, online_manifest.has_value()); - if (rom_ready && !online_start_pending && dkr::runtime::netplay::session().consume_launch_request()) { + if (rom_ready && !online_start_pending && !SharedSaveBusy() && + dkr::runtime::netplay::session().consume_launch_request()) { dkr::runtime::startup_performance::mark("launcher-online-launch-requested"); - if (SharedSaveBusy()) - continue; online_start_pending = true; } if (online_start_pending && !dkr::runtime::netplay::session().active()) { @@ -8644,8 +8758,8 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* } constexpr int launcher_page_count = kMenuPageCount; constexpr int launcher_sidebar_count = kMenuPageCount + 3; - if (page >= launcher_page_count) { - page = 0; + if (!dkr::library_ui::is_content_page(page)) { + page = kPagePlay; } const auto launcher_events_started = std::chrono::steady_clock::now(); launcher_profile.add(LauncherProfile::Services, launcher_services_started, launcher_events_started); @@ -8786,8 +8900,9 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* { const auto preparation = g_mod_launch.snapshot(); - const bool busy = dkr::crash_reports::view().consent.choice == -1 || g_legacy_imports.snapshot().busy || - g_code_library.view()->busy || g_vehicle_library.view()->busy || + const bool busy = SharedSaveBusy() || dkr::crash_reports::view().consent.choice == -1 || + g_legacy_imports.snapshot().busy || g_code_library.view()->busy || + g_vehicle_library.view()->busy || bool(g_vehicle_library.view()->pending) || dkr::store::installations().view()->busy; const auto action = online_start_pending @@ -8804,25 +8919,61 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* std::fprintf(stderr, "[launcher][automatic-start] showing launcher for selection, cancellation or recovery\n"); } + const bool trial_fade_finished = + g_time_trial_request && launch_fade.started() && launch_fade.finished(PaddockClock()); + const bool capture_return_frame = trial_fade_finished && !return_frame_captured; + if (trial_fade_finished && !capture_return_frame) { + auto trial = std::move(*g_time_trial_request); + g_time_trial_request.reset(); + if (dkr::runtime::netplay::session().active()) { + g_time_trial_message = "Leave your lobby to start Time Trial."; + } else if (!rom_ready) { + g_time_trial_message = "Select a US v1.0 or US v1.1 ROM in Play first."; + } else if (const auto trial_rom = TimeTrialRom(trial, selected_rom, rom_catalog); + !trial_rom.empty() && LaunchTimeTrial(trial)) { + g_time_trial_message.clear(); + result.start_game = true; + result.rom_path = trial_rom; + dkr::runtime::startup::prepare_launch(false, false, false, dkr::runtime::startup::Destination{}); + dkr::library_ui::runtime_intro.begin(false, launcher_theme.seconds()); + dkr::runtime::platform::show_startup_cover(trial_handoff_image.get()); + run_return_frame = std::move(next_return_frame); + dkr::runtime::time_trial::enable_launcher_return(); + g_ranked_podium_started = -1; + g_theatre_controls = true; + g_theatre_inputs = RunPreference(RunOption::ReplayInputs) != 0; + g_theatre_controller_corner = -1; + g_theatre_activity = SDL_GetTicks64(); + std::fprintf(stderr, "[startup][time-trial] shared starting screen\n"); + g_previous_time_trial_request = std::move(trial); + running = false; + continue; + } + trial_handoff_image.reset(); + next_return_frame.reset(); + return_frame_captured = false; + DeleteRankedPlayback(std::exchange(g_ranked_playback_file, {})); + } if (launch_requested && dkr::crash_reports::view().consent.choice == -1) launch_requested = false; - if (launch_requested) { + if (launch_requested && !SharedSaveBusy()) { launch_requested = false; - if (!dkr::runtime::netplay::session().active() && !dkr::store::installations().view()->busy && + if (!dkr::runtime::netplay::session().active() && !OnlineModSelectionLocked() && + !dkr::store::installations().view()->busy && dkr::store::installations().view()->ready && !g_legacy_imports.snapshot().busy && !g_code_library.view()->busy && !g_mod_launch.snapshot().modal) { mod_launch_rom = selected_rom; - if (!SharedSaveBusy()) { - if (!automatic_start.active()) { - automatic_start.manual(AutomaticStartHasMods()); - std::fprintf(stderr, "[startup][manual] shared starting screen\n"); - } - g_mod_launch.start(g_config_directory, mod_launch_rom, false); + if (!automatic_start.active()) { + automatic_start.manual(AutomaticStartHasMods()); + std::fprintf(stderr, "[startup][manual] shared starting screen\n"); } + request_cloud_sync(true); + g_mod_launch.start(g_config_directory, mod_launch_rom, false); } } if (const auto prepared = g_mod_launch.snapshot(); - prepared.modal && prepared.prepared && !prepared.busy && launch_fade.finished(PaddockClock())) { + prepared.modal && prepared.prepared && !prepared.busy && !SharedSaveBusy() && + launch_fade.finished(PaddockClock())) { // The modal owns the selection while preparing; do not admit a // local bank if an online session began in the meantime. if (dkr::runtime::netplay::session().active()) { @@ -8830,8 +8981,6 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* rom_status = "Custom launch cancelled because an online lobby became active."; } else { dkr::runtime::startup_performance::mark("launcher-local-launch-requested"); - if (SharedSaveBusy()) - continue; result.start_game = true; result.rom_path = mod_launch_rom; result.mods = prepared.prepared; @@ -8900,7 +9049,23 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* // The opaque cloud backdrop (or opaque missing-asset fallback) covers // this entire undecorated window. Drawing ImGui's background underneath // it wastes a full software-rendered viewport every frame. - if (online_start_pending && launch_fade.started()) { + if (capture_return_frame) { + DrawAutomaticStart(automatic_start, launcher_background, renderer, launcher_background_scroll, + bounded_software_return, launcher_theme.theme(), launcher_theme.seconds(), nullptr, + false, true); + } else if (g_time_trial_request && launch_fade.started()) { + dkr::mods::ModLaunchView trial_status; + trial_status.stage = g_time_trial_request->mode == trial::Mode::Watch ? "Opening replay..." + : !g_time_trial_request->ghost.empty() ? "Loading ghost..." + : "Starting run..."; + if (DrawAutomaticStart(automatic_start, launcher_background, renderer, launcher_background_scroll, + bounded_software_return, launcher_theme.theme(), launcher_theme.seconds(), + &trial_status)) { + g_time_trial_request.reset(); + DeleteRankedPlayback(std::exchange(g_ranked_playback_file, {})); + launch_fade.clear(); + } + } else if (online_start_pending && launch_fade.started()) { if (DrawAutomaticStart(automatic_start, launcher_background, renderer, launcher_background_scroll, bounded_software_return, launcher_theme.theme(), launcher_theme.seconds(), nullptr, true)) { @@ -8921,6 +9086,12 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* launcher_theme.seconds(), dkr::launcher_themes::preferences.calendar); if (launcher_profile.enabled()) ImGui::GetWindowDrawList()->AddCallback(LauncherDrawProfileRange::end, &background_profile); + if (const int requested = std::exchange(g_page_navigation_request, -1); + dkr::library_ui::is_content_page(requested)) { + focus_content |= page != requested; + page = requested; + sidebar_selection = dkr::library_ui::sidebar_parent(page); + } #if defined(__ANDROID__) || defined(DKR_IOS) dkr::runtime::mobile::menu(page, false, request_restart_popup, request_quit_popup); dkr::runtime::mobile::begin_content(); @@ -8959,11 +9130,6 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* sidebar_layout.item_spacing_y, sidebar_layout.action_section_gap, sidebar_layout.action_gap, kSidebarOrder.size() - 3); ImGui::SetCursorPosY(sidebar_position.navigation); - if (g_page_navigation_request >= 0) { - page = g_page_navigation_request; - sidebar_selection = page; - g_page_navigation_request = -1; - } ImGui::PushItemFlag(ImGuiItemFlags_NoNav, true); ++g_race_button_sidebar; LibraryNavigationCheckRoute(false, page); @@ -9111,6 +9277,9 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* DrawLauncherFade(launch_fade, PaddockClock()); PumpDialogJob(); PumpSharedSaveJob(); + if (!launch_requested && !automatic_start.active() && !online_start_pending && !OnlineModSelectionLocked() && + !dkr::runtime::netplay::session().active()) + request_cloud_sync(false); PumpModStoreLauncher(); DrawTexturePackImportModal(); DrawPaddockLegacyModImportModal(); @@ -9174,17 +9343,43 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* #endif RenderLauncherDrawData(renderer, launcher_draw_data, launcher_profile, launcher_panel_cache, bounded_software_return); + if (capture_return_frame) { + // Prepare the matching cover off-screen while the normal start + // frame stays visible. The game and launcher never share textures. + next_return_frame = CaptureTransitionFrame(renderer); + return_frame_captured = true; + continue; + } // SDL's software backend normally executes its queued drawing inside // Present. Flush only in the opt-in profiler to separate those costs. if (launcher_profile.enabled()) SDL_RenderFlush(renderer); const auto launcher_draw_finished = std::chrono::steady_clock::now(); - if (!launch_requested && !automatic_start.active() && !online_start_pending) + if (!launch_requested && !automatic_start.active() && !online_start_pending && !g_time_trial_request) launch_fade.clear(); - if ((launch_requested && !automatic_start.active()) || (online_start_pending && !launch_fade.started())) + if (!g_time_trial_request) + trial_handoff_image.reset(); + if (g_time_trial_request && launch_fade.started() && !trial_handoff_image && + launch_fade.opacity(PaddockClock()) < .25F) { + trial_handoff_image = CaptureTransitionFrame(renderer); + } + if ((launch_requested && !automatic_start.active()) || + ((online_start_pending || g_time_trial_request) && !launch_fade.started())) launch_fade.capture(renderer, PaddockClock()); LibraryCaptureHandoff(renderer, launch_fade, automatic_start.active()); - LauncherLayoutCheckCapture(renderer); + LauncherLayoutCheckCapture(renderer, page); + if (return_fade) { + const double now = PaddockClock(); + if (return_fade_started < 0) + return_fade_started = now; + const double opacity = 1.0 - std::clamp((now - return_fade_started) / .24, 0.0, 1.0); + if (opacity > 0) { + SDL_SetTextureAlphaMod(return_fade.get(), static_cast(255 * opacity)); + SDL_RenderCopy(renderer, return_fade.get(), nullptr, nullptr); + } else { + return_fade.reset(); + } + } SDL_RenderPresent(renderer); const auto launcher_present_finished = std::chrono::steady_clock::now(); launcher_present_microseconds += static_cast( @@ -9192,6 +9387,7 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* .count()); ++launcher_rendered_frames; if (launcher_rendered_frames == 1U) { + dkr::runtime::platform::finish_run_return_cover(); if (software_failure_recovery && !(SDL_GetWindowFlags(window) & (SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED))) { SDL_RaiseWindow(window); @@ -9259,6 +9455,7 @@ dkr::runtime::ui::StartupResult dkr::runtime::ui::run_startup_screen(SDL_Window* ReleaseCharacterPortraits(); ReleaseModStoreTextures(); launch_fade.clear(); + return_fade.reset(); SDL_DestroyRenderer(renderer); const auto launcher_elapsed_microseconds = std::chrono::duration_cast( std::chrono::steady_clock::now() - launcher_animation_epoch) @@ -9335,6 +9532,28 @@ void dkr::runtime::ui::detach(RT64::Application& application) { } } +bool dkr::runtime::ui::draw_replay_video_inputs(RT64::Application& application) { + if (application.presentQueue == nullptr || application.framebufferGraphicsWorker == nullptr) + return false; + if (application.presentQueue->inspector == nullptr) + attach(application); + auto* inspector = application.presentQueue->inspector.get(); + if (inspector == nullptr) + return false; + inspector->newFrame(application.framebufferGraphicsWorker.get()); + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4{.035F, .10F, .17F, 1.F}); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 10.F); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {10.F, 8.F}); + const auto state = dkr::runtime::time_trial::progress(); + if (state.adventure != dkr::runtime::time_trial::Adventure::None) + DrawTimeTrialHud(true); + DrawReplayInputViewer(state, true); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); + inspector->endFrame(); + return true; +} + void dkr::runtime::ui::draw(RT64::Application& application) { // Publish only an atomic value; the raster worker snapshots it into the // next pass's push constants. No GPU resources or samplers are rebuilt. @@ -9345,6 +9564,9 @@ void dkr::runtime::ui::draw(RT64::Application& application) { if (application.presentQueue == nullptr || application.framebufferGraphicsWorker == nullptr) { return; } + if (dkr::runtime::time_trial::exporting_video()) + // Capture builds only the controller overlay before each authored present. + return; PumpFriendPresence(); if (!g_overlay_visible.load()) LibraryCancelAnalogueCapture(); @@ -9358,6 +9580,7 @@ void dkr::runtime::ui::draw(RT64::Application& application) { (dkr::runtime::netplay::session().runtime_view().active && dkr::runtime::netplay::session().runtime_view().state == dkr::runtime::netplay::ConnectionState::Loading); const bool show_overlay = g_overlay_visible.load(std::memory_order_acquire); + const bool show_time_trial = dkr::runtime::time_trial::active(); const bool show_fps = g_fps_overlay_enabled && dkr::runtime::enhancements::modern_presentation_enabled(); const bool show_crt = g_crt_enabled && g_crt_strength > 0.0F && dkr::runtime::enhancements::modern_presentation_enabled() && g_crt_filter_index >= 0 && @@ -9373,6 +9596,7 @@ void dkr::runtime::ui::draw(RT64::Application& application) { online_session_view.launch_countdown_active && online_session_view.launch_countdown_remaining_ms > 0U; const bool show_online_waiting = OnlineWaitingActive(online_session_view); const bool show_achievement_toast = AchievementToastVisible(); + const bool show_saving_progress = !show_overlay && dkr::cloud_saves::progress_writes.visible(); const bool show_mipmap_loading = RT64::mipLoadingVisible(); const bool show_camera_tuning = CameraTuningVisible(); const bool show_session_chat = @@ -9383,11 +9607,12 @@ void dkr::runtime::ui::draw(RT64::Application& application) { #if defined(__ANDROID__) || defined(DKR_IOS) false && // Touch Menu remains available, even when all other overlays are off. #endif - !show_starting_game && !show_achievement_toast && !show_overlay && !show_fps && !show_crt && + !show_starting_game && !show_achievement_toast && !show_saving_progress && !show_overlay && !show_fps && + !show_crt && !show_online_error && !show_online_failure_modal && !show_online_notification && !show_network && !show_controller_input && !show_online_countdown && !show_online_waiting && !show_mipmap_loading && - !show_camera_tuning && !show_session_chat && !keep_owned_ui && !dkr::sdk2::tools_open.load() && - !dkr::sdk2::debug_available()) { + !show_camera_tuning && !show_session_chat && !show_time_trial && !keep_owned_ui && + !dkr::sdk2::tools_open.load() && !dkr::sdk2::debug_available()) { if (application.presentQueue->inspector != nullptr) { detach(application); } @@ -9402,7 +9627,8 @@ void dkr::runtime::ui::draw(RT64::Application& application) { if (application.presentQueue->inspector == nullptr) { return; } - if (show_starting_game || show_overlay || show_camera_tuning || dkr::chat::typing.load() || + if (show_starting_game || show_overlay || dkr::runtime::time_trial::watching() || show_camera_tuning || + dkr::chat::typing.load() || dkr::runtime::invites::dialog()) { dkr::runtime::platform::update_ui_gamepad_navigation(); } @@ -9440,7 +9666,7 @@ void dkr::runtime::ui::draw(RT64::Application& application) { dkr::runtime::hud::set_viewport_extent(hud_viewport_width, hud_viewport_height); } ApplyStyle(); - if (DrawRuntimeStartingGame()) { + if (DrawRuntimeReturningFromRun() || DrawRuntimeStartingGame()) { DrawOnlineFailureModal(); if (show_online_error) DrawOnlineErrorNotification(); @@ -9484,7 +9710,14 @@ void dkr::runtime::ui::draw(RT64::Application& application) { } else if (sidebar_action == 2) { request_quit_popup = true; } - const bool focus_selected_page = g_overlay_focus_requested.exchange(false, std::memory_order_acq_rel); + bool focus_selected_page = g_overlay_focus_requested.exchange(false, std::memory_order_acq_rel); + if (const int requested = std::exchange(g_page_navigation_request, -1); + dkr::library_ui::is_content_page(requested)) { + focus_selected_page |= g_overlay_page.load(std::memory_order_relaxed) != requested; + g_overlay_page.store(requested, std::memory_order_relaxed); + sidebar_selection = dkr::library_ui::sidebar_parent(requested); + g_overlay_sidebar_selection.store(sidebar_selection, std::memory_order_release); + } #if defined(__ANDROID__) || defined(DKR_IOS) int mobile_page = g_overlay_page.load(std::memory_order_relaxed); dkr::runtime::mobile::menu(mobile_page, true, request_restart_popup, request_quit_popup); @@ -9523,12 +9756,6 @@ void dkr::runtime::ui::draw(RT64::Application& application) { ImGui::SetCursorPosY(sidebar_position.navigation); // The sidebar is a shoulder-button rail. Excluding its widgets from // ImGui navigation keeps the D-pad entirely inside the content panel. - if (g_page_navigation_request >= 0) { - sidebar_selection = g_page_navigation_request; - g_overlay_page = sidebar_selection; - g_overlay_sidebar_selection.store(sidebar_selection, std::memory_order_release); - g_page_navigation_request = -1; - } ImGui::PushItemFlag(ImGuiItemFlags_NoNav, true); ++g_race_button_sidebar; LibraryNavigationCheckOverlayRoute(); @@ -9688,6 +9915,16 @@ void dkr::runtime::ui::draw(RT64::Application& application) { #endif DrawPinnedAchievement(); DrawAchievementToast(); + if (show_saving_progress) + DrawSavingProgress(); + if (show_time_trial && !show_overlay) { + DrawTimeTrialHud(); + if (!show_starting_game && dkr::runtime::time_trial::watching()) + DrawReplayTheatre(); + } + if (show_time_trial) + DrawRankedPodium(); + DrawSpeedrunningRestartConfirmation(); dkr::store::overlay::end(); inspector->endFrame(); } @@ -9704,6 +9941,14 @@ bool dkr::runtime::ui::handle_runtime_event(SDL_Event* event) { if (event == nullptr) { return false; } + if (dkr::runtime::time_trial::watching() && HandleTheatreInput(*event)) + return true; + if (trial::restart_confirmation_pending() && + ((event->type == SDL_KEYDOWN && event->key.keysym.scancode == SDL_SCANCODE_ESCAPE) || + (event->type == SDL_CONTROLLERBUTTONDOWN && event->cbutton.button == SDL_CONTROLLER_BUTTON_B))) { + trial::confirm_restart(false); + return true; + } if (dkr::library_ui::runtime_intro_visible.load() && ((event->type == SDL_KEYDOWN && event->key.keysym.scancode == SDL_SCANCODE_ESCAPE) || (event->type == SDL_CONTROLLERBUTTONDOWN && event->cbutton.button == SDL_CONTROLLER_BUTTON_B))) { @@ -9788,8 +10033,8 @@ bool dkr::runtime::ui::handle_runtime_event(SDL_Event* event) { (event->type == SDL_CONTROLLERDEVICEREMOVED || (event->type == SDL_WINDOWEVENT && event->window.event == SDL_WINDOWEVENT_FOCUS_LOST))) dkr::runtime::hud::editor::interrupt_move(); - if (!dkr::runtime::hud::editor::active() && event->type == SDL_KEYDOWN && event->key.repeat == 0 && - event->key.keysym.scancode == SDL_SCANCODE_ESCAPE) { + if (!dkr::runtime::time_trial::watching() && !dkr::runtime::hud::editor::active() && event->type == SDL_KEYDOWN && + event->key.repeat == 0 && event->key.keysym.scancode == SDL_SCANCODE_ESCAPE) { toggle_overlay(); return true; } @@ -9847,7 +10092,9 @@ bool dkr::runtime::ui::handle_runtime_event(SDL_Event* event) { } bool dkr::runtime::ui::input_capture_active() { - return dkr::library_ui::runtime_intro_visible.load() || dkr::chat::captures_game_input() || + return dkr::library_ui::runtime_intro_visible.load() || dkr::runtime::time_trial::watching() || + trial::restart_confirmation_pending() || + dkr::chat::captures_game_input() || #if defined(__ANDROID__) || defined(DKR_IOS) dkr::runtime::mobile::editing() || #endif diff --git a/runtime-recomp/src/game/runtime_ui.hpp b/runtime-recomp/src/game/runtime_ui.hpp index 7c8489f4..0f9ecbf4 100644 --- a/runtime-recomp/src/game/runtime_ui.hpp +++ b/runtime-recomp/src/game/runtime_ui.hpp @@ -61,6 +61,8 @@ StartupResult run_startup_screen(SDL_Window* window, const std::filesystem::path void attach(RT64::Application& application); void detach(RT64::Application& application); void draw(RT64::Application& application); +bool draw_replay_video_inputs(RT64::Application& application); +void show_run_return_cover(bool force = false); bool handle_runtime_event(SDL_Event* event); // Once per event pump, after the events: captures the pointer for the Modern // camera's mouse orbit while racing, and lets it go when anything needs it. diff --git a/runtime-recomp/src/game/runtime_ui_paddock.inl b/runtime-recomp/src/game/runtime_ui_paddock.inl index 7903ba1d..f18ce021 100644 --- a/runtime-recomp/src/game/runtime_ui_paddock.inl +++ b/runtime-recomp/src/game/runtime_ui_paddock.inl @@ -961,22 +961,22 @@ inline bool PaddockTextLink(const char* label) { return press.pressed; } -inline float PaddockSectionTabWidth(const char* label) { - const PaddockType type = PaddockSign(19.0F, 1.4F); - return std::ceil(7.0F + 9.0F + PaddockMeasure(type, label, PaddockLabelEnd(label)) + 32.0F + 4.0F); +inline float PaddockSectionTabWidth(const char* label, bool compact = false) { + const PaddockType type = PaddockSign(compact ? 14.0F : 19.0F, 1.4F); + return std::ceil(PaddockMeasure(type, label, PaddockLabelEnd(label)) + (compact ? 26.0F : 52.0F)); } -inline float PaddockSectionTabHeight() { - return std::ceil(PaddockSign(19.0F, 1.4F).line + 20.0F + 4.0F); +inline float PaddockSectionTabHeight(bool compact = false) { + return std::ceil(PaddockSign(compact ? 14.0F : 19.0F, 1.4F).line + 24.0F); } // A launcher-lettered tab with a turning chevron (.mods-section-nav button). // `stretch` > 0 widens it, label left-aligned (.texture-disclosure). -inline bool PaddockSectionTab(const char* label, bool open, float stretch = 0.0F) { - const PaddockType type = PaddockSign(19.0F, 1.4F); +inline bool PaddockSectionTab(const char* label, bool open, float stretch = 0.0F, bool compact = false) { + const PaddockType type = PaddockSign(compact ? 14.0F : 19.0F, 1.4F); const char* end = PaddockLabelEnd(label); - const float width = std::max(PaddockSectionTabWidth(label), stretch); - const float height = PaddockSectionTabHeight(); + const float width = std::max(PaddockSectionTabWidth(label, compact), stretch); + const float height = PaddockSectionTabHeight(compact); const PaddockPress press = PaddockBeginPress(label, {width, height}); const float opened = PaddockEase(PaddockTween(PaddockKey("open", press.id), open, 0.2F, 0.2F)); ImDrawList* draw = ImGui::GetWindowDrawList(); @@ -995,10 +995,10 @@ inline bool PaddockSectionTab(const char* label, bool open, float stretch = 0.0F PaddockPanel(draw, press.min, press.max, panel); const ImU32 text = PaddockApply(state(0xFFF2C8, 0xFFF7DC, 0xFFF5D5)); const float content_top = press.min.y + 12.0F; - const float chevron_x = press.min.x + 18.0F + 3.5F - 2.0F * (1.0F - opened); + const float chevron_x = press.min.x + (compact ? 8.0F : 18.0F) + 3.5F - 2.0F * (1.0F - opened); const float chevron_y = content_top + type.line * 0.5F - 2.0F * opened; PaddockChevron(draw, {chevron_x, chevron_y}, -45.0F + 90.0F * opened, 7.0F, text, 1.5F); - const float text_x = press.min.x + 18.0F + 7.0F + 9.0F; + const float text_x = press.min.x + (compact ? 18.0F : 34.0F); PaddockDrawRun(draw, type, {text_x, content_top + 2.0F}, PaddockCol(0x031623), label, end); PaddockDrawRun(draw, type, {text_x, content_top}, text, label, end); PaddockEndPress(press, 12.0F); @@ -1039,6 +1039,7 @@ inline bool PaddockSwitch(const char* id, bool* value, const char* on_label, con 24.0F + 12.0F + std::ceil(std::max(PaddockMeasure(type, on_label), PaddockMeasure(type, off_label))); const PaddockPress press = PaddockBeginPress(id, {width, 42.0F}); if (description != nullptr && ImGui::IsItemHovered()) { + const dkr::runtime::ui::ScopedDialogStyle style({12.0F, 8.0F}, 10.0F); ImGui::SetTooltip("%s", description); } bool changed = false; @@ -1113,14 +1114,14 @@ inline bool PaddockCheckbox(const char* id, const char* label, bool* value, floa enum class PaddockFieldResult { None, Edited, GamepadActivated }; -// A fixed-size keyboard affordance leaves room for the editable text instead -// of squeezing a word button into narrow fields. -inline bool PaddockKeyboardButton() { - const auto press = PaddockBeginPress("##keyboard", {44, 44}); +// The keyboard icon keeps its width in narrow fields. +inline bool PaddockKeyboardButton(float height = 44.0F) { + const auto press = PaddockBeginPress("##keyboard", {44.0F, height}); auto* draw = ImGui::GetWindowDrawList(); PaddockFill(draw, press.min, press.max, PaddockRound(8), PaddockCol(press.hovered ? 0x234E65 : 0x173A4E)); PaddockStroke(draw, press.min, press.max, PaddockRound(8), PaddockCol(0x476373), 1); - const ImVec2 a{press.min.x + 9, press.min.y + 13}, b{press.max.x - 9, press.max.y - 12}; + const float centre = (press.min.y + press.max.y) * 0.5F; + const ImVec2 a{press.min.x + 9, centre - 9}, b{press.max.x - 9, centre + 10}; draw->AddRect(a, b, PaddockCol(0xFFF0C2), 3); for (int y = 0; y < 2; ++y) for (int x = 0; x < 5; ++x) { @@ -1131,6 +1132,7 @@ inline bool PaddockKeyboardButton() { PaddockEndPress(press, 8, 1); if (press.hovered || press.focused) { const auto item = GImGui->LastItemData; + const dkr::runtime::ui::ScopedDialogStyle style({12.0F, 8.0F}, 10.0F); ImGui::SetTooltip("On-screen keyboard"); GImGui->LastItemData = item; } diff --git a/runtime-recomp/src/game/save_manager.cpp b/runtime-recomp/src/game/save_manager.cpp index e5b05e56..55598e2a 100644 --- a/runtime-recomp/src/game/save_manager.cpp +++ b/runtime-recomp/src/game/save_manager.cpp @@ -54,6 +54,7 @@ std::mutex g_save_manager_mutex; std::vector g_staged_host_online_save; std::uint64_t g_staged_host_online_match_id = 0; std::string g_host_online_mod_profile; +void ConfigureCloudProgressRoutes(); bool ValidModProfile(std::string_view profile) { return profile.empty() || (profile.size() == 64 && std::all_of(profile.begin(), profile.end(), [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); @@ -65,8 +66,8 @@ std::filesystem::path HostOnlineSubfolder(std::string_view profile) { return folder; } -std::filesystem::path AdventurePath() { - return g_config_directory / "saves" / "dkr.us.v77.bin"; +std::filesystem::path AdventurePath(bool modded = false) { + return dkr::runtime::saves::personal_adventure_path(g_config_directory, modded); } std::string MatchIdText(std::uint64_t match_id) { @@ -221,8 +222,8 @@ bool WriteAtomic(const std::filesystem::path& destination, const std::vector roots) { @@ -463,7 +465,9 @@ std::vector dkr::runtime::saves::stored_ad continue; const bool active = storage::key(candidate) == storage::key(root); const std::string prefix = active ? "" : "Other profile/portable location: "; - admit(candidate / "saves" / "dkr.us.v77.bin", active ? 0 : 3, prefix + "Offline Adventure", + admit(personal_adventure_path(candidate, false), active ? 0 : 3, prefix + "Vanilla Adventure", + StoredSaveKind::Adventure); + admit(personal_adventure_path(candidate, true), active ? 2 : 3, prefix + "Modded Adventure", StoredSaveKind::Adventure); for (int channel = 0; channel < kControllerPakCount; ++channel) { const auto pak = candidate / ("controller-pak-" + std::to_string(channel + 1) + ".mpk"); @@ -514,10 +518,7 @@ std::vector dkr::runtime::saves::stored_ad const bool transaction = relative.starts_with("save-transactions/") && name.ends_with(".original"); if (!primary && !recovery && !preserved && !transaction) continue; - const int scope = recovery || !active ? 3 - : relative.starts_with("saves/online/") ? 1 - : relative.starts_with("saves/mods/") ? 2 - : 3; + const int scope = !recovery && active && relative.starts_with("saves/online/") ? 1 : 3; const auto kind = relative.find("custom-records-v1.bin") != std::string::npos ? StoredSaveKind::CustomRecords : relative.find("experimental-controller-paks.bin") != std::string::npos @@ -556,10 +557,10 @@ bool dkr::runtime::saves::export_stored_save(const std::filesystem::path& source return WriteAtomic(destination, bytes, validator, error); } -dkr::runtime::saves::SaveInfo dkr::runtime::saves::adventure_info() { +dkr::runtime::saves::SaveInfo dkr::runtime::saves::adventure_info(bool modded) { std::scoped_lock lock(g_save_manager_mutex); SaveInfo info{}; - info.path = AdventurePath(); + info.path = AdventurePath(modded); std::error_code error; info.exists = std::filesystem::exists(info.path, error); if (info.exists && !error) { @@ -575,11 +576,11 @@ std::filesystem::path dkr::runtime::saves::backup_directory() { return g_config_directory / "save-backups"; } -std::vector dkr::runtime::saves::adventure_backups() { +std::vector dkr::runtime::saves::adventure_backups(bool modded) { std::scoped_lock lock(g_save_manager_mutex); std::vector result; std::error_code error; - const auto directory = g_config_directory / "save-backups"; + const auto directory = g_config_directory / "save-backups" / personal_adventure_subfolder(modded); if (!std::filesystem::is_directory(directory, error)) { return result; } @@ -598,9 +599,9 @@ std::vector dkr::runtime::saves::adventure_backups() { return result; } -bool dkr::runtime::saves::backup_adventure(std::filesystem::path& created, std::string& error) { +bool dkr::runtime::saves::backup_adventure(std::filesystem::path& created, std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); - return BackupUnlocked(created, error); + return BackupUnlocked(created, error, modded); } bool dkr::runtime::saves::export_adventure(const std::filesystem::path& destination, std::string& error) { @@ -612,9 +613,9 @@ bool dkr::runtime::saves::export_adventure(const std::filesystem::path& destinat return export_stored_adventure(source, destination, error); } -bool dkr::runtime::saves::import_adventure(const std::filesystem::path& source, std::string& error) { +bool dkr::runtime::saves::import_adventure(const std::filesystem::path& source, std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); - const auto owner = storage::acquire(AdventurePath(), error); + const auto owner = storage::acquire(AdventurePath(modded), error); if (!owner) return false; std::vector bytes; @@ -623,39 +624,39 @@ bool dkr::runtime::saves::import_adventure(const std::filesystem::path& source, return false; } std::error_code equivalent_error; - if (std::filesystem::exists(AdventurePath(), equivalent_error)) { + if (std::filesystem::exists(AdventurePath(modded), equivalent_error)) { std::filesystem::path backup; std::vector current; - const bool current_valid = ReadAdventure(AdventurePath(), current); - if (current_valid && !BackupUnlocked(backup, error)) { + const bool current_valid = ReadAdventure(AdventurePath(modded), current); + if (current_valid && !BackupUnlocked(backup, error, modded)) { return false; } - if (!current_valid && !BackupRawAdventureUnlocked(backup, error)) { + if (!current_valid && !BackupRawAdventureUnlocked(backup, error, modded)) { return false; } } - return WriteAtomic(AdventurePath(), bytes, ReadAdventure, error); + return WriteAtomic(AdventurePath(modded), bytes, ReadAdventure, error); } -bool dkr::runtime::saves::reset_adventure(std::string& error) { +bool dkr::runtime::saves::reset_adventure(std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); - const auto owner = storage::acquire(AdventurePath(), error); + const auto owner = storage::acquire(AdventurePath(modded), error); if (!owner) return false; std::error_code exists_error; - if (std::filesystem::exists(AdventurePath(), exists_error)) { + if (std::filesystem::exists(AdventurePath(modded), exists_error)) { std::filesystem::path backup; - if (!BackupUnlocked(backup, error)) { + if (!BackupUnlocked(backup, error, modded)) { return false; } } - return WriteAtomic(AdventurePath(), codec::blank_bytes(), ReadAdventure, error); + return WriteAtomic(AdventurePath(modded), codec::blank_bytes(), ReadAdventure, error); } -bool dkr::runtime::saves::load_adventure(codec::SaveImage& image, std::string& error) { +bool dkr::runtime::saves::load_adventure(codec::SaveImage& image, std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); std::vector bytes; - if (!ReadAdventure(AdventurePath(), bytes)) { + if (!ReadAdventure(AdventurePath(modded), bytes)) { error = "No checksum-valid Adventure EEPROM is available to edit."; return false; } @@ -687,16 +688,16 @@ bool dkr::runtime::saves::commit_adventure(const codec::SaveImage& image, std::s } bool dkr::runtime::saves::repair_adventure_checksums(bool& changed, std::filesystem::path& original_backup, - std::string& error) { + std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); changed = false; original_backup.clear(); - const auto owner = storage::acquire(AdventurePath(), error); + const auto owner = storage::acquire(AdventurePath(modded), error); if (!owner) return false; std::vector original; - if (!ReadFileBounded(AdventurePath(), kAdventureSaveSize, original) || original.size() != kAdventureSaveSize) { + if (!ReadFileBounded(AdventurePath(modded), kAdventureSaveSize, original) || original.size() != kAdventureSaveSize) { error = "No 512-byte Adventure EEPROM is available to repair."; return false; } @@ -736,10 +737,10 @@ bool dkr::runtime::saves::repair_adventure_checksums(bool& changed, std::filesys } } - if (!BackupRawAdventureUnlocked(original_backup, error)) { + if (!BackupRawAdventureUnlocked(original_backup, error, modded)) { return false; } - if (!WriteAtomic(AdventurePath(), repaired, ReadAdventure, error)) { + if (!WriteAtomic(AdventurePath(modded), repaired, ReadAdventure, error)) { return false; } changed = true; @@ -965,9 +966,9 @@ bool dkr::runtime::saves::commit_experimental_online_paks(bool host, std::uint64 error = "Invalid confirmed online MemPak image; no file was changed."; return false; } - return WriteAtomic(g_config_directory / "saves" / OnlineAdventureSubfolder(host, match_id) / - "experimental-controller-paks.bin", - {images.begin(), images.end()}, ReadExperimentalOnlinePaks, error); + return storage::write_progress(g_config_directory / "saves" / OnlineAdventureSubfolder(host, match_id) / + "experimental-controller-paks.bin", + {images.begin(), images.end()}, ReadExperimentalOnlinePaks, error); } bool dkr::runtime::saves::commit_online_adventure(bool host, std::uint64_t match_id, std::span bytes, std::string& error) { @@ -976,7 +977,8 @@ bool dkr::runtime::saves::commit_online_adventure(bool host, std::uint64_t match error = "The confirmed online EEPROM cannot be persisted: " + error; return false; } - return WriteAtomic(OnlineAdventurePath(host, match_id), {bytes.begin(), bytes.end()}, ReadAdventure, error); + return storage::write_progress(OnlineAdventurePath(host, match_id), {bytes.begin(), bytes.end()}, ReadAdventure, + error); } dkr::runtime::saves::SaveInfo dkr::runtime::saves::controller_pak_info(int channel) { @@ -1074,13 +1076,13 @@ bool dkr::runtime::saves::import_controller_pak(int channel, const std::filesyst return WriteAtomic(ControllerPakPath(channel), bytes, ReadControllerPak, error); } -bool dkr::runtime::saves::export_bundle(const std::filesystem::path& destination, std::string& error) { +bool dkr::runtime::saves::export_bundle(const std::filesystem::path& destination, std::string& error, bool modded) { std::scoped_lock lock(g_save_manager_mutex); if (!ExportDestinationAllowed(destination, error)) return false; std::vector entries; std::vector image; - if (ReadAdventure(AdventurePath(), image)) { + if (ReadAdventure(AdventurePath(modded), image)) { entries.push_back({kBundleAdventureKind, 0U, image}); } for (int channel = 0; channel < kControllerPakCount; ++channel) { @@ -1114,8 +1116,95 @@ bool dkr::runtime::saves::export_bundle(const std::filesystem::path& destination return WriteAtomic(destination, bundle, ReadBundle, error); } -bool dkr::runtime::saves::import_bundle(const std::filesystem::path& source, std::string& error) { - return shared::apply_bundle(source, error); +bool dkr::runtime::saves::import_bundle(const std::filesystem::path& source, std::string& error, bool modded) { + return shared::apply_bundle(source, error, modded); +} + +namespace { +using dkr::runtime::saves::CloudSaveSlot; +using dkr::runtime::saves::storage::Validator; +constexpr std::size_t kCloudRecordLimit = 20 + 8192 * 76; +constexpr std::array kCloudSaveSlots{{ + {"offline-adventure", "Vanilla Adventure", 512}, + {"modded-adventure", "Modded Adventure", 512}, + {"offline-pak-1", "Controller Pak 1", kControllerPakSize}, + {"offline-pak-2", "Controller Pak 2", kControllerPakSize}, + {"offline-pak-3", "Controller Pak 3", kControllerPakSize}, + {"offline-pak-4", "Controller Pak 4", kControllerPakSize}, + {"modded-records", "Modded course records", kCloudRecordLimit}, + {"online-adventure", "Hosted Online Adventure", 512}, + {"online-records", "Hosted Online course records", kCloudRecordLimit}, + {"online-paks", "Hosted Online Controller Paks", kControllerPakSize * 4}, +}}; +struct CloudSaveTarget { + std::filesystem::path path; + Validator validate = nullptr; +}; +CloudSaveTarget CloudTarget(std::string_view key) { + const auto host = OnlineAdventurePath(true, 0).parent_path(); + if (key == "offline-adventure" || key == "modded-adventure") + return {dkr::runtime::saves::personal_adventure_path(g_config_directory, key == "modded-adventure"), + ReadAdventure}; + if (key.starts_with("offline-pak-") && key.size() == 13 && key.back() >= '1' && key.back() <= '4') + return {ControllerPakPath(key.back() - '1'), ReadControllerPak}; + if (key == "modded-records") + return {AdventurePath().parent_path() / "custom-records-v1.bin", ReadCustomRecords}; + if (key == "online-adventure") + return {host / AdventurePath().filename(), ReadAdventure}; + if (key == "online-records") + return {host / "custom-records-v1.bin", ReadCustomRecords}; + if (key == "online-paks") + return {host / "experimental-controller-paks.bin", ReadExperimentalOnlinePaks}; + return {}; +} + +void ConfigureCloudProgressRoutes() { + using dkr::runtime::saves::storage::key; + dkr::cloud_saves::ProgressWrites::Routes routes; + routes.reserve(kCloudSaveSlots.size()); + for (const auto& slot : kCloudSaveSlots) + routes.emplace_back(key(CloudTarget(slot.key).path), slot.key); + dkr::cloud_saves::progress_writes.configure(std::move(routes)); +} +} // namespace + +std::span dkr::runtime::saves::cloud_save_slots() { + return kCloudSaveSlots; +} +bool dkr::runtime::saves::read_cloud_save(std::string_view key, std::vector& bytes, std::string& error) { + std::scoped_lock lock(g_save_manager_mutex); + bytes.clear(); + const auto target = CloudTarget(key); + if (!target.validate) { + error = "Unknown Cloud Save type."; + return false; + } + if (!storage::writable_path(target.path, error)) + return false; + std::error_code ec; + const bool exists = std::filesystem::exists(target.path, ec); + if (!ec) { + if (!exists) + return true; + const auto lease = storage::acquire(target.path, error); + if (!lease) + return false; + std::scoped_lock transaction(lease->transaction); + if (target.validate(target.path, bytes)) + return true; + } + error = "This save needs recovery. Its original file was kept."; + return false; +} +bool dkr::runtime::saves::replace_cloud_save(std::string_view key, const std::vector& expected, + const std::vector& replacement, std::string& error) { + std::scoped_lock lock(g_save_manager_mutex); + const auto target = CloudTarget(key); + if (!target.validate || replacement.empty()) { + error = "Unknown or empty Cloud Save image."; + return false; + } + return storage::write_atomic(target.path, replacement, target.validate, error, &expected); } #include "shared_save_backend.inl" diff --git a/runtime-recomp/src/game/save_manager.hpp b/runtime-recomp/src/game/save_manager.hpp index d62593ee..d07b84db 100644 --- a/runtime-recomp/src/game/save_manager.hpp +++ b/runtime-recomp/src/game/save_manager.hpp @@ -29,7 +29,7 @@ constexpr int kControllerPakCount = 4; void configure(const std::filesystem::path& config_directory); // Explicit, known profile/portable locations only; never a whole-drive scan. void configure_recovery_locations(std::vector roots); -SaveInfo adventure_info(); +SaveInfo adventure_info(bool modded = false); void set_online_save_protection(bool enabled); enum class StoredSaveKind { Adventure, ControllerPak, ExperimentalPaks, CustomRecords }; struct StoredAdventure { @@ -46,14 +46,14 @@ bool export_stored_adventure(const std::filesystem::path& source, const std::fil bool export_stored_save(const std::filesystem::path& source, const std::filesystem::path& destination, StoredSaveKind kind, std::string& error); std::filesystem::path backup_directory(); -std::vector adventure_backups(); -bool backup_adventure(std::filesystem::path& created, std::string& error); +std::vector adventure_backups(bool modded = false); +bool backup_adventure(std::filesystem::path& created, std::string& error, bool modded = false); bool export_adventure(const std::filesystem::path& destination, std::string& error); -bool import_adventure(const std::filesystem::path& source, std::string& error); -bool reset_adventure(std::string& error); -bool load_adventure(codec::SaveImage& image, std::string& error); +bool import_adventure(const std::filesystem::path& source, std::string& error, bool modded = false); +bool reset_adventure(std::string& error, bool modded = false); +bool load_adventure(codec::SaveImage& image, std::string& error, bool modded = false); bool commit_adventure(const codec::SaveImage& image, std::string& error); -bool repair_adventure_checksums(bool& changed, std::filesystem::path& original_backup, std::string& error); +bool repair_adventure_checksums(bool& changed, std::filesystem::path& original_backup, std::string& error, bool modded = false); bool canonical_adventure_bytes(std::vector& bytes, std::string& error); SaveInfo previous_online_adventure_info(std::string_view mod_profile = {}); // Stages validated bytes without touching previous online progress. The host's @@ -85,7 +85,16 @@ bool import_controller_pak(int channel, const std::filesystem::path& source, std // filenames or extraction paths, so importing cannot traverse outside the // configured save directory. Adventure EEPROM and all present Controller Paks // are validated before any live file is replaced. -bool export_bundle(const std::filesystem::path& destination, std::string& error); -bool import_bundle(const std::filesystem::path& source, std::string& error); +bool export_bundle(const std::filesystem::path& destination, std::string& error, bool modded = false); +bool import_bundle(const std::filesystem::path& source, std::string& error, bool modded = false); + +struct CloudSaveSlot { + std::string_view key, label; + std::size_t limit; +}; +std::span cloud_save_slots(); +bool read_cloud_save(std::string_view key, std::vector& bytes, std::string& error); +bool replace_cloud_save(std::string_view key, const std::vector& expected, + const std::vector& replacement, std::string& error); } // namespace dkr::runtime::saves diff --git a/runtime-recomp/src/game/save_storage.hpp b/runtime-recomp/src/game/save_storage.hpp index 656985b6..3cea01e0 100644 --- a/runtime-recomp/src/game/save_storage.hpp +++ b/runtime-recomp/src/game/save_storage.hpp @@ -1,4 +1,6 @@ #pragma once +#include "cloud_saves/progress.hpp" +#include "personal_adventure_paths.hpp" // Authored save-storage policy. Never use this for renderer/configuration files. #include @@ -73,7 +75,8 @@ inline bool writable_path(const std::filesystem::path& path, std::string& error) {key(target).lexically_relative(key(protected_root)).generic_string(), key(canonical_target).lexically_relative(key(protected_canonical_root)).generic_string()}) { if (relative == "saves/dkr.us.v77.bin" || relative.starts_with("saves/dkr.us.v77.bin.") || - relative.starts_with("controller-pak-") || relative.starts_with("save-backups/") || + relative.starts_with(kModdedAdventureDirectory) || relative.starts_with("controller-pak-") || + relative.starts_with("save-backups/") || relative.starts_with("save-history/")) { error = "Offline saves are protected while an online session is active."; return false; @@ -275,13 +278,22 @@ inline bool durable_replace(const std::filesystem::path& path, std::spantransaction); Bytes previous; - if (validator && validator(path, previous)) { + const bool previous_valid = validator && validator(path, previous); + if (expected) { + std::error_code ec; + const bool exists = std::filesystem::exists(path, ec); + if (ec || (exists && !previous_valid) || *expected != previous) { + error = "This device's save changed during sync. Sync again before replacing it."; + return false; + } + } + if (previous_valid) { if (previous == bytes) { error.clear(); return true; @@ -340,6 +352,20 @@ inline bool write_atomic(const std::filesystem::path& path, const Bytes& bytes, return false; } } - return durable_replace(path, bytes, validator, error); + if (!durable_replace(path, bytes, validator, error)) + return false; + if (progress) { + try { + cloud_saves::progress_writes.committed(key(path)); + } catch (const std::exception&) { + // An optional upload signal cannot turn a committed save into a failure. + } + } + return true; +} + +inline bool write_progress(const std::filesystem::path& path, const Bytes& bytes, Validator validator, + std::string& error) { + return write_atomic(path, bytes, validator, error, nullptr, true); } } // namespace dkr::runtime::saves::storage diff --git a/runtime-recomp/src/game/shared_save_backend.inl b/runtime-recomp/src/game/shared_save_backend.inl index f3d6afd7..81e40b3e 100644 --- a/runtime-recomp/src/game/shared_save_backend.inl +++ b/runtime-recomp/src/game/shared_save_backend.inl @@ -26,7 +26,7 @@ bool write_json(const std::filesystem::path& path, const Json& doc, std::string& std::filesystem::path transaction_destination(const Json& item) { const auto kind = item.at("kind").get(); if (kind == kBundleAdventureKind && item.at("channel") == 0) - return data_root() / "saves/dkr.us.v77.bin"; + return personal_adventure_path(data_root(), item.value("modded", false)); if (kind == kBundleRecordsKind && item.at("channel") == 0) return data_root() / "saves/custom-records-v1.bin"; const auto channel = item.at("channel").get(); @@ -124,9 +124,16 @@ bool recover_unlocked(std::string& error) { } } // namespace -std::string revision() { +bool load_draft(codec::SaveImage& image, std::string& revision, std::string& error, bool modded) { + const auto path = personal_adventure_path(data_root(), modded); std::vector bytes; - return storage::read_exact(adventure_info().path, 512, bytes) ? storage::content_id(bytes) : "missing"; + if (!ReadAdventure(path, bytes) || !codec::decode(bytes, image, &error)) { + error = "No checksum-valid Adventure save is available to edit."; + return false; + } + revision = storage::content_id(bytes); + error.clear(); + return true; } bool recover_transaction(std::string& error) { std::scoped_lock lock(operation_mutex); @@ -196,11 +203,11 @@ bool prepare(const std::filesystem::path& root, std::string& error) { std::fprintf(stderr, "[save][migration] original-images=%zu retained; personal save unchanged\n", records.size()); return true; } -bool queue_development_copy(std::string& error) { +bool queue_development_copy(std::string& error, bool modded) { if (!prepare(data_root(), error)) return false; std::scoped_lock lock(operation_mutex); - const auto personal = data_root() / "saves/dkr.us.v77.bin"; + const auto personal = personal_adventure_path(data_root(), modded); auto owner = storage::acquire(personal, error); if (!owner) return false; @@ -340,25 +347,22 @@ void complete(codec::SaveImage& image, int selected) { } unlock(image); } -bool apply(const codec::SaveImage& image, std::string_view expected, std::string& error) { +bool apply(const codec::SaveImage& image, std::string_view expected, std::string& error, bool modded) { if (!prepare(data_root(), error)) return false; std::scoped_lock lock(operation_mutex); - auto owner = storage::acquire(adventure_info().path, error); + const auto path = personal_adventure_path(data_root(), modded); + auto owner = storage::acquire(path, error); if (!owner) return false; - if (revision() != expected) { + std::vector original; + if (!storage::read_exact(path, codec::kImageSize, original) || storage::content_id(original) != expected) { error = "Your save changed since this editor was opened. Reload it before applying edits; no progress was replaced."; return false; } if (!codec::validate_editable_ranges(image, &error)) return false; - std::vector original; - if (!ReadAdventure(adventure_info().path, original)) { - error = "The current personal image is not valid; use Recovery before editing."; - return false; - } codec::SaveImage previous; if (!codec::decode(original, previous, &error)) return false; @@ -375,11 +379,11 @@ bool apply(const codec::SaveImage& image, std::string_view expected, std::string if (!codec::validate(proposed, &error)) return false; std::filesystem::path backup; - if (!backup_adventure(backup, error) || - !storage::write_atomic(adventure_info().path, proposed, ReadAdventure, error)) + if (!backup_adventure(backup, error, modded) || + !storage::write_atomic(path, proposed, ReadAdventure, error)) return false; std::vector check; - if (!ReadAdventure(adventure_info().path, check) || check != proposed) { + if (!ReadAdventure(path, check) || check != proposed) { error = "The saved edit failed read-back verification. Its backup was retained."; return false; } @@ -387,7 +391,7 @@ bool apply(const codec::SaveImage& image, std::string_view expected, std::string error.clear(); return true; } -bool adopt(const std::filesystem::path& source, bool repair, std::string& error) { +bool adopt(const std::filesystem::path& source, bool repair, std::string& error, bool modded) { if (!prepare(data_root(), error)) return false; std::vector bytes; @@ -411,7 +415,7 @@ bool adopt(const std::filesystem::path& source, bool repair, std::string& error) const auto staged = data_root() / "save-recovery" / ("candidate-" + storage::content_id(bytes) + ".bin"); if (!storage::write_atomic(staged, bytes, ReadAdventure, error)) return false; - return import_adventure(staged, error); + return import_adventure(staged, error, modded); } bool export_raw(const std::filesystem::path& source, const std::filesystem::path& destination, std::string& error) { if (!ExportDestinationAllowed(destination, error)) @@ -453,7 +457,7 @@ std::string describe(const std::filesystem::path& path) { : "locked"); return text; } -bool apply_bundle(const std::filesystem::path& source, std::string& error) { +bool apply_bundle(const std::filesystem::path& source, std::string& error, bool modded) { if (!prepare(data_root(), error)) return false; std::scoped_lock lock(operation_mutex); @@ -472,6 +476,8 @@ bool apply_bundle(const std::filesystem::path& source, std::string& error) { for (std::size_t i = 0; i < entries.size(); ++i) { const auto& entry = entries[i]; Json item = {{"kind", entry.kind}, {"channel", entry.channel}}; + if (entry.kind == kBundleAdventureKind) + item["modded"] = modded; const auto dest = transaction_destination(item); auto owner = storage::acquire(dest, error); if (!owner) @@ -516,24 +522,10 @@ bool apply_bundle(const std::filesystem::path& source, std::string& error) { return false; return retire_transaction(dir, error); } -bool reset(std::string& error) { +bool reset(std::string& error, bool modded) { if (!prepare(data_root(), error)) return false; - std::vector entries{{kBundleAdventureKind, 0, codec::blank_bytes()}, - {kBundleRecordsKind, 0, records::encode({})}}; - std::vector bytes(kBundleMagic.begin(), kBundleMagic.end()); - AppendLE32(bytes, kBundleVersion); - AppendLE32(bytes, entries.size()); - for (const auto& entry : entries) { - AppendLE32(bytes, entry.kind); - AppendLE32(bytes, entry.channel); - AppendLE32(bytes, entry.bytes.size()); - AppendLE32(bytes, ImageChecksum(entry.bytes)); - bytes.insert(bytes.end(), entry.bytes.begin(), entry.bytes.end()); - } - const auto source = data_root() / "save-recovery" / ("fresh-" + Timestamp() + ".dkrsave"); - if (!storage::write_atomic(source, bytes, ReadBundle, error)) - return false; - return apply_bundle(source, error); + std::scoped_lock lock(operation_mutex); + return reset_adventure(error, modded); } } // namespace dkr::runtime::saves::shared diff --git a/runtime-recomp/src/game/shared_save_jobs.inl b/runtime-recomp/src/game/shared_save_jobs.inl index 66ed1dfc..3bc594a9 100644 --- a/runtime-recomp/src/game/shared_save_jobs.inl +++ b/runtime-recomp/src/game/shared_save_jobs.inl @@ -3,25 +3,34 @@ struct SharedSaveResult { bool ok = false; std::string message; + std::optional edited_adventure; }; std::future g_shared_save_job; -std::string g_shared_draft_revision; +struct AdventureDraft { + std::optional image; + std::optional original; + std::string revision; +}; +std::array g_adventure_drafts; std::uint64_t g_shared_save_generation = 1; struct SharedSaveImport { std::filesystem::path path; int kind = 0; int port = 0; + bool modded = false; }; SharedSaveImport g_shared_save_import; bool SharedSaveBusy() { return g_shared_save_job.valid(); } -bool BeginSharedSaveJob(std::function action, std::string success) { +bool BeginSharedSaveJob(std::function action, std::string success, + std::optional edited_adventure = std::nullopt) { if (SharedSaveBusy()) return false; g_save_manager_status = "Saving..."; - g_shared_save_job = std::async(std::launch::async, [action = std::move(action), success = std::move(success)] { + g_shared_save_job = std::async(std::launch::async, [action = std::move(action), success = std::move(success), edited_adventure] { SharedSaveResult result; + result.edited_adventure = edited_adventure; try { std::string error; result.ok = action(error); @@ -41,8 +50,8 @@ void PumpSharedSaveJob() { const auto result = g_shared_save_job.get(); g_save_manager_status = result.message; if (result.ok) { - g_save_builder_image.reset(); - g_shared_draft_revision.clear(); + if (result.edited_adventure) + g_adventure_drafts[*result.edited_adventure] = {}; ++g_shared_save_generation; InvalidateSaveManagerViewCache(); } diff --git a/runtime-recomp/src/game/shared_saves.hpp b/runtime-recomp/src/game/shared_saves.hpp index 05d2d35b..8b3795e5 100644 --- a/runtime-recomp/src/game/shared_saves.hpp +++ b/runtime-recomp/src/game/shared_saves.hpp @@ -3,21 +3,21 @@ #include namespace dkr::runtime::saves::shared { -// One personal EEPROM. Content/network identities never select this file. +// Offline Adventure editing uses the selected Vanilla or Modded save. bool prepare(const std::filesystem::path& root, std::string& error); -std::string revision(); -bool apply(const codec::SaveImage& image, std::string_view expected, std::string& error); +bool load_draft(codec::SaveImage& image, std::string& revision, std::string& error, bool modded); +bool apply(const codec::SaveImage& image, std::string_view expected, std::string& error, bool modded = false); void complete(codec::SaveImage& image, int slot); void unlock(codec::SaveImage& image); -bool adopt(const std::filesystem::path& source, bool repair, std::string& error); +bool adopt(const std::filesystem::path& source, bool repair, std::string& error, bool modded = false); bool export_raw(const std::filesystem::path& source, const std::filesystem::path& destination, std::string& error); bool import_host(const std::filesystem::path& source, std::string& error); -bool apply_bundle(const std::filesystem::path& source, std::string& error); -bool reset(std::string& error); +bool apply_bundle(const std::filesystem::path& source, std::string& error, bool modded = false); +bool reset(std::string& error, bool modded = false); bool recover_transaction(std::string& error); // Development keeps its own write owner, but a new sandbox inherits personal // progress. Refreshing an existing sandbox is a separately confirmed action. bool prepare_development(const std::filesystem::path& root, const std::filesystem::path& folder, std::string& error); -bool queue_development_copy(std::string& error); +bool queue_development_copy(std::string& error, bool modded = false); std::string describe(const std::filesystem::path& path); } // namespace dkr::runtime::saves::shared diff --git a/runtime-recomp/src/game/texture_dump_ui.inl b/runtime-recomp/src/game/texture_dump_ui.inl index c3b08154..b48d4a95 100644 --- a/runtime-recomp/src/game/texture_dump_ui.inl +++ b/runtime-recomp/src/game/texture_dump_ui.inl @@ -198,8 +198,8 @@ void DrawDumpPreviewCard(const dumping::Thumbnail& item, float width) { 166.F, kSetMuted); line(detail, item.preview_error.empty() ? item.status : "Preview unavailable", 190.F, item.preview_error.empty() ? kSetMuted : kSetWarm); - if (ImGui::IsWindowHovered() && ImGui::IsMouseHoveringRect(at, end)) { - ImGui::BeginTooltip(); + if (ImGui::IsWindowHovered() && ImGui::IsMouseHoveringRect(at, end) && + dkr::runtime::ui::begin_dialog_tooltip()) { ImGui::PushTextWrapPos(320.F); ImGui::TextUnformatted(item.name.c_str()); if (!item.preview_error.empty()) @@ -492,8 +492,8 @@ void DrawTextureDumping(float width) { ImGui::SetNextWindowSize({std::min(850.F, display.x - 32.F), std::min(display.y - 32.F, display.y * .75F)}, ImGuiCond_Always); ImGui::SetNextWindowPos({display.x * .5F, display.y * .5F}, ImGuiCond_Always, {.5F, .5F}); - if (ImGui::BeginPopupModal("Choose texture sources##dump", nullptr, - ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings)) { + if (BeginPaddockModalWindow("Choose texture sources##dump", + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings)) { const float inner = ImGui::GetContentRegionAvail().x; DetailText(state->busy ? "Loading installed sources..." : "Choose the sources to export.", inner, kSetMuted, 8.F); diff --git a/runtime-recomp/src/game/time_trial/adventure_rules.hpp b/runtime-recomp/src/game/time_trial/adventure_rules.hpp new file mode 100644 index 00000000..492b67f6 --- /dev/null +++ b/runtime-recomp/src/game/time_trial/adventure_rules.hpp @@ -0,0 +1,136 @@ +#pragma once + +#include "courses.hpp" + +#include +#include + +namespace dkr::runtime::time_trial { +enum class Adventure { + None, + AnyPercent, + HundredPercent, + AllTrophyRaces, + AllBosses, + AllMinigames, + TTAmulet, + AnyPercentGlitchless, + TrophyDinoFirst, + TrophyFutureFirst, + CarPercent, + HoverPercent, + PlanePercent, +}; + +struct AdventureCategory { + Adventure goal; + std::string_view id; + std::string_view title; +}; + +inline constexpr std::array kAdventureCategories{ + AdventureCategory{Adventure::AnyPercent, "any-percent", "Any%"}, + AdventureCategory{Adventure::HundredPercent, "100-percent", "100%"}, + AdventureCategory{Adventure::AllTrophyRaces, "all-trophy-races", "All Trophy Races"}, + AdventureCategory{Adventure::AllBosses, "all-bosses", "All Bosses"}, + AdventureCategory{Adventure::AllMinigames, "all-minigames", "All Minigames"}, + AdventureCategory{Adventure::TTAmulet, "tt-amulet-no-wrong-warp", "T.T. Amulet – No Wrong Warp"}, + AdventureCategory{Adventure::AnyPercentGlitchless, "any-percent-glitchless", "Any% Glitchless"}, + AdventureCategory{Adventure::TrophyDinoFirst, "all-trophy-races-dino-first", + "All Trophy Races - Dino Domain First"}, + AdventureCategory{Adventure::TrophyFutureFirst, "all-trophy-races-ffl-first", + "All Trophy Races - Future Fun Land First"}, + AdventureCategory{Adventure::CarPercent, "car-percent", "Car%"}, + AdventureCategory{Adventure::HoverPercent, "hover-percent", "Hover%"}, + AdventureCategory{Adventure::PlanePercent, "plane-percent", "Plane%"}, +}; + +inline constexpr std::string_view kAdventureRules = "adventure-us80-7"; +inline constexpr std::string_view kAdventureOriginalRouteRules = "adventure-us80-6"; +inline constexpr std::string_view kAdventureMilestoneRules = "adventure-us80-5"; +inline constexpr std::string_view kAdventureColdSaveRules = "adventure-us80-4"; +inline constexpr std::string_view kAdventureVisualRngRules = "adventure-us80-3"; +inline constexpr std::string_view kAdventureSharedRngRules = "adventure-us80-2"; +inline constexpr std::string_view kLegacyAdventureRules = "adventure-us80-1"; +inline constexpr unsigned kAdventureInterval = 1800; +inline constexpr unsigned kAdventureMaxUpdates = 30 * 60 * 60 * 6; + +constexpr Adventure adventure_for(std::string_view id) { + for (const auto& category : kAdventureCategories) + if (category.id == id) + return category.goal; + return Adventure::None; +} + +constexpr std::string_view adventure_id(Adventure goal) { + for (const auto& category : kAdventureCategories) + if (category.goal == goal) + return category.id; + return {}; +} + +constexpr bool tracks_route(Adventure goal, bool completed_save_rules = true) { + return (goal >= Adventure::TrophyDinoFirst && goal <= Adventure::PlanePercent) || + (completed_save_rules && (goal == Adventure::AllTrophyRaces || goal == Adventure::AllMinigames)); +} + +constexpr bool completed_save_route(Adventure goal) { + return tracks_route(goal) || goal == Adventure::AllBosses; +} + +// The original game exposes earned characters through the same two bits it +// uses for cheat state. Match init_title_screen_variables' EEPROM conditions. +constexpr unsigned earned_character_flags(unsigned eeprom) { + constexpr unsigned tt_trial_bits = 0xfffff0; + return (eeprom & 2U) | unsigned((eeprom & tt_trial_bits) == tt_trial_bits); +} + +constexpr bool trophy_route(Adventure goal) { + return goal == Adventure::AllTrophyRaces || goal == Adventure::TrophyDinoFirst || + goal == Adventure::TrophyFutureFirst; +} + +struct AdventureProgress { + unsigned balloons = 0; + unsigned keys = 0; + unsigned bosses = 0; + unsigned trophies = 0; + unsigned tt_amulet = 0; + unsigned wizpig_amulet = 0; +}; + +// The retail Adventure settings store the central-island and Future Fun +// Land Wizpig victories as separate bits. Gold is 3 in each world's two-bit +// trophy field. The four world keys occupy bits 1 through 4. +constexpr bool adventure_complete(Adventure goal, AdventureProgress progress, bool all_five_trophies = false) { + constexpr unsigned final_wizpig = 1U << 5; + constexpr unsigned four_gold_cups = 0xff; + constexpr unsigned four_world_keys = 0x1e; + const bool final_victory = (progress.bosses & final_wizpig) != 0; + const bool gold_cups = (progress.trophies & four_gold_cups) == four_gold_cups; + switch (goal) { + case Adventure::AnyPercent: + return final_victory; + case Adventure::AnyPercentGlitchless: + return final_victory && (progress.bosses & 0x3f) == 0x3f; + case Adventure::HundredPercent: + return final_victory && gold_cups && (progress.keys & four_world_keys) == four_world_keys && + progress.balloons == 47 && progress.tt_amulet == 4 && progress.wizpig_amulet == 4; + case Adventure::AllTrophyRaces: + return gold_cups && (!all_five_trophies || (progress.trophies & 0x300) == 0x300); + case Adventure::AllBosses: + return (progress.bosses & 0x3f) == 0x3f; + case Adventure::AllMinigames: + case Adventure::TTAmulet: + return progress.tt_amulet == 4 && (progress.keys & four_world_keys) == four_world_keys; + case Adventure::TrophyDinoFirst: + case Adventure::TrophyFutureFirst: + case Adventure::CarPercent: + case Adventure::HoverPercent: + case Adventure::PlanePercent: + case Adventure::None: + return false; + } + return false; +} +} // namespace dkr::runtime::time_trial diff --git a/runtime-recomp/src/game/time_trial/adventure_splits.hpp b/runtime-recomp/src/game/time_trial/adventure_splits.hpp new file mode 100644 index 00000000..5e80dc8f --- /dev/null +++ b/runtime-recomp/src/game/time_trial/adventure_splits.hpp @@ -0,0 +1,227 @@ +#pragma once + +#include "adventure_rules.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace dkr::runtime::time_trial { +struct AdventureSplit { + std::string_view label; + unsigned clock; +}; + +struct AdventureRace { + unsigned level, vehicle, trophy_world, trophy_round; + bool won; +}; + +class AdventureSplits { + unsigned challenge_world_ = 0; + unsigned course_wins_ = 0; + unsigned first_trophy_world_ = 0; + unsigned event_wins_ = 0; + std::array trophy_rounds_{}; + + static constexpr std::array minigame_maps{11, 25, 26, 27}; + static constexpr std::array boss_maps{37, 46, 52, 53, 54, 55}; + static constexpr std::array minigame_names{"Fire Mountain", "Smokey Castle", "Darkwater Beach", + "Icicle Pyramid"}; + static constexpr std::array boss_names{"Wizpig 1", "Tricky", "Bluey", "Bubbler", + "Smokey", "Wizpig 2"}; + static constexpr unsigned trophy_courses[5][4] = { + {5, 3, 29, 7}, {8, 4, 10, 30}, {13, 6, 9, 28}, {19, 18, 20, 31}, {17, 32, 33, 15}, + }; + + static constexpr Vehicle route_vehicle(Adventure goal) { + return goal == Adventure::HoverPercent ? Vehicle::Hovercraft + : goal == Adventure::PlanePercent ? Vehicle::Plane + : Vehicle::Car; + } + + public: + std::vector entries; + + static std::vector upcoming(Adventure goal, std::span completed) { + std::vector route{tracks_route(goal) ? "Start" : "Overworld"}; + const auto append = [&](std::initializer_list stages) { + route.insert(route.end(), stages); + }; + if (trophy_route(goal)) { + for (unsigned set = 0; set < 5; ++set) { + const unsigned world = goal == Adventure::TrophyFutureFirst ? 4 - set : set; + for (unsigned level : trophy_courses[world]) + if (const auto course = std::ranges::find(kCourses, level, &Course::level); course != kCourses.end()) + route.push_back(course->name); + } + } else if (goal >= Adventure::CarPercent) { + for (const auto& course : kCourses) + if (course.supports(route_vehicle(goal))) + route.push_back(course.name); + } else if (goal == Adventure::AllMinigames) { + route.insert(route.end(), minigame_names.begin(), minigame_names.end()); + } else if (goal == Adventure::AllBosses) { + append({"Tricky", "Bluey", "Bubbler", "Smokey", "Wizpig 1", "Wizpig 2"}); + } else if (goal == Adventure::TTAmulet) { + append({"Fire Mountain", "Car Challenge", "Icicle Pyramid", "Hover Challenge", "Darkwater Beach", + "Plane Challenge", "Smokey Castle"}); + } else if (goal == Adventure::AnyPercent) { + append({"Enter Wizpig 1", "Wizpig 1", "Dino 2", "Enter FFL", "Enter Wizpig 2", "Wizpig 2"}); + } else { + append({"Dino 1", "Fire Mountain", "Dino 2", "Dino Trophy", "Car Challenge", "Snowflake 1", + "Icicle Pyramid", "Snowflake 2", "Snow Trophy", "Hover Challenge", "Sherbet 1", + "Darkwater Beach", "Sherbet 2", "Sherbet Trophy", "Plane Challenge", "Dragon 1", + "Smokey Castle", "Dragon 2", "Dragon Trophy", "Enter Wizpig 1", "Wizpig 1", "Enter FFL", + "Future Fun Land 1", "Future Fun Land 2"}); + if (goal == Adventure::HundredPercent) + route.push_back("Future Fun Land Trophy"); + append({"Enter Wizpig 2", "Wizpig 2"}); + } + route.push_back("Finish"); + std::erase_if(route, [&](auto stage) { + return std::ranges::find(completed, stage, &AdventureSplit::label) != completed.end(); + }); + return route; + } + + void mark(std::string_view label, unsigned clock) { + if (std::ranges::find(entries, label, &AdventureSplit::label) == entries.end()) + entries.push_back({label, clock}); + } + + void observe_race(Adventure goal, const AdventureRace& race, unsigned clock) { + const auto course = std::ranges::find(kCourses, race.level, &Course::level); + if (course == kCourses.end()) + return; + if (trophy_route(goal)) { + if (!race.trophy_world || race.trophy_world > trophy_rounds_.size() || race.trophy_round >= 4) + return; + if (trophy_courses[race.trophy_world - 1][race.trophy_round] != race.level) + return; + auto& rounds = trophy_rounds_[race.trophy_world - 1]; + if ((rounds & (1U << race.trophy_round)) == 0) { + if (!first_trophy_world_) + first_trophy_world_ = race.trophy_world; + rounds |= 1U << race.trophy_round; + mark(course->name, clock); + } + } else if (goal >= Adventure::CarPercent && !race.trophy_world && race.won && + race.vehicle == static_cast(route_vehicle(goal)) && + course->supports(route_vehicle(goal))) { + course_wins_ |= 1U << (course - kCourses.begin()); + mark(course->name, clock); + } + } + + bool wrong_first_trophy(Adventure goal) const { + return first_trophy_world_ && ((goal == Adventure::TrophyDinoFirst && first_trophy_world_ != 1) || + (goal == Adventure::TrophyFutureFirst && first_trophy_world_ != 5)); + } + + void observe_event_win(Adventure goal, unsigned level, unsigned clock) { + const std::span maps = goal == Adventure::AllMinigames + ? std::span{minigame_maps} + : std::span{boss_maps}; + const std::span names = goal == Adventure::AllMinigames + ? std::span{minigame_names} + : std::span{boss_names}; + const auto found = std::ranges::find(maps, level); + if (found != maps.end()) { + const auto index = found - maps.begin(); + event_wins_ |= 1U << index; + mark(names[index], clock); + } + } + + bool route_complete(Adventure goal, AdventureProgress progress, bool completed_save_rules = false) const { + if (trophy_route(goal)) { + const bool raced_every_round = + std::ranges::all_of(trophy_rounds_, [](unsigned rounds) { return rounds == 0xf; }); + return raced_every_round && !wrong_first_trophy(goal) && + (completed_save_rules || goal != Adventure::AllTrophyRaces || + adventure_complete(goal, progress, true)); + } + if (completed_save_rules && goal == Adventure::AllMinigames) + return event_wins_ == (1U << minigame_maps.size()) - 1; + if (completed_save_rules && goal == Adventure::AllBosses) + return event_wins_ == (1U << boss_maps.size()) - 1; + if (completed_save_rules && goal == Adventure::HundredPercent && + !adventure_complete(Adventure::AllTrophyRaces, progress, true)) + return false; + if (goal >= Adventure::CarPercent) { + for (unsigned index = 0; index < kCourses.size(); ++index) { + if (kCourses[index].supports(route_vehicle(goal)) && !(course_wins_ & (1U << index))) + return false; + } + return true; + } + return adventure_complete(goal, progress, true); + } + + void observe_future_fun_land(std::span flags, int race_type, unsigned clock) { + constexpr std::array future_courses{15U, 17U, 32U, 33U}; + const auto cleared = [&](unsigned flag) { + return std::ranges::all_of(future_courses, [&](unsigned course) { return flags[course] & flag; }); + }; + if (flags.size() > future_courses.back()) { + if (cleared(2)) + mark("Future Fun Land 1", clock); + if (cleared(4)) + mark("Future Fun Land 2", clock); + } + if (race_type == 8) + mark("Enter Wizpig 2", clock); + } + + // Use the cartridge's persistent objective bits for clears and its live + // gameplay mode for entries. Menu transitions and deaths cannot split. + void observe(AdventureProgress before, AdventureProgress now, int race_type, unsigned world, unsigned previous_taj, + unsigned taj, unsigned clock, Adventure goal = Adventure::None) { + static constexpr std::array bosses{ + "Wizpig 1", "Dino 1", "Sherbet 1", "Snowflake 1", "Dragon 1", "Wizpig 2", + "", "Dino 2", "Sherbet 2", "Snowflake 2", "Dragon 2", + }; + static constexpr std::array cups{ + "Dino Trophy", "Sherbet Trophy", "Snow Trophy", "Dragon Trophy", "Future Fun Land Trophy", + }; + static constexpr std::array boss_names{ + "Wizpig 1", "Tricky", "Bubbler", "Bluey", "Smokey", "Wizpig 2", + }; + static constexpr std::array challenges{ + "Fire Mountain", + "Darkwater Beach", + "Icicle Pyramid", + "Smokey Castle", + }; + static constexpr std::array taj_challenges{"Car Challenge", "Hover Challenge", "Plane Challenge"}; + if (race_type == 8 && world == 0) + mark("Enter Wizpig 1", clock); + if (race_type == 5 && world == 5) + mark("Enter FFL", clock); + if (race_type >= 64 && race_type <= 66 && world >= 1 && world <= challenges.size()) + challenge_world_ = world; + if (now.tt_amulet > before.tt_amulet && challenge_world_) + mark(challenges[challenge_world_ - 1], clock); + for (unsigned i = 0; i < bosses.size(); ++i) { + if (*bosses[i] && (now.bosses & ~before.bosses & (1U << i))) { + if (goal == Adventure::AllBosses && i < boss_names.size()) + mark(boss_names[i], clock); + else + mark(bosses[i], clock); + } + } + for (unsigned i = 0; i < cups.size(); ++i) { + const unsigned shift = 2 * i; + if (((now.trophies >> shift) & 3) == 3 && ((before.trophies >> shift) & 3) != 3) + mark(cups[i], clock); + } + for (unsigned i = 0; i < taj_challenges.size(); ++i) + if (taj & ~previous_taj & (8U << i)) + mark(taj_challenges[i], clock); + } +}; +} // namespace dkr::runtime::time_trial diff --git a/runtime-recomp/src/game/time_trial/courses.hpp b/runtime-recomp/src/game/time_trial/courses.hpp new file mode 100644 index 00000000..3a5ad867 --- /dev/null +++ b/runtime-recomp/src/game/time_trial/courses.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include +#include + +namespace dkr::runtime::time_trial { +enum class Vehicle : unsigned { Car, Hovercraft, Plane }; + +inline constexpr std::array kVehicleIds{"car", "hovercraft", "plane"}; +inline constexpr std::array kVehicleNames{"Car", "Hovercraft", "Plane"}; +inline constexpr std::string_view kLegacyRules = "ancient-lake-us80-practice-2"; +inline constexpr std::string_view kVanillaRules = "vanilla-time-trial-us80-1"; +inline constexpr std::string_view kCustomRules = "custom-time-trial-us80-1"; +inline constexpr std::string_view kCustomVariableLapsRules = "custom-time-trial-us80-2"; +inline constexpr unsigned kRetailLapCount = 3; +inline constexpr unsigned kMaximumLapCount = 5; + +struct Course { + std::string_view id, name; + unsigned level, vehicles; + + constexpr bool supports(Vehicle vehicle) const { + const auto index = static_cast(vehicle); + return index < kVehicleIds.size() && (vehicles & (1U << index)) != 0; + } +}; + +// Retail Time Trial level IDs and the vehicles with save-record slots. +inline constexpr std::array kCourses{ + Course{"ancient-lake", "Ancient Lake", 5, 7}, + Course{"fossil-canyon", "Fossil Canyon", 3, 7}, + Course{"jungle-falls", "Jungle Falls", 29, 7}, + Course{"hot-top-volcano", "Hot Top Volcano", 7, 6}, + Course{"everfrost-peak", "Everfrost Peak", 13, 7}, + Course{"walrus-cove", "Walrus Cove", 6, 3}, + Course{"snowball-valley", "Snowball Valley", 9, 3}, + Course{"frosty-village", "Frosty Village", 28, 7}, + Course{"whale-bay", "Whale Bay", 8, 2}, + Course{"crescent-island", "Crescent Island", 10, 3}, + Course{"pirate-lagoon", "Pirate Lagoon", 4, 2}, + Course{"treasure-caves", "Treasure Caves", 30, 7}, + Course{"windmill-plains", "Windmill Plains", 20, 7}, + Course{"greenwood-village", "Greenwood Village", 18, 3}, + Course{"boulder-canyon", "Boulder Canyon", 19, 2}, + Course{"haunted-woods", "Haunted Woods", 31, 3}, + Course{"spacedust-alley", "Spacedust Alley", 17, 7}, + Course{"darkmoon-caverns", "Darkmoon Caverns", 32, 3}, + Course{"spaceport-alpha", "Spaceport Alpha", 15, 7}, + Course{"star-city", "Star City", 33, 7}, +}; + +constexpr const Course* course_for(std::string_view id) { + for (const auto& course : kCourses) + if (course.id == id) + return &course; + return nullptr; +} +} // namespace dkr::runtime::time_trial diff --git a/runtime-recomp/src/game/time_trial/ghost_file.hpp b/runtime-recomp/src/game/time_trial/ghost_file.hpp new file mode 100644 index 00000000..87d0fdc4 --- /dev/null +++ b/runtime-recomp/src/game/time_trial/ghost_file.hpp @@ -0,0 +1,20 @@ +#pragma once + +#include +#include +#include + +namespace dkr::runtime::time_trial { +inline constexpr std::string_view kPortableGhostSignature = "DKRPGH01"; +inline constexpr unsigned kGhostPoseBytes = 20; +inline constexpr unsigned kMaxPortableGhostBytes = 136 + 54000 * kGhostPoseBytes; + +// The replay digest covers the course, vehicle, racer, rules and recorded inputs. +inline std::string portable_ghost_prefix(std::string_view replay_digest) { + return std::string(kPortableGhostSignature).append(replay_digest); +} + +inline std::filesystem::path portable_ghost_file(std::filesystem::path replay) { + return replay.replace_extension(".dkrghost"); +} +} // namespace dkr::runtime::time_trial diff --git a/runtime-recomp/src/game/time_trial/options.hpp b/runtime-recomp/src/game/time_trial/options.hpp new file mode 100644 index 00000000..aadb261a --- /dev/null +++ b/runtime-recomp/src/game/time_trial/options.hpp @@ -0,0 +1,122 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace dkr::runtime::speedrunning { + +enum class Option { + Splits, + SplitPosition, + SplitDetail, + Comparison, + Upcoming, + Precision, + HudSize, + Inset, + Background, + Contrast, + DeltaWords, + ReducedMotion, + GhostNames, + GhostOpacity, + GhostGap, + GhostStyle, + GhostProximity, + GhostMarker, + ReplayInputs, + ReplaySplits, + InputPosition, + ReplaySpeed, + PlaybackControls, + InputSize, + SeekStep, + StartPaused, + LapMarkers, + LapDelta, + Celebration, + CelebrationScope, + FinishSummary, + CueVolume, + Retention, + ReturnTo, + PostPrompt, + RememberSetup, + ConfirmRestart, + ReplaySort, + Count +}; + +struct Setting { + std::string_view key; + int initial, maximum; +}; + +inline constexpr std::array(Option::Count)> settings{{ + {"splits", 1, 1}, {"split_position", 0, 3}, {"split_detail", 0, 2}, {"comparison", 0, 3}, + {"upcoming", 1, 2}, {"precision", 0, 1}, {"hud_size", 1, 2}, {"inset", 1, 2}, + {"background", 85, 100}, {"contrast", 0, 1}, {"delta_words", 0, 1}, {"reduced_motion", 0, 1}, + {"ghost_names", 1, 1}, {"ghost_opacity", 50, 100}, {"ghost_gap", 1, 1}, {"ghost_style", 0, 1}, + {"ghost_proximity", 0, 1}, {"ghost_marker", 1, 1}, {"replay_inputs", 1, 1}, {"replay_splits", 1, 1}, + {"input_position", 2, 3}, {"replay_speed", 1, 3}, {"playback_controls", 0, 1}, {"input_size", 1, 2}, + {"seek_step", 1, 2}, {"start_paused", 0, 1}, {"lap_markers", 1, 1}, {"lap_delta", 1, 1}, + {"celebration", 0, 2}, {"celebration_scope", 0, 2}, {"finish_summary", 1, 1}, {"cue_volume", 35, 100}, + {"retention", 0, 1}, {"return_to", 0, 1}, {"post_prompt", 1, 1}, {"remember_setup", 1, 1}, + {"confirm_restart", 0, 1}, {"replay_sort", 0, 2}, +}}; + +inline constexpr std::string_view prefix = "speedrunning_"; +inline constexpr std::array playback_speeds{50, 100, 150, 200}; +inline constexpr std::array seek_seconds{5, 10, 30}; + +class Preferences { + std::array, settings.size()> values_{}; + + public: + Preferences() { + reset(); + } + + void reset() { + for (std::size_t i = 0; i < settings.size(); ++i) + values_[i].store(settings[i].initial, std::memory_order_relaxed); + } + + int get(Option option) const { + return values_[static_cast(option)].load(std::memory_order_relaxed); + } + + void set(Option option, int value) { + const auto index = static_cast(option); + const int minimum = option == Option::Background ? 55 : 0; + values_[index].store(std::clamp(value, minimum, settings[index].maximum), std::memory_order_relaxed); + } + + bool parse(std::string_view key, std::string_view value) { + if (!key.starts_with(prefix)) + return false; + key.remove_prefix(prefix.size()); + const auto entry = std::ranges::find(settings, key, &Setting::key); + if (entry == settings.end()) + return false; + int number = 0; + const auto result = std::from_chars(value.data(), value.data() + value.size(), number); + if (result.ec == std::errc{} && result.ptr == value.data() + value.size()) + set(static_cast