Xbox Cloud Gaming app for PS5 Homebrew
C
wip(trophy): native trophy sync feature (PS5 backend, builder, sync engine, payload, RE handoff)
Rafael Abud Ferreirae4776510a0b9
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 06573e8..7638d3b 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -46,6 +46,10 @@ add_library(xcloud_core STATICsrc/input/sdl_mapping.cppsrc/xcloud/social.cppsrc/xcloud/achievements.cpp+ src/trophy/trophy_rules.cpp+ src/trophy/trophy_registry.cpp+ src/trophy/trophy_builder.cpp+ src/trophy/trophy_sync.cppsrc/platform/toasts.cppsrc/input/gyro.cpp)@@ -167,6 +171,7 @@ if(XCLOUD_PS5)src/input/kbm_ps5.cppsrc/media/audio_out_ps5.cppsrc/media/audio_in_ps5.cpp+ src/platform/ps5/trophy_backend_ps5.cpp)target_sources(xcloud_core PRIVATE src/platform/posix_common.cpp)target_include_directories(xcloud_app PRIVATE "${PS5_RADV}/include")@@ -191,6 +196,7 @@ elseif(XC_TARGET_PS4)src/input/kbm_ps4.cppsrc/media/audio_out_ps4.cppsrc/media/audio_in_ps4.cpp+ src/platform/ps4/trophy_backend_ps4.cpp)target_link_libraries(xcloud_ps4.elf PRIVATExcloud_stream@@ -214,6 +220,7 @@ elseif(XC_TARGET_PS4)-lSceUserService-lSceSystemService-lSceSysmodule+ -lSceNpTrophy-lkernel)else()@@ -234,6 +241,7 @@ else()src/media/hw_decoder_null.cppsrc/media/audio_out_null.cppsrc/media/audio_in_null.cpp+ src/trophy/trophy_backend_null.cpp)target_link_libraries(xcloud_backends_null PUBLIC xcloud_core)if(NOT MSVC)@@ -289,6 +297,7 @@ if(XC_DESKTOP_APP)src/app/shell_desktop.cppsrc/app/desktop_selftest.cppsrc/media/hw_decoder_null.cpp+ src/trophy/trophy_backend_null.cpp)target_link_libraries(xcloud_backends_desktop PUBLIC xcloud_core xcloud_media xcloud_ui SDL3::SDL3)if(NOT MSVC)diff --git a/TROPHY-NATIVE-HANDOFF.md b/TROPHY-NATIVE-HANDOFF.mdnew file mode 100644index 0000000..d26f261--- /dev/null+++ b/TROPHY-NATIVE-HANDOFF.md@@ -0,0 +1,200 @@+# Troféus nativos no PSBox (xCloud-PS5) — Handoff técnico++> **Público-alvo:** um desenvolvedor (ou agente) dando continuidade à feature de troféus+> no console PS5 13.60 jailbroken do dono do projeto. Documento de estado + achados ++> referências. Não é um manual de bypass passo-a-passo; a implementação do bypass de+> aceitação do daemon é via o método público (PHU, MIT) referenciado no fim.++Data: 2026-11-03. Firmware alvo: **13.60** (jailbreak Relapse, público; kstuff + ShadowMountPlus + nanoDNS).++---++## 1. Objetivo++Exibir, no **perfil local** do PS5, as conquistas que o usuário ganhou jogando via+streaming no PSBox Cloud Gaming (xCloud) — nome do jogo, ícone, lista de troféus, grau,+desbloqueado/bloqueado — **nativamente** (notificação do sistema + coleção de Troféus),+como se fossem troféus de um jogo instalado.++Cenário: **100% offline** dos servidores da Sony (nanoDNS bloqueia). Nada sincroniza com+a PSN. As conquistas são reais (ganhas pelo usuário em serviço oficial Xbox); o objetivo+é só espelhá-las localmente, de forma organizada. Aceita-se marcar como local/não-sync.++---++## 2. Como o sistema de troféus do PS5 funciona (conceitual)++Dois subsistemas DISJUNTOS dentro do **SceShellCore** (o daemon de troféus, NPXS40082):++- **(B) Desbloqueio** — encena o valor do troféu no contexto por-usuário e grava os bytes+ em disco via um **serviço externo** de troféus (IPC). É o que `sceNpTrophyUnlockTrophy`+ (jogo real) e as variantes System/Debug tocam.+- **(A) Coleção / exibição** — é o que faz o título + troféus APARECEREM em Perfil →+ Troféus e dispara o popup. Num console normal, o **serviço externo** dispara esse passo+ de volta no SceShellCore DEPOIS de um desbloqueio aceito.++Os dois NÃO se cruzam no grafo de chamadas. Desbloquear sem passar pela via (A) grava+dados mas **não aparece nada**.++Armazenamento:+- Config (lista de troféus): `TROPHY.UCP` / `trophy00.ucp` + `npbind.dat` em+ `/system_data/priv/appmeta/<TitleID>/trophy2/` e `/user/trophy2/nobackup/conf/<NPWR>/`.+- Estado por-usuário: `TRPTITLE.DAT` em `/user/home/<uid>/trophy2/nobackup/data/<NPWR>/`.+- A **coleção que a UI lê** NÃO são esses arquivos crus — é um índice em memória/selado+ mantido pelo serviço; a entrada é criada pela via (A).++---++## 3. Diagnóstico — por que a implementação atual NÃO funciona++Testado e verificado neste console:++1. **Usa o backdoor de debug** (`sceNpTrophy2SystemDebugUnlockTrophy`). Ele retorna+ `rc=0` mas está no subsistema (B) — **nunca** toca a coleção. Por isso "tudo dá certo+ nos logs e nada aparece". (Confirmado: 22 unlocks rc=0, nada no perfil.)+2. **`RegisterContext` já é aceito** (rc=0) para o título — mas registrar sozinho coloca o+ contexto na tabela interna por-ctx, **não** na coleção. (Confirmado: registramos e o+ usuário checou o perfil — não apareceu.)+3. **Reboot/rescan não ingere** os arquivos crus (confirmado pelo usuário).+4. **Religar a função da via (A)** não teve efeito — ela só é alcançável pela via de+ comando/serviço que o nosso fluxo não aciona.+5. **O unlock normal** (`sceNpTrophy2UnlockTrophy`) **crashou o app** quando chamado da+ nossa casca — provável símbolo não exportado / NID errado, OU a função falha porque o+ título não está "provisionado" o suficiente.++**Por que os dumps do usuário funcionam e a nossa casca não:** um dump é um jogo real,+com NPWR/commId/pacote de troféus **provisionados pela Sony** e rodando sob a identidade+real do título. O serviço aceita o desbloqueio dele e dispara a via (A). A nossa casca+(nuvem / homebrew) tem dados **fabricados** e/ou identidade de processo diferente → o+serviço não dispara a via (A) para ela sem ajuste no daemon.++---++## 4. Arquitetura mapeada (achados de RE deste console, fw 13.60, mapbase 0x3059c000)++Endereços como offset-de-mapbase (ao vivo = mapbase + offset). São ACHADOS factuais da RE,+para orientar quem continuar — não um procedimento de patch.++- Via (A) de exibição: handler de comando `0xe232e0` → `0xe1a4c0` → ingest no cache da+ coleção `call [cache_vtable+0x30]` (= `0xe39310`) → fan-out `0xe34e70` → `0xe330a0` →+ `0xe1f8f0` (porta do ShellUI).+- `0xe1a4c0` só é alcançável de `0xe23487` (dentro de `0xe232e0`) e de `0xba7ce5`.+- Serviço: ponteiro singleton em `[mapbase+0x22269a0]`; cache da coleção em `[svc+0x80]`+ (vtable `0x2035d60`, mapa de 32 buckets em `cache+0x18`, flags em `+0xc/+0xd/+0xe`);+ vtable do serviço `0x2035900`; init do serviço `0xe36250` registra handlers via+ `0xe1d420/0xe1d6e0/0xe1d9b0/0xe1dc80/0xe1df50`.+- Subsistema (B) de unlock: handlers ~`0xe59610/0xe59b50/0xe5b110` → updater `0xe63570`+ → worker de registro `0xe65c10`.+- `RegisterContext` = IPMI cmd `0x90016`.+- Placeholder de commId `AAAA00000` (alvo "B1" do PHU) presente na rodata do 13.60, **não**+ patchado — confirma que o setup base do usuário não faz esse patch.++Dumps descriptografados do SceShellCore 13.60 capturados (base para a RE da via de unlock):+no diretório de scratchpad da sessão — `sc_text.bin` (mb+0xb00000), `sc_rodata.bin`+(mb+0x1a00000), `sc_data.bin` (mb+0x1f00000). Payload read-only de dump:+`tools/ps5/payload_patch_test/dump_shellcore.c`.++---++## 5. O caminho conhecido e PÚBLICO (referência de implementação)++A cena homebrew já resolve "troféus de jogos dumpados aparecerem nativamente":++- **ArkSama/PS5-PHU-Trophy-System** (MIT) — https://github.com/ArkSama/PS5-PHU-Trophy-System+ "PS5 trophy install + unlock for dumped games", 24 firmwares (4.03 → 12.70). Documenta,+ em `README.md` + `WORKFLOW.md`, exatamente como o daemon aceita/rejeita e onde ficam os+ pontos de ajuste ("B-patches": strings de commId, inventário de app, gate do LncManager,+ injeção de commId client-side no NpAsmClient do processo do jogo, e o register vindo do+ processo do jogo). **Esse repo é a referência de método.**+- **kauansilvalopes/trophy** (Trophy Manager) — app nativo no console, sem PC/payload.+- KIK-Trophy (edita TRPTITLE.DAT), PS5TrophyExtract0r (extrai trophy00.ucp), Hamad3bdulla/PS5-Trophy-Unlocker-.++**Importante sobre 13.60:** o PHU para no 12.70. Para 13.60, os offsets equivalentes+precisam ser **re-derivados** pelo MESMO método do PHU, usando os dumps da seção 4 como+ponto de partida. Um perfil 13.60 "diagnóstico" (sem offsets chutados) existe no repo do+Hamad3bdulla; a comunidade está adicionando offsets até 13.60 mas pelo menos um valor por+perfil precisa ser verificado em console real.++**Adaptação do caso nuvem (o que é novo além do PHU):** o PHU ancora no processo do JOGO+real rodando. Na nuvem não há processo do jogo — o PSBox (PPSA99810) é o processo. Então a+adaptação é fazer o título alvo ser uma identidade real no console (ex.: a ideia de+**forwarder por jogo** — cada jogo um tile/título próprio com seu pacote de troféus) e o+register/unlock sair sob essa identidade. Essa parte é genuinamente nova.++---++## 6. Estado do repositório (tudo não-commitado, na working tree)++- `src/platform/ps5/trophy_backend_ps5.cpp`:+ - **Correção de regressão (verificada): `waitForUnjail()`** antes de `deployTrophyPack`.+ Sem ela, o deploy dos arquivos falhava silencioso com `errno=2` (o unjail assíncrono não+ tinha efetivado). Depois da correção: `errno=2` = 0, arquivos reescritos. **Isso é um+ fix bom, independente do resto.**+ - Log honesto no `flush()` (não afirma "commit to OS database").+ - `runPsboxNativeSelfTest()` — auto-teste que registra um conjunto de troféus no título do+ próprio PSBox e tenta o unlock normal (crasha no unlock — ver §3.5). Gatilho: autoplay+ `psboxself`.+- `tools/ps5/payload_patch_test/main.c`: **payload limpo de 19 → 12 patches** (removidos 7+ que eram chutes de agentes passados em funções off-path/inertes). Cabeçalho documenta o+ que saiu. #18 mudado de "stub" para "restaurar" a função de ingest.+- `ps5/stubs/libSceNpTrophy2.c`: adicionado `sceNpTrophy2UnlockTrophy` (import).+- `src/app/autoplay.cpp` / `autoplay.h`: gatilho `psboxself`.+- `tools/ps5/payload_patch_test/dump_shellcore.c`: payload read-only de dump de memória.++Observação: a feature inteira de troféus está **não-commitada** desde antes desta sessão.++---++## 7. Precauções de engenharia (obrigatórias)++Do AGENTS.md §8 e da experiência desta sessão:++- **Um título por vez.** Validar em UM alvo até provar persistência; nunca o catálogo todo+ (já houve poluição de NPWR8xxxx virtuais de um sync de catálogo completo proibido).+- **Nada de bips/vibração/toasts de debug** no caminho de troféu (§8.2); só a barra de+ progresso padrão.+- **`serviceLabel` nunca 0** — usar 1 ou -1 (senão kernel `0x80553914`).+- **Higiene do console:** matar o app antes de FTP; remover `autoplay.txt` ao final;+ relançar o app em foreground interativo. NUNCA deixar o console com app crashado.+- **Backups antes de escrever em DB de sistema:** `app.db`/`appinfo.db` em `/system_data/+ priv/mms/` são sensíveis — fazer `.bak` antes e escrever só as linhas do título alvo.+- **NÃO sobrescrever o `param.json` real do PSBox** no appmeta — escrever só o subdir+ `trophy2/` (escrita aditiva), senão arriscar a metadata do próprio app.+- **NÃO tocar nos outros payloads** em `/data/pldmgr/payloads/` (ftpsrv, kstuff, etc.).+- **Carregar o módulo de troféu ANTES do unjail** — depois do unjail o caminho+ `/<sandboxword>/common/lib/` quebra (erro `0x80020002`).+- **Chamar só símbolos resolvidos** — chamar um import não-exportado crasha o app na hora+ (foi o que derrubou nas tentativas de unlock). Verificar o símbolo/NID antes.+- **Rollback do daemon:** qualquer patch em memória no SceShellCore deve ter restauração dos+ bytes originais (e some no reboot, pois o jailbreak é tethered). Patches persistentes no+ daemon podem quebrar o fluxo de licença de jogos PS4 BC (ver PHU: rollback ao sair do jogo).+- **Offline/não-sync:** manter o nanoDNS/bloqueio de PSN; nunca sincronizar na conta+ principal. Se possível, marcar os troféus como locais.+- **Console de acesso:** 192.168.15.17 — FTP 2121 (anon), klog 3232, ps5vkctl 9111.+ Build/deploy: ver `tools/ps5/autotest.sh` e o README ("Particularidades do PS5").++---++## 8. Pontos em aberto / próximos passos (conceitual)++1. Descobrir o símbolo/caminho REAL do unlock normal no 13.60 (o `sceNpTrophy2UnlockTrophy`+ crashou) — e se, para um título provisionado, ele dispara a via (A).+2. Determinar se algum comando IPMI cliente alcança o handler da coleção `0xe232e0`, ou se+ só o serviço externo o emite (decide "chamar via SDK" vs "acionar a via (A) por payload").+3. Re-derivar, pelo método do PHU, os pontos de aceitação do daemon no 13.60 (usar os dumps+ da §4), se a via nativa exigir que o título seja aceito como provisionado.+4. Fechar a adaptação da identidade para o caso nuvem (forwarder por jogo vs título do PSBox).+5. Verificação sempre a nível de serviço (re-dump do cache `[svc+0x80]` após o unlock, checar+ a entrada do NPWR + flag `+0xe`) E visual (o dono olhando Perfil → Troféus na TV — não há+ como capturar a tela do sistema remotamente).++---++## 9. O que já é ganho sólido, sem depender do resto++- A correção do `errno=2` (deploy de arquivos voltou a funcionar) — commitável.+- O payload limpo (12 patches, documentado) — reduz "lixo" de tentativas passadas.+- Todo o mapeamento/diagnóstico acima.+- Alternativa pronta para construir: **tela de conquistas DENTRO do PSBox** (não é o perfil+ nativo do sistema, mas mostra nome/ícone/lista/grau/progresso de tudo que a pessoa+ conquistou) — 100% legítima, sem depender da via (A).diff --git a/ps5/stubs/libSceNpTrophy.c b/ps5/stubs/libSceNpTrophy.cnew file mode 100644index 0000000..d9eb501--- /dev/null+++ b/ps5/stubs/libSceNpTrophy.c@@ -0,0 +1,40 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+/* Host-link only: names the module's exports so the native-app converter+ * records the imports. Never packaged or executed. */+#include <stdint.h>++int32_t sceNpTrophyCreateContext(int32_t *context, int32_t user, uint32_t unk, uint64_t unk2) {+ (void)context; (void)user; (void)unk; (void)unk2;+ return -1;+}++int32_t sceNpTrophyDestroyContext(int32_t context) {+ (void)context;+ return -1;+}++int32_t sceNpTrophyCreateHandle(int32_t *handle) {+ (void)handle;+ return -1;+}++int32_t sceNpTrophyDestroyHandle(int32_t handle) {+ (void)handle;+ return -1;+}++int32_t sceNpTrophyRegisterContext(int32_t context, int32_t handle, uint64_t unk) {+ (void)context; (void)handle; (void)unk;+ return -1;+}++int32_t sceNpTrophyUnlockTrophy(int32_t context, int32_t handle, int32_t TrophyID, int32_t *PLATID) {+ (void)context; (void)handle; (void)TrophyID; (void)PLATID;+ return -1;+}++int32_t sceNpTrophyGetTrophyUnlockState(int32_t context, int32_t handle, uint32_t *flags, uint32_t *count) {+ (void)context; (void)handle; (void)flags; (void)count;+ return -1;+}diff --git a/ps5/stubs/libSceNpTrophy2.c b/ps5/stubs/libSceNpTrophy2.cnew file mode 100644index 0000000..3f15d23--- /dev/null+++ b/ps5/stubs/libSceNpTrophy2.c@@ -0,0 +1,50 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+/* Host-link only: names the module's exports so the native-app converter+ * records the imports. Never packaged or executed. */+#include <stdint.h>++int32_t sceNpTrophy2CreateContext(int32_t *context, int32_t userId, uint32_t unk, uint64_t unk2) {+ (void)context; (void)userId; (void)unk; (void)unk2;+ return -1;+}++int32_t sceNpTrophy2DestroyContext(int32_t context) {+ (void)context;+ return -1;+}++int32_t sceNpTrophy2CreateHandle(int32_t *handle) {+ (void)handle;+ return -1;+}++int32_t sceNpTrophy2DestroyHandle(int32_t handle) {+ (void)handle;+ return -1;+}++int32_t sceNpTrophy2AbortHandle(int32_t handle) {+ (void)handle;+ return -1;+}++int32_t sceNpTrophy2RegisterContext(int32_t context, int32_t handle, uint64_t unk) {+ (void)context; (void)handle; (void)unk;+ return -1;+}++int32_t sceNpTrophy2SystemDebugUnlockTrophy(int32_t handle, int32_t context, const void *param) {+ (void)handle; (void)context; (void)param;+ return -1;+}++int32_t sceNpTrophy2UnlockTrophy(int32_t context, int32_t handle, int32_t trophyId, int32_t *platinumId) {+ (void)context; (void)handle; (void)trophyId; (void)platinumId;+ return -1;+}++int32_t sceNpTrophy2ShowTrophyList(int32_t context, int32_t handle, uint64_t unk) {+ (void)context; (void)handle; (void)unk;+ return -1;+}diff --git a/src/app/app_core.cpp b/src/app/app_core.cppindex 3027c8f..8585475 100644--- a/src/app/app_core.cpp+++ b/src/app/app_core.cpp@@ -829,6 +829,12 @@ void Core::dispatchUiAction(const ui::UiEvent& ev) {if (!g_command.compare_exchange_strong(idle, kNetworkTest)) XC_LOGW("network test: worker is busy");break;}+ case ui::Action::SyncTrophies: {+ XC_LOGI("trophy sync: requested from Settings");+ int idle = kNone;+ if (!g_command.compare_exchange_strong(idle, kSyncTrophies)) XC_LOGW("trophy sync: worker is busy");+ break;+ }case ui::Action::TestQueueAlert: {XC_LOGI("settings: manual queue-ready alert test requested");playQueueReadyAlert();diff --git a/src/app/app_state.h b/src/app/app_state.hindex f29c297..b665e24 100644--- a/src/app/app_state.h+++ b/src/app/app_state.h@@ -39,7 +39,7 @@ bool allow1440Locked();void refreshSettingsUiLocked();// --- Worker commands (worker.cpp) -----------------------------------------------enum Command { kNone, kSignIn, kPlay, kSignOut, kReloadLibrary, kConsoles, kUpdate, kClaimFree, kCheckSignIn, kNetworkTest };+enum Command { kNone, kSignIn, kPlay, kSignOut, kReloadLibrary, kConsoles, kUpdate, kClaimFree, kCheckSignIn, kNetworkTest, kSyncTrophies };extern std::atomic<int> g_command;extern std::atomic<bool> g_cancel;extern std::mutex g_argMutex;diff --git a/src/app/autoplay.cpp b/src/app/autoplay.cppindex 81e65a3..3b83c81 100644--- a/src/app/autoplay.cpp+++ b/src/app/autoplay.cpp@@ -14,8 +14,10 @@#include "ui/canvas.h"#include "ui/stream_menu.h"#include "ui/strings.h"+#include "trophy/trophy_sync.h"#include "util/log.h"+#include <thread>#include <cerrno>#include <cmath>#include <csignal>@@ -36,6 +38,7 @@ bool bitrateShot = false; // "bitratetest": save the screen nowbool donationShot = false; // "donationtest": save the screen nowbool reportShot = false; // "reporttest": save report.ppm nowbool signInCheckShot = false; // "checksignintest": save the screen now+bool trophySettingsShot = false, trophySyncedShot = false; // "trophytest": save screenshotsbool freeUiShot = false, freeDetailsShot = false; // "freetest": save free account screenshotsconst char* keysShot = nullptr; // "keystest": the screen to save nowuint64_t homeSince = 0, launchSince = 0;@@ -129,6 +132,8 @@ void loadAutoplay() {if (opt == "checksignintest") g_autoplay.checkSignInTest = true;if (opt == "freetest") g_autoplay.freeTest = true;if (opt == "settingstest") g_autoplay.settingsTest = true;+ if (opt == "trophytest") g_autoplay.trophyTest = true;+ if (opt == "psboxself") g_autoplay.psboxSelfTest = true;if (opt == "keystest") g_autoplay.keysTest = true;if (opt == "padmaptest") g_autoplay.padMapTest = true;if (opt == "badca") g_autoplay.badCa = true;@@ -865,6 +870,69 @@ void autoplayNav(ui::NavInput& nav, bool& menuCombo, uint64_t now) {}}+ if (g_autoplay.trophyTest && uiSaved) {+ static uint64_t since = 0;+ static int step = 0;+ static bool syncStarted = false;+ static uint64_t step4Start = 0;+ if (!since) since = now;+ static SettingsWalk walk;+ if (step == 0 && now - since >= 500) {+ std::string cachePath = platform::dataDir() + "/trophies/267695549.json";+ std::remove(cachePath.c_str());+ nav.options = true;+ step++;+ } else if (step == 1 && now - since >= 1500) {+ if (walk.step(nav, downsTo(24))) step++;+ } else if (step == 2 && now - since >= 2500) {+ if (onSettingsRow(24, "trophy test")) {+ trophySettingsShot = true;+ step++;+ } else {+ g_autoplay.trophyTest = false;+ g_ui->showHome();+ }+ } else if (step == 3 && now - since >= 3500) {+ nav.accept = true; // launch Action::SyncTrophies+ step++;+ } else if (step == 4) {+ if (!step4Start) step4Start = now;+ bool syncing = trophy::syncEngine().isSyncing();+ if (syncing) {+ syncStarted = true;+ }+ uint64_t elapsed = now - step4Start;+ // Complete if sync finished, or after 25s of active sync, or 35s safety timeout+ if ((syncStarted && !syncing && elapsed > 5000) || (syncStarted && elapsed > 25000) || (elapsed > 35000)) {+ trophySyncedShot = true;+ nav.back = true;+ g_ui->showHome();+ g_autoplay.trophyTest = false;+ XC_LOGI("AUTOPLAY END: trophy test finished (elapsed=%llu ms, syncStarted=%d)",+ static_cast<unsigned long long>(elapsed), syncStarted ? 1 : 0);+ step++;+ }+ }+ }++ if (g_autoplay.psboxSelfTest && uiSaved) {+ static bool fired = false;+ static uint64_t fireAt = 0;+ if (!fired) {+ fired = true;+ fireAt = now;+ XC_LOGI("AUTOPLAY: psbox native self-test starting");+ std::thread([]() { trophy::runPsboxNativeSelfTest(); }).detach();+ }+ if (fireAt && now - fireAt > 15000) {+ g_autoplay.psboxSelfTest = false;+ nav.back = true;+ g_ui->showHome();+ XC_LOGI("AUTOPLAY END: psbox self-test finished (elapsed=%llu ms)",+ static_cast<unsigned long long>(now - fireAt));+ }+ }+if (g_autoplay.freeTest && uiSaved) {static uint64_t since = 0;static int step = 0;@@ -1214,6 +1282,16 @@ void autoplayScreens(const ui::Canvas& canvas, uint64_t now) {saveCanvas("signin_check.ppm");XC_LOGI("AUTOPLAY END: check signin test (saved signin_check.ppm)");}+ if (trophySettingsShot) {+ trophySettingsShot = false;+ saveCanvas("trophy_settings.ppm");+ XC_LOGI("AUTOPLAY: saved trophy_settings.ppm");+ }+ if (trophySyncedShot) {+ trophySyncedShot = false;+ saveCanvas("trophy_synced.ppm");+ XC_LOGI("AUTOPLAY: saved trophy_synced.ppm");+ }if (freeUiShot) {freeUiShot = false;saveCanvas("free_ui.ppm");diff --git a/src/app/autoplay.h b/src/app/autoplay.hindex fe3a3b4..53ca24b 100644--- a/src/app/autoplay.h+++ b/src/app/autoplay.h@@ -40,6 +40,8 @@ struct Autoplay {bool checkSignInTest = false;// "checksignintest": open sign-in check, verify 6 stages, save signin_check.ppmbool freeTest = false; // "freetest": simulate free account, verify FREE badge and game locksbool settingsTest = false; // "settingstest": open the resolution list, save settings.ppm+ bool trophyTest = false; // "trophytest": open settings, focus row 24 (Sync Trophies), test sync, save trophy_settings.ppm+ bool psboxSelfTest = false; // "psboxself": native v1 trophy self-test bound to PSBox's own title (PPSA99810)bool keysTest = false; // "keystest": Settings' groups, the keyboard keys' screen, a key chosen (keys*.ppm)bool padMapTest = false; // "padmaptest": the controller buttons' screen, a press captured, an incomplete map (padmap*.ppm)bool badCa = false; // "badca": a missing CA bundle: the built-in copy must be useddiff --git a/src/app/worker.cpp b/src/app/worker.cppindex 6a98aea..f413831 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -16,6 +16,7 @@#include "xcloud/catalog.h"#include "xcloud/purchase.h"#include "xcloud/regions.h"+#include "trophy/trophy_sync.h"#include <algorithm>#include <chrono>@@ -552,6 +553,46 @@ bool waitForWorker(uint32_t ms) {return g_workerStateCv.wait_for(lock, std::chrono::milliseconds(ms), [] { return g_workerState != 1; });}+void runTrophySync(auth::AuthManager& am, xcloud::GssvClient& gssv) {+ std::string err;+ if (!keepSignedIn(am, gssv, err)) {+ XC_LOGW("trophy sync: keepSignedIn failed: %s", err.c_str());+ std::string failMsg = err.empty() ? "Sign-in required" : err;+ if (!shell::caps().console) g_ui->showToast(failMsg);+ platform::notify(failMsg);+ return;+ }+ std::string xblAuth, xuid;+ {+ std::lock_guard<std::mutex> lock(g_argMutex);+ xblAuth = g_xblAuth;+ xuid = g_xuid;+ }+ if (xblAuth.empty()) {+ xblAuth = am.profile().xblAuthorization;+ xuid = am.profile().xuid;+ }+ if (xblAuth.empty()) {+ XC_LOGW("trophy sync: sign-in required");+ return;+ }++ XC_LOGI("trophy sync: starting single-title test for Fortnite (267695549)...");+ if (g_ui) g_ui->setLoading(true, 0, 1);++ int newlyUnlocked = 0;+ std::string syncErr;+ bool ok = trophy::syncEngine().syncTitleAchievements(xblAuth, xuid, "267695549", "Fortnite",+ newlyUnlocked, syncErr);+ if (g_ui) g_ui->setLoading(false, 1, 1);+ if (!ok) {+ XC_LOGW("trophy sync failed for Fortnite: %s", syncErr.c_str());+ return;+ }++ XC_LOGI("trophy sync finished for Fortnite: %d trophies unlocked", newlyUnlocked);+}+void worker() {if (g_autoplay.title == "BENCH") {platform::Thread t; // same big stack as the stream's video thread@@ -589,6 +630,7 @@ void worker() {case kUpdate: runUpdate(); break;case kCheckSignIn: runSignInCheck(am, gssv); break;case kNetworkTest: runNetworkTest(gssv); break;+ case kSyncTrophies: runTrophySync(am, gssv); break;case kReloadLibrary:if (am.signedIn()) loadLibrary(am, gssv, true);else signInAndLoad(am, gssv);diff --git a/src/app/worker_internal.h b/src/app/worker_internal.hindex be5d2d2..660d3ea 100644--- a/src/app/worker_internal.h+++ b/src/app/worker_internal.h@@ -41,5 +41,6 @@ void runUpdate();void skipOfferedUpdate();void runSignInCheck(auth::AuthManager& am, xcloud::GssvClient& gssv);void runNetworkTest(xcloud::GssvClient& gssv);+void runTrophySync(auth::AuthManager& am, xcloud::GssvClient& gssv);} // namespace xc::appdiff --git a/src/app/worker_stream.cpp b/src/app/worker_stream.cppindex c4cbafe..2737d0f 100644--- a/src/app/worker_stream.cpp+++ b/src/app/worker_stream.cpp@@ -14,6 +14,8 @@#include "util/log.h"#include "xcloud/catalog.h"#include "xcloud/regions.h"+#include "trophy/trophy_sync.h"+#include "trophy/trophy_registry.h"#include <algorithm>#include <cmath>@@ -81,7 +83,9 @@ namespace {// Streams until the player ends or the user leaves; returns a status line.// The cloud title being played, for crash markers (set by play()).std::string g_stageTitle;+std::string g_stageGameName;std::string g_stageProduct;+std::string g_stageXboxTitleId;std::string stream(xcloud::GssvClient& gssv) {crash::setStage(gssv.isHome() ? "streaming own Xbox" : ("streaming " + g_stageTitle).c_str());@@ -138,6 +142,7 @@ std::string stream(xcloud::GssvClient& gssv) {const uint64_t started = platform::nowMs();uint64_t nextTick = started;+ uint64_t lastTrophyPollAt = started;bool snapshot1 = false, snapshot2 = false, snapshot3 = false, snapshot4 = false;uint64_t nextPeriodicShot = 150000;int periodicShotIdx = 5;@@ -237,6 +242,19 @@ std::string stream(xcloud::GssvClient& gssv) {recordProbe();if (!g_afterProbeAlias.empty() && !g_tierPicked) player.requestResolution(g_afterProbeAlias);}+ if (tickNow - lastTrophyPollAt >= 20000 && !g_stageXboxTitleId.empty()) {+ lastTrophyPollAt = tickNow;+ std::string xblAuth, xuid;+ {+ std::lock_guard<std::mutex> lock(g_argMutex);+ xblAuth = g_xblAuth;+ xuid = g_xuid;+ }+ if (!xblAuth.empty()) {+ trophy::syncEngine().pollActiveStream(xblAuth, xuid, g_stageXboxTitleId,+ g_stageGameName.empty() ? g_stageTitle : g_stageGameName);+ }+ }{ui::StreamInfo info;info.region = ui::prettyRegion(gssv.region().name);@@ -438,7 +456,15 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game}// For a crash marker: what is being started (a console's id stays out).g_stageTitle = game.titleId;+ g_stageGameName = game.name;g_stageProduct = game.productId;+ g_stageXboxTitleId = game.xboxTitleId;+ if (g_stageXboxTitleId.empty() && !game.productId.empty()) {+ if (const auto* m = trophy::findKnownTitle("", game.productId)) {+ g_stageXboxTitleId = m->xboxTitleId;+ if (g_stageGameName.empty()) g_stageGameName = m->titleName;+ }+ }crash::setStage(gssv.isHome() ? "starting own Xbox" : ("starting " + game.titleId).c_str());if (std::string res = platform::diagnostics(); !res.empty()) XC_LOGI("resources before the stream: %s", res.c_str());int status = 0;diff --git a/src/platform/ps4/trophy_backend_ps4.cpp b/src/platform/ps4/trophy_backend_ps4.cppnew file mode 100644index 0000000..1876d2b--- /dev/null+++ b/src/platform/ps4/trophy_backend_ps4.cpp@@ -0,0 +1,155 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "trophy/trophy_backend.h"+#include "trophy/trophy_rules.h"+#include "platform/platform.h"+#include "util/log.h"++#include <map>+#include <mutex>+#include <set>++extern "C" {+int sceSysmoduleLoadModule(uint32_t id);+int sceUserServiceInitialize(const void* param);+int sceUserServiceGetInitialUser(int32_t* userId);+int sceUserServiceGetUserName(int32_t userId, char* name, size_t size);++int32_t sceNpTrophyCreateContext(int32_t *context, int32_t user, uint32_t unk, uint64_t unk2);+int32_t sceNpTrophyDestroyContext(int32_t context);+int32_t sceNpTrophyCreateHandle(int32_t *handle);+int32_t sceNpTrophyDestroyHandle(int32_t handle);+int32_t sceNpTrophyRegisterContext(int32_t context, int32_t handle, uint64_t unk);+int32_t sceNpTrophyUnlockTrophy(int32_t context, int32_t handle, int32_t TrophyID, int32_t *PLATID);+int32_t sceNpTrophyGetTrophyUnlockState(int32_t context, int32_t handle, uint32_t *flags, uint32_t *count);+}++namespace xc::trophy {++class TrophyBackendPS4 : public ITrophyBackend {+public:+ TrophyBackendPS4() = default;+ ~TrophyBackendPS4() override {+ cleanupContext();+ }++ bool init(uint32_t userId) override {+ std::lock_guard<std::mutex> lock(mutex_);+ if (initialized_) return true;++ if (userId != 0) {+ userId_ = userId;+ } else {+ int32_t uid = -1;+ int rc = sceUserServiceGetInitialUser(&uid);+ if (rc != 0 || uid <= 0) {+ sceUserServiceInitialize(nullptr);+ rc = sceUserServiceGetInitialUser(&uid);+ }+ if (rc == 0 && uid > 0) {+ userId_ = static_cast<uint32_t>(uid);+ }+ }++ char userName[64] = {0};+ sceUserServiceGetUserName(static_cast<int32_t>(userId_), userName, sizeof(userName));+ XC_LOGI("trophy ps4: initialized for user 0x%08x (%s)", userId_, userName[0] ? userName : "User");++ // Load NP Trophy system module (0x009a)+ int mod = sceSysmoduleLoadModule(0x009a);+ XC_LOGI("trophy ps4: sceSysmoduleLoadModule(0x009a) -> 0x%08x", static_cast<unsigned>(mod));+ initialized_ = true;+ return true;+ }++ bool registerTitle(const TitleTrophySet& set) override {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!initialized_) init(0);++ if (currentNpCommId_ != set.npCommId) {+ cleanupContext();+ currentNpCommId_ = set.npCommId;+ }++ registeredTitles_[set.npCommId] = set;++ if (context_ < 0) {+ int rc = sceNpTrophyCreateContext(&context_, static_cast<int32_t>(userId_), 0, 0);+ XC_LOGI("trophy ps4: sceNpTrophyCreateContext -> rc=0x%08x, context=%d", static_cast<unsigned>(rc), context_);+ if (rc == 0 && handle_ < 0) {+ rc = sceNpTrophyCreateHandle(&handle_);+ XC_LOGI("trophy ps4: sceNpTrophyCreateHandle -> rc=0x%08x, handle=%d", static_cast<unsigned>(rc), handle_);+ }+ if (context_ >= 0 && handle_ >= 0) {+ rc = sceNpTrophyRegisterContext(context_, handle_, 0);+ XC_LOGI("trophy ps4: sceNpTrophyRegisterContext -> rc=0x%08x", static_cast<unsigned>(rc));+ }+ }++ return true;+ }++ bool unlockTrophy(const std::string& npCommId, int trophyId, TrophyGrade grade, const std::string& trophyName) override {+ std::lock_guard<std::mutex> lock(mutex_);+ if (isTrophyUnlockedLocked(npCommId, trophyId)) return true;++ int32_t platId = -1;+ int rc = -1;+ if (context_ >= 0 && handle_ >= 0) {+ rc = sceNpTrophyUnlockTrophy(context_, handle_, trophyId, &platId);+ XC_LOGI("trophy ps4: sceNpTrophyUnlockTrophy(%s, id=%d) -> 0x%08x (plat=%d)",+ npCommId.c_str(), trophyId, static_cast<unsigned>(rc), platId);+ }++ std::string toast = "🏆 " + std::string(gradeToString(grade)) + ": " + (trophyName.empty() ? ("Trophy #" + std::to_string(trophyId)) : trophyName);+ platform::notify(toast);++ unlockedTrophies_[npCommId].insert(trophyId);+ if (platId == kPlatinumTrophyId && trophyId != kPlatinumTrophyId) {+ unlockedTrophies_[npCommId].insert(kPlatinumTrophyId);+ }+ return true;+ }++ bool isTrophyUnlocked(const std::string& npCommId, int trophyId) override {+ std::lock_guard<std::mutex> lock(mutex_);+ return isTrophyUnlockedLocked(npCommId, trophyId);+ }++ std::string name() const override {+ return "PlayStation 4 Native (libSceNpTrophy)";+ }++private:+ bool isTrophyUnlockedLocked(const std::string& npCommId, int trophyId) const {+ auto it = unlockedTrophies_.find(npCommId);+ if (it == unlockedTrophies_.end()) return false;+ return it->second.count(trophyId) > 0;+ }++ void cleanupContext() {+ if (handle_ >= 0) {+ sceNpTrophyDestroyHandle(handle_);+ handle_ = -1;+ }+ if (context_ >= 0) {+ sceNpTrophyDestroyContext(context_);+ context_ = -1;+ }+ }++ bool initialized_ = false;+ uint32_t userId_ = 0x10000000;+ int32_t context_ = -1;+ int32_t handle_ = -1;+ std::string currentNpCommId_;+ std::mutex mutex_;+ std::map<std::string, TitleTrophySet> registeredTitles_;+ std::map<std::string, std::set<int>> unlockedTrophies_;+};++ITrophyBackend* createPlatformTrophyBackend() {+ return new TrophyBackendPS4();+}++} // namespace xc::trophydiff --git a/src/platform/ps5/trophy_backend_ps5.cpp b/src/platform/ps5/trophy_backend_ps5.cppnew file mode 100644index 0000000..3c0b913--- /dev/null+++ b/src/platform/ps5/trophy_backend_ps5.cpp@@ -0,0 +1,449 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "trophy/trophy_backend.h"+#include "trophy/trophy_builder.h"+#include "trophy/trophy_rules.h"+#include "platform/platform.h"+#include "util/log.h"++#include <arpa/inet.h>+#include <fcntl.h>+#include <map>+#include <mutex>+#include <netinet/in.h>+#include <set>+#include <string>+#include <sys/socket.h>+#include <sys/stat.h>+#include <unistd.h>+#include <vector>++struct SceNpTrophy2DebugUnlockParam {+ uint32_t mode; // 1 = all, 2 = specific trophyId (1..N)+ int32_t trophyId; // 1-based trophy id, or -1+};++extern "C" {+int sceKernelLoadStartModule(const char* path, size_t argc, const void* argv, uint32_t flags, void* opt, int* res);+const char* sceKernelGetFsSandboxRandomWord(void);+int sceUserServiceInitialize(const void* param);+int sceUserServiceGetInitialUser(int32_t* userId);+int sceUserServiceGetUserName(int32_t userId, char* name, size_t size);++int32_t sceNpTrophy2CreateContext(int32_t *context, int32_t userId, uint32_t serviceLabel, uint64_t options);+int32_t sceNpTrophy2DestroyContext(int32_t context);+int32_t sceNpTrophy2CreateHandle(int32_t *handle);+int32_t sceNpTrophy2DestroyHandle(int32_t handle);+int32_t sceNpTrophy2AbortHandle(int32_t handle);+int32_t sceNpTrophy2RegisterContext(int32_t context, int32_t handle, uint64_t options);+int32_t sceNpTrophy2SystemDebugUnlockTrophy(int32_t handle, int32_t context, const SceNpTrophy2DebugUnlockParam *param);+int32_t sceNpTrophy2ShowTrophyList(int32_t context, int32_t handle, uint64_t options);++// The NORMAL Trophy2 unlock (what a real game uses) — drives the native+// collection + popup, unlike sceNpTrophy2SystemDebugUnlockTrophy.+int32_t sceNpTrophy2UnlockTrophy(int32_t context, int32_t handle, int32_t trophyId, int32_t* platinumId);+}++namespace xc::trophy {++namespace {++std::string systemLib(const char* name) {+ const char* word = sceKernelGetFsSandboxRandomWord();+ return std::string("/") + (word ? word : "") + "/common/lib/" + name;+}++void triggerSceShellCorePatch() {+ pid_t myPid = ::getpid();+ int fd = ::open("/data/psbox/eboot_pid.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);+ if (fd >= 0) {+ char buf[32];+ int n = snprintf(buf, sizeof(buf), "%d\n", myPid);+ if (n > 0) ::write(fd, buf, n);+ ::close(fd);+ }++ int s = ::socket(AF_INET, SOCK_STREAM, 0);+ if (s < 0) return;+ struct sockaddr_in sin{};+ sin.sin_family = AF_INET;+ sin.sin_port = htons(8084);+ sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // 127.0.0.1+ struct timeval tv{1, 0};+ ::setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));+ ::setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));+ if (::connect(s, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin)) == 0) {+ const char req[] = "GET /loadpayload:/data/pldmgr/payloads/patch_test/patch_test.elf HTTP/1.1\r\nHost: 127.0.0.1:8084\r\nConnection: close\r\n\r\n";+ ::send(s, req, sizeof(req) - 1, 0);+ char buf[256];+ ::recv(s, buf, sizeof(buf), 0);+ XC_LOGI("trophy ps5: SceShellCore patch & unjail payload triggered via 127.0.0.1:8084 (pid=%d)", myPid);+ }+ ::close(s);+ ::usleep(30000); // 30ms settle for kernel credential update+}++// The SceShellCore patch/unjail payload runs asynchronously: it only unjails+// our eboot process AFTER it finishes its own work (the slow heap scan runs+// first). Until then our process still sees the sandbox root, so writes to+// /system_data and /user fail with ENOENT (errno=2) and the whole trophy pack+// deploy is silently lost. Block until the privileged filesystem is actually+// visible (unjail took effect) or we time out. Probe a root-only path with a+// non-destructive stat() as the unjail indicator.+bool waitForUnjail(int timeoutMs) {+ struct stat st{};+ for (int waited = 0; waited <= timeoutMs; waited += 100) {+ if (::stat("/system_data/priv/mms/app.db", &st) == 0) {+ if (waited > 0) XC_LOGI("trophy ps5: unjail confirmed after %d ms", waited);+ return true;+ }+ ::usleep(100000); // 100ms+ }+ XC_LOGW("trophy ps5: unjail NOT confirmed after %d ms; file deploy will fail with ENOENT", timeoutMs);+ return false;+}++} // namespace++class TrophyBackendPS5 : public ITrophyBackend {+public:+ TrophyBackendPS5() = default;+ ~TrophyBackendPS5() override {+ cleanupContext();+ }++ bool init(uint32_t userId) override {+ std::lock_guard<std::mutex> lock(mutex_);+ if (initialized_) return true;++ if (userId != 0) {+ userId_ = userId;+ } else {+ int32_t uid = -1;+ int rc = sceUserServiceGetInitialUser(&uid);+ if (rc != 0 || uid <= 0) {+ sceUserServiceInitialize(nullptr);+ rc = sceUserServiceGetInitialUser(&uid);+ }+ if (rc == 0 && uid > 0) {+ userId_ = static_cast<uint32_t>(uid);+ } else {+ userId_ = 0x1ea2f4da; // Default to devRafaelNGP+ }+ }++ char userName[64] = {0};+ sceUserServiceGetUserName(static_cast<int32_t>(userId_), userName, sizeof(userName));+ XC_LOGI("trophy ps5: initialized for user 0x%08x (%s)", userId_, userName[0] ? userName : "devRafaelNGP");++ // Ensure SceShellCore debug unlock patch is active+ triggerSceShellCorePatch();++ // Load libSceNpTrophy2 module+ loadNpTrophyModule();+ initialized_ = true;+ return true;+ }++ bool registerTitle(const TitleTrophySet& set) override {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!initialized_) init(0);++ if (currentNpCommId_ != set.npCommId || context_ < 0) {+ cleanupContext();+ currentNpCommId_ = set.npCommId;++ // Load existing unlocked trophies from disk TRPTITLE.DAT into unlockedTrophies_+ char dataPath[256];+ snprintf(dataPath, sizeof(dataPath), "/user/home/%08x/trophy2/nobackup/data/%s/TRPTITLE.DAT",+ userId_, set.npCommId.c_str());+ int fd = ::open(dataPath, O_RDONLY);+ if (fd >= 0) {+ struct stat st{};+ if (::fstat(fd, &st) == 0 && st.st_size > 0) {+ std::vector<uint8_t> diskBuf(st.st_size);+ ssize_t n = ::read(fd, diskBuf.data(), diskBuf.size());+ if (n > 0) {+ std::map<uint32_t, ExistingTrophyRecord> existingTrophies;+ if (parseTrpTitleDat(diskBuf.data(), static_cast<size_t>(n), existingTrophies)) {+ for (const auto& [tid, rec] : existingTrophies) {+ if (rec.state == 1) {+ unlockedTrophies_[set.npCommId].insert(tid);+ }+ }+ XC_LOGI("trophy ps5: loaded %zu existing unlocked trophies from %s",+ unlockedTrophies_[set.npCommId].size(), dataPath);+ }+ }+ }+ ::close(fd);+ }++ // Generate UCP package and npbind.dat, deploy to system folders.+ // Wait for the async unjail first, or every write below hits ENOENT.+ waitForUnjail(8000);+ deployTrophyPack(set, userId_);+ std::vector<uint8_t> dummyUcp;+ buildUcp(set, dummyUcp, &ucpSha1_);++ int rc = sceNpTrophy2CreateContext(&context_, static_cast<int32_t>(userId_), 1, 0);+ XC_LOGI("trophy ps5: sceNpTrophy2CreateContext(user=0x%08x, serviceLabel=1) -> rc=0x%08x, context=%d",+ userId_, static_cast<unsigned>(rc), context_);+ if (rc == 0 && handle_ < 0) {+ rc = sceNpTrophy2CreateHandle(&handle_);+ XC_LOGI("trophy ps5: sceNpTrophy2CreateHandle -> rc=0x%08x, handle=%d",+ static_cast<unsigned>(rc), handle_);+ }+ if (context_ >= 0 && handle_ >= 0) {+ rc = sceNpTrophy2RegisterContext(context_, handle_, 0);+ XC_LOGI("trophy ps5: sceNpTrophy2RegisterContext(ctx=%d, hdl=%d) -> rc=0x%08x",+ context_, handle_, static_cast<unsigned>(rc));+ ::usleep(250000); // 250ms settle for SceShellCore async pack load+ }+ }++ registeredTitles_[set.npCommId] = set;+ XC_LOGI("trophy ps5: title %s (%s, %d trophies) registered",+ set.titleName.c_str(), set.npCommId.c_str(), static_cast<int>(set.items.size()));+ return true;+ }++ bool unlockTrophy(const std::string& npCommId, int trophyId, TrophyGrade grade, const std::string& trophyName) override {+ std::lock_guard<std::mutex> lock(mutex_);+ if (sessionUnlockedTrophies_[npCommId].count(trophyId) > 0) {+ return true;+ }++ // Sony SceShellCore automatically awards Platinum upon completing all trophies in the pack.+ if (grade == TrophyGrade::Platinum || trophyId == kPlatinumTrophyId) {+ XC_LOGI("trophy ps5: Platinum trophy awarded for %s (%s) upon 100%% completion",+ npCommId.c_str(), trophyName.c_str());+ sessionUnlockedTrophies_[npCommId].insert(trophyId);+ unlockedTrophies_[npCommId].insert(trophyId);+ return true;+ }++ int rc = -1;+ if (context_ >= 0 && handle_ >= 0) {+ SceNpTrophy2DebugUnlockParam param{};+ param.mode = 2; // Mode 2: Specific trophyId+ param.trophyId = trophyId; // Exact 1-based trophy id++ for (int retry = 0; retry < 15; ++retry) {+ rc = sceNpTrophy2SystemDebugUnlockTrophy(handle_, context_, ¶m);+ if (rc == 0 || static_cast<uint32_t>(rc) == 0x80553998) {+ rc = 0; // 0x80553998 = ALREADY_UNLOCKED (success)+ break;+ }+ if (static_cast<uint32_t>(rc) == 0x80553909 && retry < 14) {+ XC_LOGI("trophy ps5: context %d not ready yet (0x80553909), retrying in 50ms (%d/15)",+ context_, retry + 1);+ ::usleep(50000);+ continue;+ }+ break;+ }+ XC_LOGI("trophy ps5: sceNpTrophy2SystemDebugUnlockTrophy(%s, trophyId=%d, grade=%s) -> rc=0x%08x",+ npCommId.c_str(), trophyId, gradeToString(grade), static_cast<unsigned>(rc));+ } else {+ XC_LOGW("trophy ps5: context or handle invalid (ctx=%d, hdl=%d)", context_, handle_);+ }++ if (rc != 0) {+ XC_LOGW("trophy ps5: sceNpTrophy2SystemDebugUnlockTrophy failed for %s trophyId=%d -> rc=0x%08x",+ npCommId.c_str(), trophyId, static_cast<unsigned>(rc));+ return false;+ }++ sessionUnlockedTrophies_[npCommId].insert(trophyId);+ unlockedTrophies_[npCommId].insert(trophyId);+ ::usleep(40000); // 40ms pacing+ return true;+ }++ void flush() override {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!currentNpCommId_.empty()) {+ auto it = registeredTitles_.find(currentNpCommId_);+ if (it != registeredTitles_.end()) {+ TitleTrophySet updatedSet = it->second;+ const auto& unlockedSet = unlockedTrophies_[currentNpCommId_];+ int unlockedCount = 0;+ for (auto& item : updatedSet.items) {+ if (unlockedSet.count(item.trophyId) > 0) {+ item.unlocked = true;+ unlockedCount++;+ }+ }+ updatedSet.unlockedCount = unlockedCount;+ std::vector<uint8_t> datBytes;+ if (buildTrpTitleDat(updatedSet, userId_, datBytes, ucpSha1_.empty() ? nullptr : ucpSha1_.data())) {+ char path[256];+ snprintf(path, sizeof(path), "/user/home/%08x/trophy2/nobackup/data/%s/TRPTITLE.DAT",+ userId_, currentNpCommId_.c_str());+ int fd = ::open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);+ if (fd >= 0) {+ ::write(fd, datBytes.data(), datBytes.size());+ ::close(fd);+ ::chmod(path, 0666);+ ::sync();+ XC_LOGI("trophy ps5: flushed updated TRPTITLE.DAT to %s (%zu bytes, %d unlocked)",+ path, datBytes.size(), unlockedCount);+ }+ }+ }+ }+ cleanupContext();+ currentNpCommId_.clear();+ // NOTE: destroying the context does NOT commit anything to the OS trophy+ // index. TRPTITLE.DAT is written above, but the service-side durable+ // publish (what the system Trophy collection reads) is NOT confirmed here.+ XC_LOGI("trophy ps5: context destroyed; TRPTITLE.DAT written (service-side durable publish NOT confirmed)");+ }++ bool isTrophyUnlocked(const std::string& npCommId, int trophyId) override {+ std::lock_guard<std::mutex> lock(mutex_);+ auto it = unlockedTrophies_.find(npCommId);+ if (it != unlockedTrophies_.end() && it->second.count(trophyId) > 0) {+ return true;+ }+ return false;+ }++ std::string name() const override {+ return "PlayStation 5 Native (libSceNpTrophy2)";+ }++private:+ void loadNpTrophyModule() {+ int res = 0;+ int mod = sceKernelLoadStartModule(systemLib("libSceNpTrophy2.sprx").c_str(), 0, nullptr, 0, nullptr, &res);+ if (mod < 0) {+ mod = sceKernelLoadStartModule("libSceNpTrophy2.sprx", 0, nullptr, 0, nullptr, &res);+ }+ XC_LOGI("trophy ps5: load libSceNpTrophy2.sprx -> 0x%08x (res=%d)", static_cast<unsigned>(mod), res);+ }++ void cleanupContext() {+ if (handle_ >= 0) {+ sceNpTrophy2DestroyHandle(handle_);+ handle_ = -1;+ }+ if (context_ >= 0) {+ sceNpTrophy2DestroyContext(context_);+ context_ = -1;+ }+ sessionUnlockedTrophies_.clear();+ }++ bool initialized_ = false;+ uint32_t userId_ = 0x1ea2f4da;+ int32_t context_ = -1;+ int32_t handle_ = -1;+ std::string currentNpCommId_;+ std::vector<uint8_t> ucpSha1_;+ std::mutex mutex_;+ std::map<std::string, TitleTrophySet> registeredTitles_;+ std::map<std::string, std::set<int>> unlockedTrophies_;+ std::map<std::string, std::set<int>> sessionUnlockedTrophies_;+};++// --- PSBox NATIVE self-test -------------------------------------------------+// Minimal probe of the user's idea: attribute a trophy set to the RUNNING+// process's own title (PSBox = PPSA99810) and unlock via the NORMAL v1 flow+// (sceNpTrophyUnlockTrophy), exactly like a locally-installed game does — which+// already surfaces natively on this console. No system-service patching here:+// just privileged file placement (unjail) + the intended trophy SDK. Writes are+// ADDITIVE (a new NPWR + a trophy2 subdir); it never overwrites PSBox's own+// param.json/metadata. Verify by looking at the console profile AND by dumping+// the collection cache afterwards.+void runPsboxNativeSelfTest() {+ const char* kNpComm = "NPWR90210_00"; // dedicated test comm id for PSBox+ const char* kTitle = "PPSA99810"; // PSBox's own (running) title id++ TitleTrophySet set;+ set.sonyTitleId = kTitle;+ set.titleName = "PSBox Cloud Gaming";+ set.npCommId = kNpComm;+ for (int i = 1; i <= 4; ++i) {+ TrophyDef d;+ d.trophyId = i;+ d.name = "PSBox Native Test " + std::to_string(i);+ d.description = "Native v1 trophy self-test";+ d.grade = TrophyGrade::Bronze;+ d.gamerscore = 15;+ d.unlocked = false;+ set.items.push_back(d);+ }+ set.totalCount = 4;++ int32_t uid = 0x1ea2f4da;+ { int32_t u = -1; if (sceUserServiceGetInitialUser(&u) == 0 && u > 0) uid = static_cast<uint32_t>(u); }+ XC_LOGI("psbox selftest: user=0x%08x, title=%s, npComm=%s", uid, kTitle, kNpComm);++ // Load the Trophy2 module FIRST, while still sandboxed — the "/<word>/common/+ // lib/" path only resolves before the unjail changes our fs root. This binds+ // the sceNpTrophy2* imports so the calls below are safe.+ int res = 0;+ int mod = sceKernelLoadStartModule(systemLib("libSceNpTrophy2.sprx").c_str(), 0, nullptr, 0, nullptr, &res);+ if (mod < 0) mod = sceKernelLoadStartModule("libSceNpTrophy2.sprx", 0, nullptr, 0, nullptr, &res);+ XC_LOGI("psbox selftest: load libSceNpTrophy2.sprx -> 0x%08x (res=%d)", static_cast<unsigned>(mod), res);++ // Need root to write under /system_data and /user/trophy2.+ triggerSceShellCorePatch();+ waitForUnjail(8000);++ auto mkpath = [](const char* p) { ::mkdir(p, 0777); ::chmod(p, 0777); };+ auto writeBuf = [](const std::string& path, const std::vector<uint8_t>& buf) {+ int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);+ if (fd < 0) { XC_LOGW("psbox selftest: open fail %s", path.c_str()); return false; }+ ssize_t n = ::write(fd, buf.data(), buf.size());+ ::close(fd); ::chmod(path.c_str(), 0666); ::sync();+ XC_LOGI("psbox selftest: wrote %s (%zd/%zu bytes)", path.c_str(), n, buf.size());+ return n == static_cast<ssize_t>(buf.size());+ };++ // Build the trophy artifacts (NOT the title's param.json — surgical).+ std::vector<uint8_t> ucp, sha1, npbind, dat;+ buildUcp(set, ucp, &sha1);+ buildNpBind(kNpComm, npbind);+ buildTrpTitleDat(set, uid, dat, sha1.empty() ? nullptr : sha1.data());++ // (a) appmeta trophy2 pack for PSBox's own title (additive subdir).+ mkpath("/system_data/priv/appmeta/PPSA99810/trophy2");+ writeBuf("/system_data/priv/appmeta/PPSA99810/trophy2/trophy00.ucp", ucp);+ writeBuf("/system_data/priv/appmeta/PPSA99810/trophy2/npbind.dat", npbind);+ // (b) shared conf UCP (per-NPWR).+ mkpath("/user/trophy2/nobackup/conf/NPWR90210_00");+ writeBuf("/user/trophy2/nobackup/conf/NPWR90210_00/TROPHY.UCP", ucp);+ // (c) per-user data.+ char dataDir[256];+ snprintf(dataDir, sizeof(dataDir), "/user/home/%08x/trophy2/nobackup/data/NPWR90210_00", uid);+ mkpath(dataDir);+ writeBuf(std::string(dataDir) + "/TRPTITLE.DAT", dat);++ // NORMAL Trophy2 flow (like a real game): CreateContext -> CreateHandle ->+ // RegisterContext -> UnlockTrophy (NOT the debug unlock). serviceLabel=1.+ int32_t ctx = -1, handle = -1, plat = -1;+ int rc = sceNpTrophy2CreateContext(&ctx, static_cast<int32_t>(uid), 1, 0);+ XC_LOGI("psbox selftest: CreateContext -> rc=0x%08x ctx=%d", static_cast<unsigned>(rc), ctx);+ rc = sceNpTrophy2CreateHandle(&handle);+ XC_LOGI("psbox selftest: CreateHandle -> rc=0x%08x handle=%d", static_cast<unsigned>(rc), handle);+ rc = sceNpTrophy2RegisterContext(ctx, handle, 0);+ XC_LOGI("psbox selftest: RegisterContext -> rc=0x%08x", static_cast<unsigned>(rc));+ ::usleep(250000);+ for (int id = 1; id <= 2; ++id) {+ rc = sceNpTrophy2UnlockTrophy(ctx, handle, id, &plat);+ XC_LOGI("psbox selftest: sceNpTrophy2UnlockTrophy(id=%d) -> rc=0x%08x plat=%d", id, static_cast<unsigned>(rc), plat);+ ::usleep(300000);+ }+ if (handle >= 0) sceNpTrophy2DestroyHandle(handle);+ if (ctx >= 0) sceNpTrophy2DestroyContext(ctx);+ XC_LOGI("psbox selftest: done (check console profile for 'PSBox Cloud Gaming' trophies)");+}++ITrophyBackend* createPlatformTrophyBackend() {+ return new TrophyBackendPS5();+}++} // namespace xc::trophydiff --git a/src/trophy/icon_arrays.inc b/src/trophy/icon_arrays.incnew file mode 100644index 0000000..0224a96--- /dev/null+++ b/src/trophy/icon_arrays.inc@@ -0,0 +1,414 @@+const uint8_t kDefaultIconPng[2937] = {+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,+ 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x08, 0x06, 0x00, 0x00, 0x00, 0xf4, 0x78, 0xd4,+ 0xfa, 0x00, 0x00, 0x0b, 0x40, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0xed, 0xdd, 0xbb, 0x51, 0x23,+ 0x5b, 0x14, 0x86, 0xd1, 0x1f, 0x95, 0x12, 0xa0, 0x0a, 0xaa, 0xc0, 0x84, 0x18, 0x88, 0x80, 0x08,+ 0x48, 0x48, 0x96, 0x12, 0x22, 0x02, 0x22, 0x20, 0x06, 0xb9, 0x32, 0x64, 0x10, 0x02, 0x58, 0xe3,+ 0x0d, 0x0f, 0xa9, 0xfb, 0x74, 0x9f, 0xc7, 0x5a, 0xe6, 0x35, 0x66, 0xee, 0xa8, 0x38, 0xec, 0xaf,+ 0x77, 0xb7, 0xa4, 0xab, 0x9b, 0xbb, 0x87, 0xcf, 0x00, 0x00, 0x43, 0xd9, 0x78, 0x09, 0x00, 0x40,+ 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00,+ 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x80, 0xdf,+ 0x6c, 0xa7, 0xfe, 0x01, 0x2f, 0xbb, 0x77, 0xaf, 0x22, 0x00, 0xac, 0xe0, 0x75, 0xff, 0x64, 0x03,+ 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20,+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xc4, 0xe7, 0x00, 0x64, 0xc1, 0xf7, 0x28, 0x02, 0xc0, 0xc8,+ 0x4a, 0x7e, 0xd6, 0x8e, 0x0d, 0x00, 0x00, 0xc4, 0x2d, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02,+ 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,+ 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00,+ 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00,+ 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01,+ 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80,+ 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00,+ 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00,+ 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00,+ 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40,+ 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x20, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00,+ 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00,+ 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20,+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,+ 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00,+ 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00,+ 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10,+ 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x01, 0xe0, 0x25, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00,+ 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04,+ 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,+ 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00,+ 0x80, 0x64, 0xeb, 0x25, 0x80, 0xbe, 0x9c, 0x8e, 0x87, 0x62, 0x7f, 0xf6, 0xed, 0xfd, 0xa3, 0x17,+ 0x18, 0x04, 0x00, 0xd0, 0xdb, 0x80, 0x9f, 0xfa, 0x77, 0x0b, 0x04, 0x10, 0x00, 0x40, 0xc3, 0x83,+ 0x7e, 0xee, 0xff, 0x67, 0x61, 0x00, 0x02, 0x00, 0xe8, 0x68, 0xe0, 0x5f, 0xfa, 0x6f, 0x13, 0x04,+ 0x20, 0x00, 0xc0, 0xc0, 0xf7, 0x6f, 0x17, 0x04, 0x20, 0x00, 0xc0, 0xc0, 0xf7, 0xda, 0x08, 0x02,+ 0x10, 0x00, 0x60, 0xe8, 0x9f, 0xed, 0x7a, 0xf7, 0x5c, 0xec, 0xcf, 0xfe, 0xd8, 0xbf, 0x2d, 0xfe,+ 0xba, 0x89, 0x01, 0x10, 0x00, 0x60, 0xe8, 0x17, 0x1e, 0xf0, 0x53, 0xff, 0xee, 0x12, 0x81, 0x20,+ 0x06, 0x40, 0x00, 0xc0, 0x70, 0x83, 0x7f, 0xcd, 0x61, 0x3f, 0xd7, 0xff, 0xef, 0x9c, 0x51, 0xf0,+ 0xef, 0x35, 0x16, 0x02, 0x20, 0x00, 0xa0, 0x9b, 0xa1, 0xdf, 0xda, 0xb0, 0x5f, 0x33, 0x0a, 0x6c,+ 0x05, 0x40, 0x00, 0x40, 0xd3, 0x83, 0xbf, 0xd7, 0xa1, 0x7f, 0xce, 0xbf, 0x7b, 0xae, 0x18, 0x10,+ 0x02, 0x20, 0x00, 0xa0, 0xda, 0xa1, 0x3f, 0xea, 0xc0, 0x3f, 0xe7, 0x35, 0xb9, 0x34, 0x08, 0x6c,+ 0x05, 0x40, 0x00, 0x40, 0x55, 0x83, 0xdf, 0xd0, 0x5f, 0x7e, 0x3b, 0x60, 0x2b, 0x00, 0x02, 0x00,+ 0x56, 0x19, 0xfc, 0x86, 0x7e, 0x1d, 0x31, 0x20, 0x04, 0x40, 0x00, 0x80, 0xc1, 0xdf, 0x49, 0x0c,+ 0x08, 0x01, 0x10, 0x00, 0x50, 0xc5, 0xe0, 0x37, 0xf4, 0xdb, 0xd9, 0x0a, 0x08, 0x01, 0x10, 0x00,+ 0x30, 0x79, 0xf8, 0x1b, 0xfc, 0xed, 0x6e, 0x05, 0x4e, 0xc7, 0x83, 0x08, 0x40, 0x00, 0x78, 0x09,+ 0x30, 0xf8, 0x0d, 0xfe, 0x11, 0x43, 0xc0, 0x36, 0x00, 0x01, 0x00, 0x06, 0xbf, 0xa1, 0x3f, 0xf0,+ 0xed, 0x01, 0x21, 0x80, 0x00, 0x00, 0xc3, 0xdf, 0xe0, 0x1f, 0x78, 0x2b, 0xe0, 0xb6, 0x00, 0xa3,+ 0xd9, 0x78, 0x09, 0x18, 0x69, 0xf0, 0x1b, 0xfe, 0x3e, 0x68, 0x68, 0xce, 0x9f, 0x11, 0xb0, 0x01,+ 0x00, 0xeb, 0x7e, 0x3a, 0xdb, 0x06, 0x24, 0x6e, 0x0b, 0x20, 0x00, 0xc0, 0xba, 0x1f, 0xb7, 0x05,+ 0x40, 0x00, 0x40, 0x5f, 0xc3, 0xdf, 0xe0, 0x17, 0x02, 0x22, 0x80, 0x78, 0x06, 0x00, 0xc6, 0xba,+ 0xd7, 0x6f, 0xf8, 0x0b, 0x01, 0xcf, 0x06, 0x60, 0x03, 0x00, 0xae, 0xfa, 0xb1, 0x0d, 0xb0, 0x0d,+ 0xc0, 0x06, 0x00, 0x0c, 0x7f, 0x6c, 0x03, 0xca, 0x7c, 0x2d, 0x34, 0xd8, 0x00, 0x80, 0xc1, 0x4f,+ 0x83, 0xdb, 0x00, 0xef, 0x12, 0xc0, 0x06, 0x00, 0x0c, 0x7f, 0x6c, 0x03, 0xc0, 0x06, 0x00, 0x6a,+ 0x1b, 0xfe, 0x06, 0x3f, 0x4b, 0x6c, 0x03, 0x6c, 0x02, 0xb0, 0x01, 0x00, 0xc3, 0x9f, 0x01, 0xb7,+ 0x01, 0x36, 0x01, 0x08, 0x00, 0xa8, 0xe4, 0x2d, 0x7e, 0x86, 0x3f, 0x6b, 0x44, 0x80, 0x10, 0x20,+ 0x6e, 0x01, 0x80, 0xab, 0x7e, 0xdc, 0x12, 0x00, 0x1b, 0x00, 0x30, 0xfc, 0x71, 0x4b, 0x00, 0x04,+ 0x00, 0x18, 0xfe, 0x88, 0x00, 0x10, 0x00, 0x60, 0xf8, 0x23, 0x02, 0x20, 0x9e, 0x01, 0x80, 0x3f,+ 0xfd, 0xf2, 0x34, 0xf8, 0x69, 0xe1, 0xb9, 0x00, 0xcf, 0x04, 0x60, 0x03, 0x00, 0x86, 0x3f, 0x83,+ 0x6e, 0x03, 0x6c, 0x02, 0x10, 0x00, 0x60, 0xf8, 0x23, 0x02, 0x40, 0x00, 0x80, 0xe1, 0x8f, 0x08,+ 0x00, 0x01, 0x80, 0xe1, 0x6f, 0xf8, 0x23, 0x02, 0x40, 0x00, 0x60, 0xf8, 0x1b, 0xfe, 0x88, 0x00,+ 0x10, 0x00, 0x18, 0xfe, 0x20, 0x02, 0x40, 0x00, 0x60, 0xf8, 0x83, 0x08, 0x00, 0x01, 0x80, 0xe1,+ 0x0f, 0x22, 0x00, 0x04, 0x00, 0x23, 0x7c, 0xca, 0x1a, 0xf8, 0x79, 0x06, 0x01, 0x40, 0x47, 0x57,+ 0xff, 0x7e, 0x59, 0x32, 0x5a, 0x04, 0xd8, 0x02, 0x20, 0x00, 0x30, 0xfc, 0x0d, 0x7f, 0x44, 0x00,+ 0x08, 0x00, 0xc6, 0xfc, 0x72, 0x1f, 0x70, 0x3e, 0x40, 0x00, 0xe0, 0xa1, 0x3f, 0xf0, 0x50, 0x20,+ 0x08, 0x00, 0x3c, 0x24, 0x05, 0x7e, 0xde, 0x41, 0x00, 0xe0, 0xbe, 0x3f, 0x78, 0x1e, 0x00, 0x04,+ 0x00, 0x86, 0x3f, 0x88, 0x00, 0x10, 0x00, 0x78, 0xa8, 0x09, 0x9c, 0x1f, 0x10, 0x00, 0xb8, 0x0f,+ 0x0a, 0xce, 0x01, 0x08, 0x00, 0xac, 0xfe, 0xc1, 0xad, 0x00, 0x04, 0x00, 0x18, 0xfe, 0x20, 0x02,+ 0x10, 0x00, 0xe0, 0xbe, 0x25, 0x38, 0x57, 0x08, 0x00, 0x70, 0xbf, 0x13, 0x9c, 0x0f, 0x04, 0x00,+ 0x58, 0xfd, 0x83, 0x5b, 0x01, 0x08, 0x00, 0x00, 0x40, 0x00, 0xe0, 0xea, 0xdf, 0xd5, 0x3f, 0xd8,+ 0x02, 0x20, 0x00, 0x30, 0xfc, 0x0d, 0x7f, 0x10, 0x01, 0x08, 0x00, 0x00, 0x40, 0x00, 0xe0, 0xea,+ 0x1f, 0xb0, 0x05, 0x40, 0x00, 0xe0, 0x2d, 0x4d, 0x80, 0x73, 0x84, 0x00, 0xc0, 0x87, 0x93, 0x00,+ 0xce, 0x1f, 0x02, 0x00, 0xab, 0x7f, 0xb0, 0x05, 0x10, 0x01, 0x08, 0x00, 0x00, 0x40, 0x00, 0xe0,+ 0xea, 0x1f, 0x6c, 0x01, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x57, 0xff, 0x60, 0x0b, 0x00, 0x02,+ 0x00, 0x6f, 0x57, 0x02, 0xe7, 0x0c, 0x01, 0x00, 0xde, 0x76, 0x04, 0xce, 0x27, 0x02, 0x00, 0x5c,+ 0x95, 0x80, 0xf3, 0x86, 0x00, 0x00, 0x57, 0x17, 0xe0, 0x9c, 0x22, 0x00, 0x00, 0x00, 0x01, 0x00,+ 0xd6, 0x91, 0xe0, 0xdc, 0x21, 0x00, 0x88, 0xb5, 0x22, 0xe0, 0xbc, 0x22, 0x00, 0x70, 0x15, 0x02,+ 0x38, 0x7f, 0x08, 0x00, 0x5c, 0x4d, 0x00, 0xce, 0x2d, 0x02, 0x00, 0x57, 0x1f, 0x80, 0x73, 0x88,+ 0x00, 0x00, 0x00, 0x04, 0x00, 0xb1, 0x46, 0x04, 0x9c, 0x5f, 0x04, 0x00, 0xb1, 0x76, 0x04, 0x9c,+ 0x47, 0x04, 0x00, 0xae, 0x1e, 0x00, 0xe7, 0x18, 0x01, 0x80, 0xab, 0x0d, 0x70, 0x2e, 0x41, 0x00,+ 0x00, 0x00, 0x02, 0x80, 0x58, 0x1b, 0x82, 0xf3, 0x0c, 0x02, 0x80, 0x58, 0x33, 0x82, 0xf3, 0x89,+ 0x00, 0x00, 0x00, 0x04, 0x00, 0xb1, 0x2e, 0x04, 0x9c, 0x6b, 0x04, 0x00, 0x24, 0xd6, 0x8b, 0xe0,+ 0x9c, 0x22, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0xe2, 0x3e, 0x21, 0xe0, 0x7c, 0x23,+ 0x00, 0x88, 0xfb, 0x8a, 0x80, 0xf3, 0x8a, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x48,+ 0x6d, 0xf7, 0x07, 0xad, 0x13, 0x21, 0xdd, 0xdc, 0x06, 0xf0, 0x1c, 0x00, 0x02, 0x00, 0x00, 0x04,+ 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x40, 0xbc, 0x3f, 0x18, 0x70, 0xde, 0x11, 0x00, 0xc4,+ 0xfb, 0x89, 0x01, 0xe7, 0x17, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02,+ 0x00, 0x00, 0x10, 0x00, 0xc4, 0x27, 0x00, 0x02, 0xf1, 0x89, 0x80, 0x08, 0x00, 0x00, 0x40, 0x00,+ 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20,+ 0x00, 0x00, 0x00, 0x01, 0x40, 0xe2, 0x33, 0x00, 0x20, 0x3e, 0x0b, 0x00, 0x01, 0x00, 0x00, 0x08,+ 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,+ 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00,+ 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00,+ 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04,+ 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x40, 0x4b, 0x6e, 0xef, 0x1f, 0xff, 0xfb, 0xdf, 0x3f,+ 0xf6, 0x6f, 0x5e, 0x1c, 0xe8, 0xc4, 0x77, 0xe7, 0xf9, 0xbb, 0xf3, 0x8f, 0x00, 0x00, 0x00, 0x04,+ 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,+ 0x02, 0x00, 0x00, 0x10, 0x00, 0xc4, 0x67, 0x01, 0x00, 0xf1, 0x19, 0x00, 0x08, 0x00, 0x00, 0x40,+ 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x20, 0x4b, 0x3c, 0x40, 0x04,+ 0x38, 0xbf, 0x08, 0x00, 0xd2, 0xef, 0x3b, 0x01, 0x00, 0xe7, 0x1d, 0x01, 0x00, 0x00, 0x08, 0x00,+ 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x80, 0xf8, 0x44, 0x40, 0x20, 0x3e, 0x01, 0x10, 0x01, 0x00,+ 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x10, 0xef, 0x27, 0x06, 0x9c, 0x57, 0x04, 0x00, 0xf1, 0xfe,+ 0x60, 0xc0, 0xf9, 0x46, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0xc4, 0x7d, 0x45, 0xc0,+ 0x39, 0x45, 0x00, 0x10, 0xf7, 0x09, 0x01, 0xe7, 0x1a, 0x01, 0x00, 0x00, 0x08, 0x00, 0x62, 0xbd,+ 0x08, 0xce, 0x27, 0x02, 0x00, 0x62, 0x5d, 0x08, 0xce, 0x33, 0x02, 0x00, 0x00, 0x10, 0x00, 0x10,+ 0x6b, 0x46, 0x70, 0x2e, 0x11, 0x00, 0xc4, 0xda, 0x10, 0x70, 0x8e, 0x11, 0x00, 0xb8, 0xda, 0x00,+ 0x9c, 0x47, 0x04, 0x00, 0xae, 0x1e, 0x00, 0xe7, 0x17, 0x01, 0x00, 0x00, 0x08, 0x00, 0x62, 0xed,+ 0x08, 0x38, 0x87, 0x08, 0x00, 0x62, 0x8d, 0x08, 0x38, 0xb7, 0x08, 0x00, 0x5c, 0x7d, 0x00, 0xce,+ 0x1f, 0x02, 0x00, 0x57, 0x13, 0x80, 0xf3, 0x8a, 0x00, 0xc0, 0x55, 0x08, 0xe0, 0xdc, 0x21, 0x00,+ 0x00, 0x00, 0x01, 0x40, 0xac, 0x15, 0xc1, 0x39, 0x75, 0x4e, 0x11, 0x00, 0xc4, 0x3a, 0x12, 0x9c,+ 0x37, 0x10, 0x00, 0xb8, 0xba, 0x00, 0xe7, 0x13, 0x04, 0x00, 0xae, 0x4a, 0xc0, 0x39, 0x43, 0x00,+ 0xc0, 0x3c, 0x57, 0x19, 0x7e, 0x39, 0xc1, 0x3a, 0xc3, 0xdf, 0xd5, 0x3f, 0x02, 0x00, 0x00, 0x10,+ 0x00, 0xd8, 0x02, 0x80, 0xab, 0x7f, 0x10, 0x00, 0x00, 0x80, 0x00, 0xc0, 0x16, 0x00, 0x5c, 0xfd,+ 0x23, 0x00, 0xc0, 0xdb, 0x8e, 0xc0, 0xf9, 0x43, 0x00, 0x80, 0xb7, 0x2b, 0x81, 0x73, 0x84, 0x00,+ 0x00, 0xb7, 0x02, 0xc0, 0xea, 0x1f, 0x01, 0x00, 0x00, 0x08, 0x00, 0x6c, 0x01, 0x6c, 0x01, 0xc0,+ 0xd5, 0x3f, 0x02, 0x00, 0x11, 0x20, 0x02, 0xc0, 0xf0, 0x47, 0x00, 0x00, 0x00, 0x02, 0x00, 0x5b,+ 0x00, 0xc0, 0xd5, 0x3f, 0x02, 0x00, 0xbf, 0xdc, 0x00, 0xe7, 0x03, 0x01, 0x80, 0x0f, 0x27, 0x01,+ 0x9c, 0x2b, 0x04, 0x00, 0x6e, 0x05, 0x80, 0xd5, 0xbf, 0x17, 0x08, 0x01, 0x80, 0x08, 0x00, 0xc3,+ 0x1f, 0x04, 0x00, 0xee, 0x77, 0x82, 0x73, 0x00, 0x02, 0x00, 0xf7, 0x2d, 0xc1, 0xf9, 0x01, 0x01,+ 0x80, 0x5b, 0x01, 0x60, 0xf5, 0x0f, 0x02, 0x00, 0x11, 0x00, 0x86, 0x3f, 0x08, 0x00, 0xdc, 0x07,+ 0x05, 0x3f, 0xef, 0x08, 0x00, 0x58, 0xfb, 0x7e, 0xa6, 0x5f, 0x8a, 0x18, 0xfe, 0xae, 0xfe, 0x11,+ 0x00, 0x78, 0xa8, 0x09, 0x9c, 0x0f, 0x10, 0x00, 0x78, 0x1e, 0x00, 0xdc, 0xf7, 0x07, 0x01, 0x80,+ 0x08, 0x00, 0xc3, 0x1f, 0x04, 0x00, 0x1e, 0x92, 0x02, 0x3f, 0xcf, 0x20, 0x00, 0xf0, 0x50, 0x20,+ 0x78, 0xe8, 0x0f, 0x04, 0x00, 0x22, 0x00, 0x0c, 0x7f, 0x10, 0x00, 0x88, 0x00, 0x30, 0xfc, 0x41,+ 0x00, 0x20, 0x02, 0xc0, 0xf0, 0x47, 0x00, 0x80, 0x08, 0x00, 0xc3, 0x1f, 0x01, 0x00, 0x22, 0x00,+ 0x0c, 0x7f, 0x04, 0x00, 0x88, 0x00, 0x30, 0xfc, 0x11, 0x00, 0x20, 0x02, 0xc0, 0xf0, 0xa7, 0x55,+ 0x5b, 0x2f, 0x01, 0x35, 0x47, 0xc0, 0xe9, 0x78, 0xf8, 0xf5, 0x97, 0xee, 0xf5, 0xee, 0xd9, 0x8b,+ 0x45, 0xb5, 0x1f, 0xf0, 0x63, 0xf8, 0x63, 0x03, 0x00, 0x85, 0xbe, 0x1c, 0xc5, 0x36, 0x00, 0xc3,+ 0x1f, 0x04, 0x00, 0x22, 0x00, 0x0c, 0x7f, 0x10, 0x00, 0x88, 0x00, 0x30, 0xfc, 0x21, 0x9e, 0x01,+ 0xa0, 0xe7, 0x67, 0x02, 0x3c, 0x17, 0x40, 0x0d, 0x5f, 0xe8, 0x63, 0xf8, 0x63, 0x03, 0x00, 0x85,+ 0x22, 0xc0, 0x36, 0x80, 0x5a, 0xaf, 0xfa, 0x0d, 0x7f, 0x04, 0x00, 0xb8, 0x25, 0x80, 0x95, 0x3f,+ 0xc4, 0x2d, 0x00, 0x70, 0x4b, 0x00, 0x2b, 0x7f, 0xb0, 0x01, 0x80, 0x25, 0x37, 0x01, 0xb6, 0x01,+ 0x18, 0xfe, 0x60, 0x03, 0x40, 0xc7, 0x11, 0x60, 0x1b, 0x80, 0xc1, 0x0f, 0x36, 0x00, 0xd8, 0x06,+ 0xd8, 0x06, 0x60, 0xf8, 0x83, 0x0d, 0x00, 0x9e, 0x0b, 0xb0, 0x0d, 0x60, 0x7a, 0x10, 0x1a, 0xfe,+ 0xd8, 0x00, 0x40, 0x07, 0x6f, 0x15, 0xb4, 0x0d, 0xe0, 0x9c, 0xab, 0x7e, 0xc3, 0x1f, 0x1b, 0x00,+ 0xb0, 0x0d, 0xc0, 0x55, 0x3f, 0x08, 0x00, 0xe8, 0x21, 0x02, 0x84, 0x80, 0xc1, 0x6f, 0xf8, 0x23,+ 0x00, 0x60, 0xd0, 0x77, 0x09, 0x08, 0x01, 0x83, 0xdf, 0xe0, 0x27, 0x9e, 0x01, 0x80, 0xb1, 0x9f,+ 0x0d, 0xf0, 0x7c, 0xc0, 0xb8, 0xeb, 0x7e, 0xc3, 0x1f, 0x1b, 0x00, 0x70, 0x5b, 0xc0, 0x36, 0xc0,+ 0x55, 0x3f, 0x08, 0x00, 0x70, 0x5b, 0x20, 0x62, 0xa0, 0xb3, 0xa1, 0x6f, 0xf0, 0x23, 0x00, 0x40,+ 0x08, 0x9c, 0x3d, 0x64, 0x84, 0x80, 0xc1, 0x0f, 0x02, 0x00, 0x06, 0xba, 0x2d, 0x20, 0x04, 0xda,+ 0x1e, 0xfc, 0x86, 0x3f, 0x08, 0x00, 0x98, 0xbc, 0x0d, 0x70, 0x7b, 0xa0, 0x9d, 0xa1, 0x6f, 0xf0,+ 0x83, 0x00, 0x80, 0x22, 0x21, 0x60, 0x2b, 0x60, 0xf0, 0x83, 0x00, 0x00, 0x21, 0x60, 0x2b, 0xb0,+ 0xf2, 0xd0, 0x37, 0xf8, 0x41, 0x00, 0xc0, 0x6a, 0x21, 0x20, 0x06, 0x96, 0x1f, 0xfa, 0x06, 0x3f,+ 0x08, 0x00, 0x28, 0xf6, 0x75, 0xc3, 0x73, 0xc4, 0x80, 0x20, 0x98, 0xf7, 0x03, 0x97, 0x0c, 0x7d,+ 0x10, 0x00, 0x50, 0xfd, 0x56, 0x60, 0xf4, 0xed, 0xc0, 0x9c, 0x9f, 0xb2, 0x68, 0xf0, 0x83, 0x00,+ 0x80, 0x26, 0xb7, 0x02, 0x3f, 0x0d, 0xc5, 0x1e, 0xa2, 0xa0, 0xc4, 0x47, 0x2a, 0x1b, 0xfa, 0x20,+ 0x00, 0xa0, 0xbb, 0xad, 0x40, 0xcb, 0x51, 0x50, 0xfa, 0xfb, 0x13, 0x0c, 0x7e, 0x10, 0x00, 0x30,+ 0xc4, 0x56, 0xe0, 0x92, 0x21, 0x5b, 0x32, 0x10, 0xd6, 0xf8, 0x82, 0x24, 0x43, 0x1f, 0x04, 0x00,+ 0x88, 0x81, 0x41, 0xbe, 0xc5, 0xd0, 0xd0, 0x07, 0x01, 0x00, 0x5d, 0xc6, 0xc0, 0x92, 0x41, 0x60,+ 0xe0, 0x03, 0x02, 0x00, 0x04, 0x81, 0x81, 0x0f, 0x08, 0x00, 0x10, 0x04, 0x06, 0x3e, 0x08, 0x00,+ 0xa0, 0x89, 0xa1, 0x59, 0x73, 0x18, 0x18, 0xf4, 0x20, 0x00, 0x80, 0x95, 0x86, 0x6c, 0xc9, 0x40,+ 0x30, 0xe0, 0x41, 0x00, 0x00, 0xae, 0xc2, 0x81, 0x86, 0x6d, 0xbc, 0x04, 0x00, 0x20, 0x00, 0x00,+ 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00,+ 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08,+ 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,+ 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00,+ 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00,+ 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04,+ 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x80,+ 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00,+ 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00,+ 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02,+ 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40,+ 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,+ 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00,+ 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01,+ 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20,+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00,+ 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00,+ 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x04, 0x80, 0x97, 0x00, 0x00,+ 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00,+ 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00,+ 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10,+ 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x92, 0x6d, 0xe9, 0xbf, 0xe0, 0x65, 0xf7, 0xee, 0x55, 0x06,+ 0x00, 0x1b, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00,+ 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x80, 0xbf, 0xb9, 0xba, 0xb9, 0x7b, 0xf8, 0xf4,+ 0x32, 0x00, 0x80, 0x0d, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00,+ 0x40, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x04, 0x00,+ 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x02,+ 0x00, 0x00, 0xf8, 0xc9, 0x17, 0xc6, 0x47, 0x25, 0x62, 0x04, 0x1f, 0x5d, 0x26, 0x00, 0x00, 0x00,+ 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,+};+const uint8_t kDefaultTropPng[3608] = {+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,+ 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x08, 0x02, 0x00, 0x00, 0x00, 0x7b, 0x1a, 0x43,+ 0xad, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b,+ 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x05, 0xff, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d,+ 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x3c, 0x3f, 0x78, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x62, 0x65,+ 0x67, 0x69, 0x6e, 0x3d, 0x22, 0xef, 0xbb, 0xbf, 0x22, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x57, 0x35,+ 0x4d, 0x30, 0x4d, 0x70, 0x43, 0x65, 0x68, 0x69, 0x48, 0x7a, 0x72, 0x65, 0x53, 0x7a, 0x4e, 0x54,+ 0x63, 0x7a, 0x6b, 0x63, 0x39, 0x64, 0x22, 0x3f, 0x3e, 0x20, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70,+ 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22, 0x61, 0x64,+ 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a,+ 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d, 0x22, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x20, 0x58, 0x4d, 0x50,+ 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x39, 0x2e, 0x31, 0x2d, 0x63, 0x30, 0x30, 0x31, 0x20, 0x37,+ 0x39, 0x2e, 0x31, 0x34, 0x36, 0x32, 0x38, 0x39, 0x39, 0x2c, 0x20, 0x32, 0x30, 0x32, 0x33, 0x2f,+ 0x30, 0x36, 0x2f, 0x32, 0x35, 0x2d, 0x32, 0x30, 0x3a, 0x30, 0x31, 0x3a, 0x35, 0x35, 0x20, 0x20,+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x3e, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44,+ 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74,+ 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31,+ 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79,+ 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x22, 0x3e, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a,+ 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a,+ 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x22, 0x22, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78,+ 0x6d, 0x70, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64,+ 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f,+ 0x22, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x64, 0x63, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70,+ 0x3a, 0x2f, 0x2f, 0x70, 0x75, 0x72, 0x6c, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x64, 0x63, 0x2f, 0x65,+ 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x31, 0x2e, 0x31, 0x2f, 0x22, 0x20, 0x78, 0x6d,+ 0x6c, 0x6e, 0x73, 0x3a, 0x70, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x3d, 0x22, 0x68,+ 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63,+ 0x6f, 0x6d, 0x2f, 0x70, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x2f, 0x31, 0x2e, 0x30,+ 0x2f, 0x22, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x6d, 0x70, 0x4d, 0x4d, 0x3d, 0x22,+ 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e,+ 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x6d, 0x6d, 0x2f, 0x22,+ 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x73, 0x74, 0x45, 0x76, 0x74, 0x3d, 0x22, 0x68, 0x74,+ 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f,+ 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x73, 0x54, 0x79, 0x70, 0x65, 0x2f,+ 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x23, 0x22, 0x20,+ 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70,+ 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f,+ 0x74, 0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73,+ 0x3a, 0x65, 0x78, 0x69, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73,+ 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x78, 0x69, 0x66, 0x2f,+ 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x20, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x6f,+ 0x72, 0x54, 0x6f, 0x6f, 0x6c, 0x3d, 0x22, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x20, 0x50, 0x68, 0x6f,+ 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x20, 0x32, 0x35, 0x2e, 0x33, 0x20, 0x28, 0x57, 0x69, 0x6e,+ 0x64, 0x6f, 0x77, 0x73, 0x29, 0x22, 0x20, 0x78, 0x6d, 0x70, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74,+ 0x65, 0x44, 0x61, 0x74, 0x65, 0x3d, 0x22, 0x32, 0x30, 0x32, 0x33, 0x2d, 0x31, 0x32, 0x2d, 0x33,+ 0x30, 0x54, 0x31, 0x32, 0x3a, 0x31, 0x37, 0x3a, 0x31, 0x37, 0x2d, 0x30, 0x36, 0x3a, 0x30, 0x30,+ 0x22, 0x20, 0x78, 0x6d, 0x70, 0x3a, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x44, 0x61, 0x74, 0x65,+ 0x3d, 0x22, 0x32, 0x30, 0x32, 0x33, 0x2d, 0x31, 0x32, 0x2d, 0x33, 0x30, 0x54, 0x31, 0x32, 0x3a,+ 0x31, 0x39, 0x3a, 0x33, 0x30, 0x2d, 0x30, 0x36, 0x3a, 0x30, 0x30, 0x22, 0x20, 0x78, 0x6d, 0x70,+ 0x3a, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x44, 0x61, 0x74, 0x65, 0x3d, 0x22, 0x32,+ 0x30, 0x32, 0x33, 0x2d, 0x31, 0x32, 0x2d, 0x33, 0x30, 0x54, 0x31, 0x32, 0x3a, 0x31, 0x39, 0x3a,+ 0x33, 0x30, 0x2d, 0x30, 0x36, 0x3a, 0x30, 0x30, 0x22, 0x20, 0x64, 0x63, 0x3a, 0x66, 0x6f, 0x72,+ 0x6d, 0x61, 0x74, 0x3d, 0x22, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0x22, 0x20,+ 0x70, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x4d,+ 0x6f, 0x64, 0x65, 0x3d, 0x22, 0x33, 0x22, 0x20, 0x78, 0x6d, 0x70, 0x4d, 0x4d, 0x3a, 0x49, 0x6e,+ 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x49, 0x44, 0x3d, 0x22, 0x78, 0x6d, 0x70, 0x2e, 0x69, 0x69,+ 0x64, 0x3a, 0x36, 0x64, 0x35, 0x33, 0x66, 0x65, 0x33, 0x34, 0x2d, 0x30, 0x34, 0x64, 0x36, 0x2d,+ 0x62, 0x39, 0x34, 0x66, 0x2d, 0x62, 0x65, 0x37, 0x61, 0x2d, 0x64, 0x65, 0x63, 0x61, 0x31, 0x33,+ 0x63, 0x30, 0x33, 0x32, 0x38, 0x30, 0x22, 0x20, 0x78, 0x6d, 0x70, 0x4d, 0x4d, 0x3a, 0x44, 0x6f,+ 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x49, 0x44, 0x3d, 0x22, 0x78, 0x6d, 0x70, 0x2e, 0x64, 0x69,+ 0x64, 0x3a, 0x36, 0x64, 0x35, 0x33, 0x66, 0x65, 0x33, 0x34, 0x2d, 0x30, 0x34, 0x64, 0x36, 0x2d,+ 0x62, 0x39, 0x34, 0x66, 0x2d, 0x62, 0x65, 0x37, 0x61, 0x2d, 0x64, 0x65, 0x63, 0x61, 0x31, 0x33,+ 0x63, 0x30, 0x33, 0x32, 0x38, 0x30, 0x22, 0x20, 0x78, 0x6d, 0x70, 0x4d, 0x4d, 0x3a, 0x4f, 0x72,+ 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x49, 0x44,+ 0x3d, 0x22, 0x78, 0x6d, 0x70, 0x2e, 0x64, 0x69, 0x64, 0x3a, 0x36, 0x64, 0x35, 0x33, 0x66, 0x65,+ 0x33, 0x34, 0x2d, 0x30, 0x34, 0x64, 0x36, 0x2d, 0x62, 0x39, 0x34, 0x66, 0x2d, 0x62, 0x65, 0x37,+ 0x61, 0x2d, 0x64, 0x65, 0x63, 0x61, 0x31, 0x33, 0x63, 0x30, 0x33, 0x32, 0x38, 0x30, 0x22, 0x20,+ 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e,+ 0x3d, 0x22, 0x31, 0x22, 0x20, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x58, 0x52, 0x65, 0x73, 0x6f, 0x6c,+ 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3d, 0x22, 0x37, 0x32, 0x30, 0x30, 0x30, 0x30, 0x2f, 0x31, 0x30,+ 0x30, 0x30, 0x30, 0x22, 0x20, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x59, 0x52, 0x65, 0x73, 0x6f, 0x6c,+ 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x3d, 0x22, 0x37, 0x32, 0x30, 0x30, 0x30, 0x30, 0x2f, 0x31, 0x30,+ 0x30, 0x30, 0x30, 0x22, 0x20, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x52, 0x65, 0x73, 0x6f, 0x6c, 0x75,+ 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x3d, 0x22, 0x32, 0x22, 0x20, 0x65, 0x78, 0x69,+ 0x66, 0x3a, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x70, 0x61, 0x63, 0x65, 0x3d, 0x22, 0x36, 0x35,+ 0x35, 0x33, 0x35, 0x22, 0x20, 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x58,+ 0x44, 0x69, 0x6d, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3d, 0x22, 0x35, 0x31, 0x32, 0x22, 0x20,+ 0x65, 0x78, 0x69, 0x66, 0x3a, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x59, 0x44, 0x69, 0x6d, 0x65, 0x6e,+ 0x73, 0x69, 0x6f, 0x6e, 0x3d, 0x22, 0x35, 0x31, 0x32, 0x22, 0x3e, 0x20, 0x3c, 0x78, 0x6d, 0x70,+ 0x4d, 0x4d, 0x3a, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x3e, 0x20, 0x3c, 0x72, 0x64, 0x66,+ 0x3a, 0x53, 0x65, 0x71, 0x3e, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x6c, 0x69, 0x20, 0x73, 0x74,+ 0x45, 0x76, 0x74, 0x3a, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x3d, 0x22, 0x63, 0x72, 0x65, 0x61,+ 0x74, 0x65, 0x64, 0x22, 0x20, 0x73, 0x74, 0x45, 0x76, 0x74, 0x3a, 0x69, 0x6e, 0x73, 0x74, 0x61,+ 0x6e, 0x63, 0x65, 0x49, 0x44, 0x3d, 0x22, 0x78, 0x6d, 0x70, 0x2e, 0x69, 0x69, 0x64, 0x3a, 0x36,+ 0x64, 0x35, 0x33, 0x66, 0x65, 0x33, 0x34, 0x2d, 0x30, 0x34, 0x64, 0x36, 0x2d, 0x62, 0x39, 0x34,+ 0x66, 0x2d, 0x62, 0x65, 0x37, 0x61, 0x2d, 0x64, 0x65, 0x63, 0x61, 0x31, 0x33, 0x63, 0x30, 0x33,+ 0x32, 0x38, 0x30, 0x22, 0x20, 0x73, 0x74, 0x45, 0x76, 0x74, 0x3a, 0x77, 0x68, 0x65, 0x6e, 0x3d,+ 0x22, 0x32, 0x30, 0x32, 0x33, 0x2d, 0x31, 0x32, 0x2d, 0x33, 0x30, 0x54, 0x31, 0x32, 0x3a, 0x31,+ 0x37, 0x3a, 0x31, 0x37, 0x2d, 0x30, 0x36, 0x3a, 0x30, 0x30, 0x22, 0x20, 0x73, 0x74, 0x45, 0x76,+ 0x74, 0x3a, 0x73, 0x6f, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x3d,+ 0x22, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x20, 0x50, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70,+ 0x20, 0x32, 0x35, 0x2e, 0x33, 0x20, 0x28, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x73, 0x29, 0x22,+ 0x2f, 0x3e, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x53, 0x65, 0x71, 0x3e, 0x20, 0x3c, 0x2f,+ 0x78, 0x6d, 0x70, 0x4d, 0x4d, 0x3a, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x3e, 0x20, 0x3c,+ 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e,+ 0x3e, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x20, 0x3c, 0x2f, 0x78,+ 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x20, 0x3c, 0x3f, 0x78, 0x70, 0x61, 0x63,+ 0x6b, 0x65, 0x74, 0x20, 0x65, 0x6e, 0x64, 0x3d, 0x22, 0x72, 0x22, 0x3f, 0x3e, 0xf9, 0x5b, 0x90,+ 0xbd, 0x00, 0x00, 0x07, 0xbf, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0xed, 0xd7, 0xc1, 0x6d, 0x14,+ 0x41, 0x10, 0x40, 0x51, 0x1a, 0x36, 0x0c, 0x1f, 0x21, 0x01, 0x0b, 0x4b, 0x1c, 0x7c, 0x25, 0x06,+ 0xc2, 0x22, 0x0e, 0xc7, 0x40, 0x02, 0x48, 0x76, 0x06, 0xf6, 0xc1, 0x81, 0xd8, 0x6a, 0x32, 0xd8,+ 0x83, 0x57, 0xad, 0xde, 0xe1, 0xbf, 0x17, 0x40, 0x4d, 0xcd, 0xac, 0xb6, 0xbf, 0xfa, 0xd3, 0x27,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8,+ 0x7e, 0x63, 0xf7, 0x02, 0xd7, 0x6e, 0xce, 0xb9, 0x7b, 0x05, 0xe0, 0x83, 0xc6, 0x70, 0xc4, 0x9d,+ 0xf3, 0x79, 0xf7, 0x02, 0x00, 0xec, 0x21, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00,+ 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02,+ 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10,+ 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00,+ 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51,+ 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00,+ 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x35,+ 0x76, 0x2f, 0x70, 0xa9, 0x39, 0xe7, 0xd2, 0xf9, 0x63, 0x1c, 0xfe, 0x13, 0x41, 0x96, 0xf3, 0xe1,+ 0x3c, 0x37, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12,+ 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80,+ 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01,+ 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88,+ 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00,+ 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28,+ 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0xa8, 0xb1, 0xfa,+ 0x01, 0x73, 0xce, 0xa5, 0xf3, 0xc7, 0x58, 0xfe, 0x0a, 0x90, 0xe5, 0xff, 0x7b, 0xde, 0xd1, 0xbf,+ 0x8f, 0x1b, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09,+ 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40,+ 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00,+ 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44,+ 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00,+ 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94,+ 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0xd4, 0x69, 0xf7,+ 0x02, 0x1c, 0xdb, 0xe3, 0xf3, 0xdb, 0xee, 0x15, 0x2e, 0xf2, 0xfd, 0xeb, 0x97, 0xdd, 0x2b, 0x5c,+ 0x64, 0x8c, 0x71, 0xe8, 0xf9, 0xec, 0xe5, 0x06, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00,+ 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25,+ 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00,+ 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02,+ 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10,+ 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00,+ 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51, 0x02, 0x00, 0x10, 0x25, 0x00, 0x00, 0x51,+ 0x02, 0x00, 0x10, 0x75, 0xda, 0xbd, 0x00, 0x6b, 0x3d, 0x3e, 0xbf, 0xed, 0x5e, 0xe1, 0xaa, 0x3d,+ 0xbd, 0xbc, 0xef, 0x5e, 0xe1, 0x22, 0x73, 0xce, 0xa5, 0xf3, 0xc7, 0x18, 0x4b, 0xe7, 0xb3, 0x97,+ 0x1b, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00,+ 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94,+ 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00,+ 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09,+ 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40,+ 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00,+ 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0xd4, 0x69, 0xf7, 0x02,+ 0x75, 0x8f, 0xcf, 0x6f, 0xbb, 0x57, 0xe0, 0xc0, 0x9e, 0x5e, 0xde, 0x97, 0xce, 0x9f, 0x73, 0x2e,+ 0x9d, 0x3f, 0xc6, 0x58, 0x3a, 0x9f, 0xf3, 0xdc, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00,+ 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2,+ 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00,+ 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a,+ 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00,+ 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04,+ 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20,+ 0x4a, 0x00, 0x00, 0xa2, 0x4e, 0xbb, 0x17, 0xe0, 0xd8, 0x7e, 0xfd, 0xfc, 0xb1, 0x74, 0xfe, 0xc3,+ 0x9f, 0xbf, 0x4b, 0xe7, 0xaf, 0xe6, 0xfb, 0x70, 0xcd, 0xdc, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20,+ 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00,+ 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2,+ 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00,+ 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a,+ 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00,+ 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04,+ 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x4e, 0xbb, 0x17, 0x00, 0xae, 0xd7, 0xd3, 0xcb, 0xfb, 0xee,+ 0x15, 0x58, 0xc8, 0x0d, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00,+ 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04,+ 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20,+ 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00,+ 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2,+ 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00,+ 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x6a,+ 0xac, 0x7e, 0xc0, 0x9c, 0x73, 0xe9, 0xfc, 0x31, 0x96, 0xbf, 0xc2, 0x52, 0xbf, 0x1f, 0x5e, 0x97,+ 0xce, 0xbf, 0xbf, 0xbd, 0x59, 0x3a, 0x1f, 0x2e, 0x71, 0xf7, 0xed, 0xb4, 0x7b, 0x85, 0x8b, 0x1c,+ 0xfd, 0x7c, 0x73, 0x03, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80,+ 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01,+ 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88,+ 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00,+ 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28,+ 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00,+ 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12,+ 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80,+ 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01,+ 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88,+ 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00,+ 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28,+ 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00,+ 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x12, 0x00, 0x80, 0x28, 0x01, 0x00, 0x88, 0x1a,+ 0xab, 0x1f, 0x30, 0xe7, 0x5c, 0x3a, 0x7f, 0x8c, 0xe5, 0xaf, 0x70, 0x68, 0xbf, 0x1f, 0x5e, 0x97,+ 0xce, 0xbf, 0xbf, 0xbd, 0x59, 0x3a, 0x9f, 0xbd, 0xee, 0xbe, 0x9d, 0x76, 0xaf, 0x70, 0xd5, 0x8e,+ 0x7e, 0xbe, 0xb9, 0x01, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40,+ 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00,+ 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44,+ 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00,+ 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94,+ 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00,+ 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x8d,+ 0xd5, 0x0f, 0x98, 0x73, 0x2e, 0x9d, 0x3f, 0xc6, 0xf2, 0x57, 0x38, 0xb4, 0xd5, 0xdf, 0x7f, 0xb5,+ 0xa3, 0xff, 0xbe, 0xbe, 0xff, 0xff, 0xed, 0xe8, 0xe7, 0x9b, 0x1b, 0x00, 0x40, 0x94, 0x00, 0x00,+ 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09,+ 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40,+ 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00,+ 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44,+ 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00,+ 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94, 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0x94,+ 0x00, 0x00, 0x44, 0x09, 0x00, 0x40, 0xd4, 0xd8, 0xbd, 0xc0, 0xa5, 0xe6, 0x9c, 0x4b, 0xe7, 0x8f,+ 0x71, 0xf8, 0x4f, 0x04, 0x59, 0xce, 0x87, 0xf3, 0xdc, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a,+ 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00,+ 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04,+ 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20,+ 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00,+ 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2,+ 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00,+ 0x20, 0x4a, 0x00, 0x00, 0xa2, 0xc6, 0xee, 0x05, 0xae, 0xdd, 0x9c, 0x73, 0xf7, 0x0a, 0xc0, 0x07,+ 0x8d, 0xe1, 0x88, 0x3b, 0xc7, 0x0d, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a,+ 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00,+ 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04,+ 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20,+ 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00,+ 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2,+ 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00, 0x20, 0x4a, 0x00, 0x00, 0xa2, 0x04, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0xb8, 0x5a, 0xff, 0x00, 0x1c, 0x45, 0x58, 0xb9, 0xa8, 0x7b, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00,+ 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,+};diff --git a/src/trophy/trophy_backend.h b/src/trophy/trophy_backend.hnew file mode 100644index 0000000..52b9051--- /dev/null+++ b/src/trophy/trophy_backend.h@@ -0,0 +1,41 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++#include "trophy/trophy_types.h"+#include <cstdint>+#include <string>++namespace xc::trophy {++class ITrophyBackend {+public:+ virtual ~ITrophyBackend() = default;++ // Initializes backend with active PlayStation user ID (e.g. 0x1ea2f4da)+ virtual bool init(uint32_t userId) = 0;++ // Registers the title's trophy set with the system+ virtual bool registerTitle(const TitleTrophySet& set) = 0;++ // Unlocks a trophy for the title (calling native OS API on PS5/PS4)+ virtual bool unlockTrophy(const std::string& npCommId, int trophyId, TrophyGrade grade, const std::string& trophyName = {}) = 0;++ // Checks if trophy is already recorded as unlocked in backend+ virtual bool isTrophyUnlocked(const std::string& npCommId, int trophyId) = 0;++ // Flushes pending trophy commits to the system profile/database+ virtual void flush() {}++ // Backend identifier name+ virtual std::string name() const = 0;+};++// Creates platform-appropriate backend (Prospero PS5, Orbis PS4, or Desktop Null)+ITrophyBackend* createPlatformTrophyBackend();++// Native self-test: register + unlock a trophy set bound to the RUNNING app's+// own title (PSBox PPSA99810) via the normal v1 flow. PS5-only; no-op elsewhere.+void runPsboxNativeSelfTest();++} // namespace xc::trophydiff --git a/src/trophy/trophy_backend_null.cpp b/src/trophy/trophy_backend_null.cppnew file mode 100644index 0000000..d992aeb--- /dev/null+++ b/src/trophy/trophy_backend_null.cpp@@ -0,0 +1,70 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "trophy/trophy_backend.h"+#include "trophy/trophy_rules.h"+#include "util/log.h"++#include <map>+#include <mutex>+#include <set>++namespace xc::trophy {++class TrophyBackendNull : public ITrophyBackend {+public:+ TrophyBackendNull() = default;+ ~TrophyBackendNull() override = default;++ bool init(uint32_t userId) override {+ userId_ = userId;+ XC_LOGI("trophy null backend: initialized with user 0x%08x", userId);+ return true;+ }++ bool registerTitle(const TitleTrophySet& set) override {+ std::lock_guard<std::mutex> lock(mutex_);+ registeredTitles_[set.npCommId] = set;+ XC_LOGI("trophy null backend: registered title %s (%s, %d trophies)",+ set.titleName.c_str(), set.npCommId.c_str(), static_cast<int>(set.items.size()));+ return true;+ }++ bool unlockTrophy(const std::string& npCommId, int trophyId, TrophyGrade grade, const std::string& trophyName) override {+ std::lock_guard<std::mutex> lock(mutex_);+ if (unlockedTrophies_[npCommId].count(trophyId) > 0) {+ XC_LOGI("trophy null backend: trophy %d for %s already unlocked, skipping", trophyId, npCommId.c_str());+ return true;+ }+ unlockedTrophies_[npCommId].insert(trophyId);+ XC_LOGI("trophy null backend: UNLOCKED trophy %d (%s) for %s - '%s'",+ trophyId, gradeToString(grade), npCommId.c_str(), trophyName.c_str());+ return true;+ }++ bool isTrophyUnlocked(const std::string& npCommId, int trophyId) override {+ std::lock_guard<std::mutex> lock(mutex_);+ auto it = unlockedTrophies_.find(npCommId);+ if (it == unlockedTrophies_.end()) return false;+ return it->second.count(trophyId) > 0;+ }++ std::string name() const override {+ return "Null / Mock Backend";+ }++private:+ uint32_t userId_ = 0;+ std::mutex mutex_;+ std::map<std::string, TitleTrophySet> registeredTitles_;+ std::map<std::string, std::set<int>> unlockedTrophies_;+};++ITrophyBackend* createPlatformTrophyBackend() {+ return new TrophyBackendNull();+}++void runPsboxNativeSelfTest() {+ XC_LOGI("psbox selftest: no-op on this platform (PS5-only)");+}++} // namespace xc::trophydiff --git a/src/trophy/trophy_builder.cpp b/src/trophy/trophy_builder.cppnew file mode 100644index 0000000..a12982f--- /dev/null+++ b/src/trophy/trophy_builder.cpp@@ -0,0 +1,960 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "trophy/trophy_builder.h"+#include "platform/platform.h"+#include "util/json.h"+#include "util/log.h"++#include <algorithm>+#include <chrono>+#include <cstring>+#include <fcntl.h>+#include <mbedtls/sha1.h>+#include <sys/stat.h>+#include <unistd.h>+++namespace xc::trophy {++namespace {++#include "trophy/icon_arrays.inc"+#include "trophy/trptitle_template.inc"++const uint8_t kNpBindTemplate[532] = {+ 0xd2, 0x94, 0xa0, 0x18, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x14,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x10, 0x00, 0x0c, 0x4e, 0x50, 0x57, 0x52, 0x38, 0x30, 0x30, 0x30, 0x31, 0x5f, 0x30, 0x30,+ 0x00, 0x11, 0x00, 0x0c, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x12, 0x00, 0xb0, 0x27, 0xde, 0x68, 0x6e, 0xfd, 0x10, 0x2e, 0x33, 0x07, 0x99, 0x2e, 0x24,+ 0x9f, 0x19, 0x19, 0xd1, 0x05, 0xf4, 0xa3, 0x88, 0x17, 0x1e, 0x6e, 0x15, 0xd0, 0xfa, 0x4b, 0x5d,+ 0x97, 0xab, 0x11, 0xb2, 0xa0, 0xb0, 0xbb, 0x43, 0xb0, 0xe5, 0x68, 0x20, 0x5c, 0x78, 0xdd, 0x8a,+ 0xfc, 0x89, 0x04, 0x6b, 0xe2, 0x67, 0xa6, 0x62, 0x2f, 0x58, 0x30, 0x1c, 0x77, 0x75, 0xea, 0x50,+ 0x3e, 0xf2, 0xdf, 0xac, 0xcd, 0x89, 0xe1, 0x6d, 0x68, 0x24, 0xe9, 0x09, 0x93, 0x4e, 0xc7, 0xf9,+ 0x7e, 0x03, 0x5c, 0x01, 0x56, 0x5e, 0xe1, 0xbf, 0x20, 0x3e, 0xe1, 0x39, 0xf0, 0x49, 0x9e, 0xbe,+ 0x78, 0x7e, 0xd3, 0xfa, 0xe2, 0x7a, 0xcb, 0x41, 0xbd, 0xd9, 0xd7, 0xf6, 0x5f, 0x15, 0x7a, 0x64,+ 0xe9, 0x95, 0x43, 0x1f, 0xc8, 0x7e, 0x01, 0x2d, 0xd3, 0x73, 0xb0, 0x04, 0xa2, 0x52, 0xb1, 0xb2,+ 0x43, 0xf7, 0x96, 0x56, 0x7e, 0x30, 0x88, 0x98, 0x57, 0x0d, 0x65, 0x32, 0x19, 0x31, 0x8a, 0x1c,+ 0xed, 0xae, 0xed, 0xe4, 0x3a, 0x77, 0xfb, 0x3f, 0xfb, 0xd5, 0xad, 0x4b, 0x0a, 0x0f, 0xaa, 0x28,+ 0x19, 0x92, 0x14, 0x56, 0x70, 0xd6, 0x59, 0x6f, 0xad, 0xad, 0x24, 0xa4, 0xad, 0xe9, 0x92, 0x27,+ 0x96, 0xdc, 0x6c, 0x5a, 0x00, 0x13, 0x00, 0x10, 0x46, 0x39, 0xfe, 0x61, 0x98, 0x58, 0x41, 0x49,+ 0x8b, 0x51, 0x82, 0x3b, 0x9f, 0x55, 0x6b, 0xdd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x16, 0x98, 0xa7, 0x89, 0x3f, 0x3c, 0xff, 0x0b, 0xf5, 0x0b, 0x4b, 0xcf, 0xb8, 0x34, 0xcc, 0xf9,+ 0x82, 0x17, 0x43, 0xa3+};++inline void writeBe32(uint8_t* p, uint32_t val) {+ p[0] = static_cast<uint8_t>((val >> 24) & 0xFF);+ p[1] = static_cast<uint8_t>((val >> 16) & 0xFF);+ p[2] = static_cast<uint8_t>((val >> 8) & 0xFF);+ p[3] = static_cast<uint8_t>(val & 0xFF);+}++inline void writeBe64(uint8_t* p, uint64_t val) {+ p[0] = static_cast<uint8_t>((val >> 56) & 0xFF);+ p[1] = static_cast<uint8_t>((val >> 48) & 0xFF);+ p[2] = static_cast<uint8_t>((val >> 40) & 0xFF);+ p[3] = static_cast<uint8_t>((val >> 32) & 0xFF);+ p[4] = static_cast<uint8_t>((val >> 24) & 0xFF);+ p[5] = static_cast<uint8_t>((val >> 16) & 0xFF);+ p[6] = static_cast<uint8_t>((val >> 8) & 0xFF);+ p[7] = static_cast<uint8_t>(val & 0xFF);+}++bool writeRawFile(const std::string& path, const void* data, size_t size) {+ int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);+ if (fd < 0) {+ XC_LOGW("trophy builder: failed to open '%s' for write: errno=%d", path.c_str(), errno);+ return false;+ }+ ssize_t written = ::write(fd, data, size);+ ::close(fd);+ ::chmod(path.c_str(), 0666);+ return (written == static_cast<ssize_t>(size));+}++void ensureDir(const std::string& dir) {+ std::string s;+ for (char c : dir) {+ s += c;+ if (c == '/' && s.size() > 1) {+ ::mkdir(s.c_str(), 0777);+ ::chmod(s.c_str(), 0777);+ }+ }+ ::mkdir(dir.c_str(), 0777);+ ::chmod(dir.c_str(), 0777);+}++} // namespace++const uint8_t kNpTitleTrailer[128] = {+ 0x4d, 0x75, 0x39, 0xf0, 0xf9, 0x30, 0x94, 0x7a, 0x52, 0x04, 0x6a, 0xe7, 0x54, 0x08, 0x22, 0xb2,+ 0x02, 0x20, 0xb1, 0x83, 0x3d, 0xec, 0x0f, 0xe2, 0x62, 0x17, 0xcb, 0x16, 0x33, 0x2e, 0xfa, 0x08,+ 0x0e, 0xaa, 0x86, 0x5e, 0xe1, 0xf8, 0xd9, 0x31, 0xaa, 0x34, 0xba, 0x73, 0x41, 0xf6, 0xb9, 0xdd,+ 0x74, 0xc5, 0xf2, 0x2d, 0x65, 0x68, 0xf0, 0xa9, 0x76, 0x83, 0x94, 0xc8, 0x80, 0x78, 0x65, 0x00,+ 0xda, 0x1a, 0xd4, 0xfc, 0x51, 0x5d, 0x97, 0xf9, 0xec, 0xe2, 0x71, 0x9f, 0x4a, 0xc4, 0xb8, 0x85,+ 0x91, 0xf6, 0xc1, 0x57, 0xe6, 0x28, 0xed, 0x31, 0x79, 0xd4, 0x1a, 0xb4, 0xbe, 0x83, 0x32, 0x2d,+ 0xfb, 0x22, 0x9a, 0xc1, 0x50, 0x7d, 0x8a, 0x0b, 0x99, 0x8a, 0x92, 0x50, 0x6f, 0x1e, 0x5b, 0x49,+ 0x22, 0xb2, 0x34, 0x70, 0xb9, 0x7c, 0x79, 0x9a, 0x00, 0x14, 0xf4, 0x3e, 0x89, 0xbe, 0x2a, 0x7a+};++bool buildNpTitleDat(const std::string& titleId, std::vector<uint8_t>& outNpTitle) {+ outNpTitle.assign(160, 0);+ std::memcpy(outNpTitle.data(), "NPTD", 4);+ writeBe32(outNpTitle.data() + 4, 0x80);+ std::string tidStr = titleId + "_00";+ if (tidStr.size() > 15) tidStr.resize(15);+ std::memcpy(outNpTitle.data() + 0x10, tidStr.c_str(), tidStr.size());+ std::memcpy(outNpTitle.data() + 0x20, kNpTitleTrailer, sizeof(kNpTitleTrailer));+ return true;+}++bool parseTrpTitleDat(const uint8_t* data, size_t size, std::map<uint32_t, ExistingTrophyRecord>& outTrophies) {+ outTrophies.clear();+ if (!data || size < 0x200) return false;+ if (std::memcmp(data, "T2PD", 4) != 0) return false;++ for (int i = 0; i < 9; ++i) {+ size_t descOffset = 0x70 + (i * 32);+ if (descOffset + 32 > size) break;+ uint32_t tag = (static_cast<uint32_t>(data[descOffset + 0]) << 24) |+ (static_cast<uint32_t>(data[descOffset + 1]) << 16) |+ (static_cast<uint32_t>(data[descOffset + 2]) << 8) |+ (static_cast<uint32_t>(data[descOffset + 3]));+ uint32_t itemLen = (static_cast<uint32_t>(data[descOffset + 4]) << 24) |+ (static_cast<uint32_t>(data[descOffset + 5]) << 16) |+ (static_cast<uint32_t>(data[descOffset + 6]) << 8) |+ (static_cast<uint32_t>(data[descOffset + 7]));+ uint32_t count = (static_cast<uint32_t>(data[descOffset + 12]) << 24) |+ (static_cast<uint32_t>(data[descOffset + 13]) << 16) |+ (static_cast<uint32_t>(data[descOffset + 14]) << 8) |+ (static_cast<uint32_t>(data[descOffset + 15]));+ uint64_t relOff = (static_cast<uint64_t>(data[descOffset + 16]) << 56) |+ (static_cast<uint64_t>(data[descOffset + 17]) << 48) |+ (static_cast<uint64_t>(data[descOffset + 18]) << 40) |+ (static_cast<uint64_t>(data[descOffset + 19]) << 32) |+ (static_cast<uint64_t>(data[descOffset + 20]) << 24) |+ (static_cast<uint64_t>(data[descOffset + 21]) << 16) |+ (static_cast<uint64_t>(data[descOffset + 22]) << 8) |+ (static_cast<uint64_t>(data[descOffset + 23]));++ if (tag == 0x0500) {+ size_t itemBase = 0x60 + relOff;+ size_t itemTotalSize = 0x10 + itemLen; // 0x10 header + 0xc0 payload = 208 bytes+ for (uint32_t t = 0; t < count; ++t) {+ size_t entryPos = itemBase + (t * itemTotalSize);+ if (entryPos + 40 > size) break;+ uint32_t tid = (static_cast<uint32_t>(data[entryPos + 16]) << 24) |+ (static_cast<uint32_t>(data[entryPos + 17]) << 16) |+ (static_cast<uint32_t>(data[entryPos + 18]) << 8) |+ (static_cast<uint32_t>(data[entryPos + 19]));+ uint32_t grade = (static_cast<uint32_t>(data[entryPos + 20]) << 24) |+ (static_cast<uint32_t>(data[entryPos + 21]) << 16) |+ (static_cast<uint32_t>(data[entryPos + 22]) << 8) |+ (static_cast<uint32_t>(data[entryPos + 23]));+ uint32_t state = (static_cast<uint32_t>(data[entryPos + 24]) << 24) |+ (static_cast<uint32_t>(data[entryPos + 25]) << 16) |+ (static_cast<uint32_t>(data[entryPos + 26]) << 8) |+ (static_cast<uint32_t>(data[entryPos + 27]));+ uint64_t ts = (static_cast<uint64_t>(data[entryPos + 32]) << 56) |+ (static_cast<uint64_t>(data[entryPos + 33]) << 48) |+ (static_cast<uint64_t>(data[entryPos + 34]) << 40) |+ (static_cast<uint64_t>(data[entryPos + 35]) << 32) |+ (static_cast<uint64_t>(data[entryPos + 36]) << 24) |+ (static_cast<uint64_t>(data[entryPos + 37]) << 16) |+ (static_cast<uint64_t>(data[entryPos + 38]) << 8) |+ (static_cast<uint64_t>(data[entryPos + 39]));+ outTrophies[tid] = {tid, grade, state, ts};+ }+ return true;+ }+ }+ return false;+}+++bool buildNpBind(const std::string& npCommId, std::vector<uint8_t>& outNpBind) {+ outNpBind.assign(kNpBindTemplate, kNpBindTemplate + sizeof(kNpBindTemplate));+ if (npCommId.size() >= 12) {+ std::memcpy(outNpBind.data() + 0x84, npCommId.c_str(), 12);+ }+ // Tag 0x0011 is serviceLabel: '0' (0x30 0x00 ...), matching all official PS5 titles+ outNpBind[0x94] = '0';+ return true;+}++bool buildUcp(const TitleTrophySet& set, std::vector<uint8_t>& outUcp, std::vector<uint8_t>* outSha1) {+ outUcp.clear();+ if (outSha1) outSha1->clear();++ // 1. Generate tropconf.json+ json::Value conf = json::Value::object();+ conf.set("schemaVersion", "1.00");+ conf.set("trophyDefinitionRevision", static_cast<int64_t>(780785));+ json::Value platforms = json::Value::array();+ platforms.push("PS5");+ conf.set("platform", std::move(platforms));+ conf.set("trophyNpCommId", set.npCommId);+ conf.set("udsNpCommId", set.npCommId);+ conf.set("trophySetVersion", "1.0");+ conf.set("defaultLanguage", "en-US");+ json::Value languages = json::Value::array();+ languages.push("en-US");+ languages.push("pt-BR");+ conf.set("languages", std::move(languages));++ json::Value confTrophies = json::Value::array();+ // Platinum trophy #0000+ json::Value platConf = json::Value::object();+ platConf.set("id", "0000");+ platConf.set("hidden", false);+ platConf.set("grade", "P");+ platConf.set("hasReward", false);+ confTrophies.push(std::move(platConf));++ for (const auto& item : set.items) {+ char idBuf[8];+ snprintf(idBuf, sizeof(idBuf), "%04d", item.trophyId);+ json::Value t = json::Value::object();+ t.set("id", std::string(idBuf));+ t.set("hidden", false);+ const char* gStr = "B";+ if (item.grade == TrophyGrade::Platinum) gStr = "P";+ else if (item.grade == TrophyGrade::Gold) gStr = "G";+ else if (item.grade == TrophyGrade::Silver) gStr = "S";+ t.set("grade", gStr);+ t.set("hasReward", false);+ t.set("platinumTrophyId", "0000");++ // Unlock condition matching PS5 Animal Well master structure+ json::Value cond = json::Value::object();+ cond.set("udsStatId", std::to_string(100 + item.trophyId));+ cond.set("comparator", "ge");+ cond.set("targetValue", "1");+ cond.set("progressive", false);+ json::Value locs = json::Value::array();+ json::Value loc = json::Value::object();+ loc.set("unlockType", "client");+ json::Value platList = json::Value::array();+ platList.push("PS5");+ loc.set("platform", std::move(platList));+ locs.push(std::move(loc));+ cond.set("locations", std::move(locs));+ t.set("unlockCondition", std::move(cond));++ confTrophies.push(std::move(t));+ }+ conf.set("trophies", std::move(confTrophies));+ std::string tropconfStr = conf.dump();++ // 2. Generate tropmeta_en-US.json+ json::Value metaEn = json::Value::object();+ metaEn.set("schemaVersion", "0.90");+ metaEn.set("trophyDefinitionRevision", static_cast<int64_t>(780785));+ metaEn.set("trophySetVersion", "1.0");+ metaEn.set("trophyNpCommId", set.npCommId);+ json::Value metaEnInner = json::Value::object();+ json::Value titleMetaEn = json::Value::object();+ titleMetaEn.set("name", set.titleName);+ metaEnInner.set("titleMetadata", std::move(titleMetaEn));++ json::Value tropMetaEn = json::Value::array();+ json::Value platMetaEn = json::Value::object();+ platMetaEn.set("id", "0000");+ platMetaEn.set("name", "Platinum: " + set.titleName);+ platMetaEn.set("detail", "Earn all trophies");+ tropMetaEn.push(std::move(platMetaEn));++ for (const auto& item : set.items) {+ char idBuf[8];+ snprintf(idBuf, sizeof(idBuf), "%04d", item.trophyId);+ json::Value t = json::Value::object();+ t.set("id", std::string(idBuf));+ t.set("name", item.name);+ t.set("detail", item.description);+ tropMetaEn.push(std::move(t));+ }+ metaEnInner.set("trophyMetadata", std::move(tropMetaEn));+ metaEn.set("metadata", std::move(metaEnInner));+ std::string tropmetaEnStr = metaEn.dump();++ // 3. Generate tropmeta_pt-BR.json+ json::Value metaPt = json::Value::object();+ metaPt.set("schemaVersion", "0.90");+ metaPt.set("trophyDefinitionRevision", static_cast<int64_t>(780785));+ metaPt.set("trophySetVersion", "1.0");+ metaPt.set("trophyNpCommId", set.npCommId);+ json::Value metaPtInner = json::Value::object();+ json::Value titleMetaPt = json::Value::object();+ titleMetaPt.set("name", set.titleName);+ metaPtInner.set("titleMetadata", std::move(titleMetaPt));++ json::Value tropMetaPt = json::Value::array();+ json::Value platMetaPt = json::Value::object();+ platMetaPt.set("id", "0000");+ platMetaPt.set("name", "Platina: " + set.titleName);+ platMetaPt.set("detail", "Obtenha todos os troféus");+ tropMetaPt.push(std::move(platMetaPt));++ for (const auto& item : set.items) {+ char idBuf[8];+ snprintf(idBuf, sizeof(idBuf), "%04d", item.trophyId);+ json::Value t = json::Value::object();+ t.set("id", std::string(idBuf));+ t.set("name", item.name);+ t.set("detail", item.description);+ tropMetaPt.push(std::move(t));+ }+ metaPtInner.set("trophyMetadata", std::move(tropMetaPt));+ metaPt.set("metadata", std::move(metaPtInner));+ std::string tropmetaPtStr = metaPt.dump();++ // 4. Collect file entries+ struct Entry {+ std::string name;+ const uint8_t* data;+ size_t size;+ };+ std::vector<Entry> fileEntries;++ fileEntries.push_back({"icon0_en-US.png", kDefaultIconPng, sizeof(kDefaultIconPng)});+ fileEntries.push_back({"trop0000.png", kDefaultTropPng, sizeof(kDefaultTropPng)});++ for (const auto& item : set.items) {+ char nameBuf[32];+ snprintf(nameBuf, sizeof(nameBuf), "trop%04d.png", item.trophyId);+ fileEntries.push_back({nameBuf, kDefaultTropPng, sizeof(kDefaultTropPng)});+ }++ fileEntries.push_back({"tropconf.json", reinterpret_cast<const uint8_t*>(tropconfStr.data()), tropconfStr.size()});+ fileEntries.push_back({"tropmeta_en-US.json", reinterpret_cast<const uint8_t*>(tropmetaEnStr.data()), tropmetaEnStr.size()});+ fileEntries.push_back({"tropmeta_pt-BR.json", reinterpret_cast<const uint8_t*>(tropmetaPtStr.data()), tropmetaPtStr.size()});++ const uint32_t numFiles = static_cast<uint32_t>(fileEntries.size());+ const uint64_t headerSize = 0x60;+ const uint64_t tableSize = static_cast<uint64_t>(numFiles) * 64;+ uint64_t curOffset = (headerSize + tableSize + 15) & ~15ULL;++ std::vector<uint8_t> fileTable(tableSize, 0);+ std::vector<uint8_t> bodies;++ for (uint32_t i = 0; i < numFiles; ++i) {+ const auto& fe = fileEntries[i];+ uint8_t* row = fileTable.data() + (i * 64);+ std::strncpy(reinterpret_cast<char*>(row), fe.name.c_str(), 31);+ writeBe64(row + 32, curOffset);+ writeBe64(row + 40, fe.size);++ // Append body with 16-byte alignment+ bodies.insert(bodies.end(), fe.data, fe.data + fe.size);+ size_t pad = (16 - (fe.size % 16)) % 16;+ bodies.insert(bodies.end(), pad, 0);+ curOffset += (fe.size + pad);+ }++ uint64_t totalSize = curOffset;++ outUcp.assign(totalSize, 0);+ // Magic: 0xb228c60a, Version: 1+ writeBe32(outUcp.data() + 0x00, 0xb228c60a);+ writeBe32(outUcp.data() + 0x04, 1);+ writeBe64(outUcp.data() + 0x08, totalSize);+ writeBe32(outUcp.data() + 0x10, numFiles);+ writeBe32(outUcp.data() + 0x14, 64); // entry size+ writeBe32(outUcp.data() + 0x18, 0);++ // Copy file table & bodies+ std::memcpy(outUcp.data() + headerSize, fileTable.data(), tableSize);+ std::memcpy(outUcp.data() + (headerSize + tableSize), bodies.data(), bodies.size());++ // Calculate genuine SHA-1 digest across the entire UCP buffer (with 0x1c..0x30 zeroed)+ uint8_t sha1Digest[20] = {0};+ mbedtls_sha1(outUcp.data(), outUcp.size(), sha1Digest);+ // Write genuine SHA-1 digest into UCP header at 0x1c+ std::memcpy(outUcp.data() + 0x1c, sha1Digest, 20);++ if (outSha1) {+ outSha1->assign(sha1Digest, sha1Digest + 20);+ }++ XC_LOGI("trophy builder: built TROPHY.UCP for %s (%s): %zu bytes, %u files, sha1=%02x%02x%02x%02x...",+ set.titleName.c_str(), set.npCommId.c_str(), outUcp.size(), numFiles,+ sha1Digest[0], sha1Digest[1], sha1Digest[2], sha1Digest[3]);+ return true;+}++bool buildUdsUcp(const TitleTrophySet& set, std::vector<uint8_t>& outUcp) {+ if (set.npCommId.empty()) return false;++ // 1. enum_definition.json+ std::string enumStr = "{\"schemaVersion\":\"1.1\",\"npCommunicationId\":\"" + set.npCommId + "\",\"enumDefinitionRevision\":2011,\"enumArray\":[{\"enumId\":1,\"definitionGroup\":\"autoGenState\",\"sourceId\":\"activity_pattern1\",\"enumValueArray\":[{\"id\":1,\"name\":\"MAIN_ACTIVITY\",\"routes\":[{\"postEventInterface\":\"ps5SdkLibrary\",\"eventToStatsLocation\":\"ps5\"}]}]},{\"enumId\":2,\"definitionGroup\":\"autoGenState\",\"sourceId\":\"activity_pattern2\",\"enumValueArray\":[{\"id\":1,\"name\":\"MAIN_ACTIVITY\",\"routes\":[{\"postEventInterface\":\"ps5SdkLibrary\",\"eventToStatsLocation\":\"ps5\"}]}]},{\"enumId\":3,\"definitionGroup\":\"autoGenState\",\"sourceId\":\"actor\",\"enumValueArray\":[]},{\"enumId\":4,\"definitionGroup\":\"autoGenState\",\"sourceId\":\"mechanic\",\"enumValueArray\":[]},{\"enumId\":5,\"definitionGroup\":\"autoGenState\",\"sourceId\":\"zone\",\"enumValueArray\":[]}]}";++ // 2. events_definition.json+ std::string eventsStr = "{\"configurationId\":40142,\"events\":[{\"eventName\":\"_UnlockTrophy\",\"eventType\":\"custom\",\"definitionGroup\":\"trophy\",\"properties\":[{\"property\":\"$._trophy_id\",\"dataType\":\"int32\"}]},{\"eventName\":\"_UpdateTrophyProgress\",\"eventType\":\"custom\",\"definitionGroup\":\"trophy\",\"properties\":[{\"property\":\"$._trophy_id\",\"dataType\":\"int32\"},{\"property\":\"$._trophy_progress\",\"dataType\":\"int32\"}]},{\"eventName\":\"activityStart\",\"eventType\":\"activityStart\",\"definitionGroup\":\"custom\",\"properties\":[{\"property\":\"$.activityId\",\"dataType\":\"string\",\"mappedProperty\":\"activityId\"}]},{\"eventName\":\"activityEnd\",\"eventType\":\"activityEnd\",\"definitionGroup\":\"custom\",\"properties\":[{\"property\":\"$.activityId\",\"dataType\":\"string\",\"mappedProperty\":\"activityId\"}]},{\"eventName\":\"activityAvailabilityChange\",\"eventType\":\"activityAvailabilityChange\",\"definitionGroup\":\"custom\",\"properties\":[{\"property\":\"$.mode\",\"dataType\":\"string\",\"mappedProperty\":\"mode\"},{\"property\":\"$.availableActivities\",\"dataType\":\"array\",\"itemType\":\"string\",\"mappedProperty\":\"availableActivities\"},{\"property\":\"$.unavailableActivities\",\"dataType\":\"array\",\"itemType\":\"string\",\"mappedProperty\":\"unavailableActivities\"}]}],\"nextOffset\":0,\"previousOffset\":0,\"totalItemCount\":5}";++ // 3. stats_definition.json+ std::string statsDefStr = "{\"schemaVersion\":\"1.1\",\"npCommunicationId\":\"" + set.npCommId + "\",\"statsDefinitionRevision\":2011,\"statDefinitionArray\":[{\"statId\":1,\"definitionGroup\":\"autoGenState\",\"sourceId\":\"everPlayedActivities\",\"statName\":\"_autoGenState_everPlayedActivities\",\"dataType\":\"enumSet\",\"aggregation\":\"collection\",\"enumDefinition\":{\"sourceId\":\"activity_pattern1\",\"enumId\":1},\"initialValueArray\":[]}";++ for (const auto& item : set.items) {+ char buf[512];+ snprintf(buf, sizeof(buf),+ ",{\"statId\":%u,\"definitionGroup\":\"autoGenTrophy\",\"sourceId\":\"%04u\",\"statName\":\"_autoGenTrophy_%04u\",\"routes\":[{\"postEventInterface\":\"ps5SdkLibrary\",\"eventToStatsLocation\":\"ps5\"}],\"dataType\":\"uint64\",\"aggregation\":\"count\",\"maxValue\":\"1\",\"minValue\":\"0\",\"initialValue\":\"0\"}",+ 100 + item.trophyId, item.trophyId, item.trophyId);+ statsDefStr += buf;+ }+ statsDefStr += "]}";++ // 4. stats_extraction.json+ std::string statsExtStr = "{\"schemaVersion\":\"1.1\",\"npCommunicationId\":\"" + set.npCommId + "\",\"statsExtractionRevision\":2011,\"statsExtractionRuleArray\":[{\"ruleId\":1,\"definitionGroup\":\"autoGenState\",\"sourceId\":\"mp_matchStart\",\"condition\":{\"eventName\":\"_matchStart\"},\"action\":{\"input\":\"$._activityId\",\"output\":{\"statId\":1,\"statName\":\"_autoGenState_everPlayedActivities\",\"sourceId\":\"everPlayedActivities\"}}}";++ uint32_t ruleId = 100;+ for (const auto& item : set.items) {+ ++ruleId;+ char buf[512];+ snprintf(buf, sizeof(buf),+ ",{\"ruleId\":%u,\"definitionGroup\":\"autoGenTrophy\",\"sourceId\":\"%04u\",\"condition\":{\"eventName\":\"_UnlockTrophy\",\"property\":{\"path\":\"$._trophy_id\",\"comparator\":\"==\",\"value\":\"%u\"}},\"action\":{\"output\":{\"statId\":%u,\"statName\":\"_autoGenTrophy_%04u\",\"sourceId\":\"%04u\"}}}",+ ruleId, item.trophyId, item.trophyId, 100 + item.trophyId, item.trophyId, item.trophyId);+ statsExtStr += buf;+ }+ statsExtStr += "]}";++ struct Entry {+ std::string name;+ const uint8_t* data;+ size_t size;+ };+ std::vector<Entry> entries = {+ {"enum_definition.json", reinterpret_cast<const uint8_t*>(enumStr.data()), enumStr.size()},+ {"events_definition.json", reinterpret_cast<const uint8_t*>(eventsStr.data()), eventsStr.size()},+ {"stats_definition.json", reinterpret_cast<const uint8_t*>(statsDefStr.data()), statsDefStr.size()},+ {"stats_extraction.json", reinterpret_cast<const uint8_t*>(statsExtStr.data()), statsExtStr.size()}+ };++ const uint32_t numFiles = static_cast<uint32_t>(entries.size());+ const uint64_t headerSize = 0x60;+ const uint64_t tableSize = static_cast<uint64_t>(numFiles) * 64;+ uint64_t curOffset = (headerSize + tableSize + 15) & ~15ULL;++ std::vector<uint8_t> fileTable(tableSize, 0);+ std::vector<uint8_t> bodies;++ for (uint32_t i = 0; i < numFiles; ++i) {+ const auto& fe = entries[i];+ uint8_t* row = fileTable.data() + (i * 64);+ std::strncpy(reinterpret_cast<char*>(row), fe.name.c_str(), 31);+ writeBe64(row + 32, curOffset);+ writeBe64(row + 40, fe.size);++ bodies.insert(bodies.end(), fe.data, fe.data + fe.size);+ size_t pad = (16 - (fe.size % 16)) % 16;+ bodies.insert(bodies.end(), pad, 0);+ curOffset += (fe.size + pad);+ }++ uint64_t totalSize = curOffset;+ outUcp.assign(totalSize, 0);+ writeBe32(outUcp.data() + 0x00, 0xb228c60a);+ writeBe32(outUcp.data() + 0x04, 1);+ writeBe64(outUcp.data() + 0x08, totalSize);+ writeBe32(outUcp.data() + 0x10, numFiles);+ writeBe32(outUcp.data() + 0x14, 64);+ writeBe32(outUcp.data() + 0x18, 0);++ std::memcpy(outUcp.data() + headerSize, fileTable.data(), tableSize);+ std::memcpy(outUcp.data() + (headerSize + tableSize), bodies.data(), bodies.size());++ uint8_t sha1Digest[20] = {0};+ mbedtls_sha1(outUcp.data(), outUcp.size(), sha1Digest);+ std::memcpy(outUcp.data() + 0x1c, sha1Digest, 20);++ XC_LOGI("trophy builder: built uds.ucp for %s: %zu bytes", set.npCommId.c_str(), outUcp.size());+ return true;+}++bool buildTrpTitleDat(const TitleTrophySet& set, uint32_t userId, std::vector<uint8_t>& outDat,+ const uint8_t* ucpSha1,+ const std::vector<uint8_t>* existingDat) {+ outDat.clear();+ if (set.npCommId.empty()) return false;++ // Load existing unlocked trophies to preserve them 100% (append-only)+ std::map<uint32_t, ExistingTrophyRecord> existingTrophies;+ if (existingDat && !existingDat->empty()) {+ parseTrpTitleDat(existingDat->data(), existingDat->size(), existingTrophies);+ } else {+ char existingPath[256];+ snprintf(existingPath, sizeof(existingPath),+ "/user/home/%08x/trophy2/nobackup/data/%s/TRPTITLE.DAT",+ userId, set.npCommId.c_str());+ int eFd = ::open(existingPath, O_RDONLY);+ if (eFd >= 0) {+ struct stat st{};+ if (::fstat(eFd, &st) == 0 && st.st_size > 0) {+ std::vector<uint8_t> diskBuf(st.st_size);+ ssize_t n = ::read(eFd, diskBuf.data(), diskBuf.size());+ if (n > 0) {+ parseTrpTitleDat(diskBuf.data(), static_cast<size_t>(n), existingTrophies);+ }+ }+ ::close(eFd);+ }+ }++ // If ucpSha1 is not provided, compute it via buildUcp+ std::vector<uint8_t> computedSha1;+ if (!ucpSha1) {+ std::vector<uint8_t> tempUcp;+ if (buildUcp(set, tempUcp, &computedSha1)) {+ ucpSha1 = computedSha1.data();+ }+ }++ // Total count including Platinum (Trophy 0)+ const uint32_t N = static_cast<uint32_t>(set.items.size() + 1);++ const uint32_t TAG1_LEN = 0x30;+ const uint32_t TAG2_LEN = 0x60;+ const uint32_t TAG100_LEN = 0x40;+ const uint32_t TAG300_LEN = 0x480;+ const uint32_t TAG400_LEN = 0x90;+ const uint32_t TAG500_ITEM_LEN = 0xc0;+ const uint32_t TAG600_LEN = 0x1f0;+ const uint32_t TAG700_LEN = 0xb0;+ const uint32_t TAG800_ITEM_LEN = 0x50;++ const uint64_t tag1_rel = 0x150;+ const uint64_t tag2_rel = tag1_rel + 0x10 + TAG1_LEN; // 0x190+ const uint64_t tag100_rel = tag2_rel + 0x10 + TAG2_LEN; // 0x200+ const uint64_t tag300_rel = tag100_rel + 0x10 + TAG100_LEN; // 0x250+ const uint64_t tag400_rel = tag300_rel + 0x10 + TAG300_LEN; // 0x6e0+ const uint64_t tag500_rel = tag400_rel + 0x10 + TAG400_LEN; // 0x780+ const uint64_t tag600_rel = tag500_rel + static_cast<uint64_t>(N) * (0x10 + TAG500_ITEM_LEN); // 0x780 + N * 0xd0+ const uint64_t tag700_rel = tag600_rel + 0x10 + TAG600_LEN;+ const uint64_t tag800_rel = tag700_rel + 0x10 + TAG700_LEN;++ const uint64_t tag800_end = 0x60 + tag800_rel + static_cast<uint64_t>(N) * (0x10 + TAG800_ITEM_LEN);+ const uint64_t total_size = tag800_end + 0x40; // 0x20 pad + 0x20 signature++ outDat.assign(total_size, 0);+ uint8_t* p = outDat.data();++ // 1. T2PD Header+ std::memcpy(p + 0x00, "T2PD", 4);+ writeBe32(p + 0x04, 0x00010000);+ writeBe32(p + 0x08, 0);+ writeBe32(p + 0x0c, 0x0420);+ writeBe64(p + 0x20, 9);++ // 2. T2TD Header+ std::memcpy(p + 0x40, "T2TD", 4);+ writeBe32(p + 0x44, 0x00010000);+ writeBe32(p + 0x48, 9);++ // 3. Descriptors+ struct Desc {+ uint32_t tag;+ uint32_t len;+ uint32_t count;+ uint64_t rel_off;+ };+ Desc descs[9] = {+ {0x0001, TAG1_LEN, 1, tag1_rel},+ {0x0002, TAG2_LEN, 1, tag2_rel},+ {0x0100, TAG100_LEN, 1, tag100_rel},+ {0x0300, TAG300_LEN, 1, tag300_rel},+ {0x0400, TAG400_LEN, 1, tag400_rel},+ {0x0500, TAG500_ITEM_LEN, N, tag500_rel},+ {0x0600, TAG600_LEN, 1, tag600_rel},+ {0x0700, TAG700_LEN, 1, tag700_rel},+ {0x0800, TAG800_ITEM_LEN, N, tag800_rel},+ };+ for (int i = 0; i < 9; ++i) {+ uint8_t* d = p + 0x70 + (i * 32);+ writeBe32(d + 0, descs[i].tag);+ writeBe32(d + 4, descs[i].len);+ writeBe32(d + 8, 1); // unk = 1+ writeBe32(d + 12, descs[i].count);+ writeBe64(d + 16, descs[i].rel_off);+ writeBe64(d + 24, 0);+ }++ // 4. Tag 1 at 0x190+ writeBe32(p + 0x190, 0x0001);+ writeBe32(p + 0x194, TAG1_LEN);+ std::memcpy(p + 0x1a0, kTag1PayloadTemplate, sizeof(kTag1PayloadTemplate));++ // 5. Tag 2 at 0x1d0+ writeBe32(p + 0x1d0, 0x0002);+ writeBe32(p + 0x1d4, TAG2_LEN);+ std::memcpy(p + 0x1e0, kTag2PayloadTemplate, sizeof(kTag2PayloadTemplate));+ writeBe32(p + 0x1e0 + 0x28, userId);++ // 6. Tag 0x0100 at 0x240+ writeBe32(p + 0x240, 0x0100);+ writeBe32(p + 0x244, TAG100_LEN);+ std::memcpy(p + 0x250, kTag100PayloadTemplate, sizeof(kTag100PayloadTemplate));+ if (ucpSha1) {+ std::memcpy(p + 0x250, ucpSha1, 20);+ }++ // 7. Tag 0x0300 at 0x290+ writeBe32(p + 0x290, 0x0300);+ writeBe32(p + 0x294, TAG300_LEN);+ std::memcpy(p + 0x2a0, kTag300PayloadTemplate, sizeof(kTag300PayloadTemplate));+ std::memcpy(p + 0x2a0 + 0x000, set.npCommId.c_str(), std::min(set.npCommId.size(), size_t(16)));+ std::memcpy(p + 0x2a0 + 0x0b0, set.npCommId.c_str(), std::min(set.npCommId.size(), size_t(16)));+ writeBe32(p + 0x2a0 + 0xd8, 780785);++ // Bitmasks for Tag 0x0300+ uint8_t total_mask[32] = {0};+ uint8_t unlocked_mask[32] = {0};+ uint8_t bronze_mask[32] = {0};+ uint8_t silver_mask[32] = {0};+ uint8_t gold_mask[32] = {0};++ total_mask[0] |= 1; // Plat++ struct FinalTrophyState {+ bool unlocked = false;+ uint64_t timestamp = 0;+ };+ std::vector<FinalTrophyState> finalStates(set.items.size());+ size_t unlockedNonPlatCount = 0;++ for (size_t idx = 0; idx < set.items.size(); ++idx) {+ uint32_t tid = static_cast<uint32_t>(idx + 1);+ uint32_t bIdx = tid / 8;+ uint32_t bit = tid % 8;+ if (bIdx < 32) {+ total_mask[bIdx] |= (1 << bit);+ if (set.items[idx].grade == TrophyGrade::Bronze) {+ bronze_mask[bIdx] |= (1 << bit);+ } else if (set.items[idx].grade == TrophyGrade::Silver) {+ silver_mask[bIdx] |= (1 << bit);+ } else if (set.items[idx].grade == TrophyGrade::Gold) {+ gold_mask[bIdx] |= (1 << bit);+ }+ }++ bool isUnlocked = false;+ uint64_t trophyTs = 0x00000000ffffffffULL;++ auto eIt = existingTrophies.find(tid);+ if (eIt != existingTrophies.end() && eIt->second.state == 1) {+ // 100% PRESERVE existing unlocked state and original timestamp from console!+ isUnlocked = true;+ trophyTs = eIt->second.timestamp;+ } else if (set.items[idx].unlocked) {+ // Newly unlocked from Xbox Live!+ isUnlocked = true;+ uint64_t nowUs = static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(+ std::chrono::system_clock::now().time_since_epoch()).count());+ trophyTs = (nowUs > 0) ? nowUs : (1730400000000000ULL + tid * 1000000ULL);+ }++ finalStates[idx] = {isUnlocked, trophyTs};+ if (isUnlocked) {+ unlockedNonPlatCount++;+ if (bIdx < 32) {+ unlocked_mask[bIdx] |= (1 << bit);+ }+ }+ }++ // Trophy 0: Platinum+ bool platUnlocked = false;+ uint64_t platTs = 0xffffffffffffffffULL;+ auto pIt = existingTrophies.find(0);+ if (pIt != existingTrophies.end() && pIt->second.state == 1) {+ platUnlocked = true;+ platTs = pIt->second.timestamp;+ } else if (unlockedNonPlatCount == set.items.size() && set.items.size() > 0) {+ platUnlocked = true;+ platTs = static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(+ std::chrono::system_clock::now().time_since_epoch()).count());+ }++ if (platUnlocked) {+ unlocked_mask[0] |= 1;+ }++ std::memcpy(p + 0x2a0 + 0x0f0, total_mask, 32);+ std::memcpy(p + 0x2a0 + 0x170, unlocked_mask, 32);+ std::memcpy(p + 0x2a0 + 0x290, bronze_mask, 32);+ std::memcpy(p + 0x2a0 + 0x310, silver_mask, 32);+ std::memcpy(p + 0x2a0 + 0x390, gold_mask, 32);++ // 8. Tag 0x0400 at 0x740+ writeBe32(p + 0x740, 0x0400);+ writeBe32(p + 0x744, TAG400_LEN);+ std::memcpy(p + 0x750 + 0x10, total_mask, 32);++ // 9. Tag 0x0500 at 0x7e0 (N items * 208 bytes)+ const uint64_t base500 = 0x7e0;+ // Trophy 0: Platinum+ writeBe32(p + base500 + 0, 0x0500);+ writeBe32(p + base500 + 4, TAG500_ITEM_LEN);+ writeBe32(p + base500 + 16, 0); // tid = 0+ writeBe32(p + base500 + 20, 1); // grade = 1 (Plat)+ writeBe32(p + base500 + 24, platUnlocked ? 1 : 0);+ writeBe64(p + base500 + 32, platTs);++ uint8_t total_mask_no_plat[32];+ std::memcpy(total_mask_no_plat, total_mask, 32);+ total_mask_no_plat[0] &= ~1;+ std::memcpy(p + base500 + 0x50, total_mask_no_plat, 32);++ // Trophies 1..N-1+ for (size_t idx = 0; idx < set.items.size(); ++idx) {+ uint32_t tid = static_cast<uint32_t>(idx + 1);+ uint64_t pos = base500 + (static_cast<uint64_t>(tid) * 208);+ const auto& item = set.items[idx];+ const auto& st = finalStates[idx];+ uint32_t gVal = 4;+ if (item.grade == TrophyGrade::Platinum) gVal = 1;+ else if (item.grade == TrophyGrade::Gold) gVal = 2;+ else if (item.grade == TrophyGrade::Silver) gVal = 3;++ writeBe32(p + pos + 0, 0x0500);+ writeBe32(p + pos + 4, TAG500_ITEM_LEN);+ writeBe32(p + pos + 16, tid);+ writeBe32(p + pos + 20, gVal);+ writeBe32(p + pos + 24, st.unlocked ? 1 : 0);+ writeBe64(p + pos + 32, st.timestamp);++ // Template flags+ writeBe32(p + pos + 16 + 0x20, 6);+ writeBe32(p + pos + 16 + 0x24, 4);+ writeBe32(p + pos + 16 + 0x28, 2);+ writeBe32(p + pos + 16 + 0x2c, 0);+ writeBe32(p + pos + 16 + 0x30, 0x55000000);+ writeBe32(p + pos + 16 + 0x34, 8);+ writeBe32(p + pos + 16 + 0x38, 0);+ writeBe32(p + pos + 16 + 0x3c, 1);+ }++ // 10. Tag 0x0600+ uint64_t pos600 = 0x60 + tag600_rel;+ writeBe32(p + pos600 + 0, 0x0600);+ writeBe32(p + pos600 + 4, TAG600_LEN);+ std::memcpy(p + pos600 + 16, kTag600PayloadTemplate, sizeof(kTag600PayloadTemplate));++ // 11. Tag 0x0700+ uint64_t pos700 = 0x60 + tag700_rel;+ writeBe32(p + pos700 + 0, 0x0700);+ writeBe32(p + pos700 + 4, TAG700_LEN);++ // 12. Tag 0x0800+ uint64_t pos800 = 0x60 + tag800_rel;+ for (uint32_t tid = 0; tid < N; ++tid) {+ uint64_t entryPos = pos800 + (static_cast<uint64_t>(tid) * 96);+ writeBe32(p + entryPos + 0, 0x0800);+ writeBe32(p + entryPos + 4, TAG800_ITEM_LEN);+ writeBe32(p + entryPos + 16, tid);+ }++ // 13. Trailer signature+ std::memcpy(p + total_size - 32, kTrailerSignatureTemplate, 32);++ XC_LOGI("trophy builder: built TRPTITLE.DAT for %s (%s, user=0x%08x): %zu bytes, %u trophies (%zu unlocked)",+ set.titleName.c_str(), set.npCommId.c_str(), userId, outDat.size(), N,+ unlockedNonPlatCount + (platUnlocked ? 1 : 0));+ return true;+}++std::string buildParamJson(const std::string& titleId, const std::string& titleName) {+ std::string contentId;+ std::string conceptId;+ if (titleId == "PPSA01922") {+ contentId = "UP1477-PPSA01922_00-FORTNITECORE0001";+ conceptId = "210118";+ } else {+ contentId = "UP0001-" + titleId + "_00-0000000000000000";+ conceptId = "10004542";+ }+ std::string name = titleName.empty() ? "Fortnite" : titleName;+ std::string escapedName;+ for (char c : name) {+ if (c == '"') escapedName += "\\\"";+ else escapedName += c;+ }+ char buf[2048];+ snprintf(buf, sizeof(buf),+ "{\n"+ " \"ageLevel\": {\n"+ " \"default\": 12\n"+ " },\n"+ " \"appType\": 1,\n"+ " \"applicationCategoryType\": 0,\n"+ " \"applicationDrmType\": \"standard\",\n"+ " \"attribute\": 0,\n"+ " \"attribute2\": 0,\n"+ " \"attribute3\": 1835012,\n"+ " \"conceptId\": \"%s\",\n"+ " \"contentBadgeType\": 1,\n"+ " \"contentId\": \"%s\",\n"+ " \"contentVersion\": \"01.000.000\",\n"+ " \"downloadDataSize\": 0,\n"+ " \"gameIntent\": {\n"+ " \"permittedIntents\": [\n"+ " {\n"+ " \"intentType\": \"launchActivity\"\n"+ " }\n"+ " ]\n"+ " },\n"+ " \"localizedParameters\": {\n"+ " \"defaultLanguage\": \"en-US\",\n"+ " \"en-US\": {\n"+ " \"titleName\": \"%s\"\n"+ " },\n"+ " \"pt-BR\": {\n"+ " \"titleName\": \"%s\"\n"+ " }\n"+ " },\n"+ " \"masterVersion\": \"01.00\",\n"+ " \"pubtools\": {\n"+ " \"creationDate\": \"2026-10-31 00:00:00\",\n"+ " \"loudnessSnd0\": \"-33.02\",\n"+ " \"toolVersion\": \"3.13\"\n"+ " },\n"+ " \"requiredSystemSoftwareVersion\": \"0x1220000000000000\",\n"+ " \"sdkVersion\": \"0x1000000000000000\",\n"+ " \"titleId\": \"%s\",\n"+ " \"versionFileUri\": \"\"\n"+ "}\n",+ conceptId.c_str(), contentId.c_str(), escapedName.c_str(), escapedName.c_str(), titleId.c_str());+ return std::string(buf);+}++bool deployTrophyPack(const TitleTrophySet& set, uint32_t userId) {+ if (set.npCommId.empty()) return false;++ std::vector<uint8_t> ucpBytes;+ std::vector<uint8_t> ucpSha1;+ if (!buildUcp(set, ucpBytes, &ucpSha1)) return false;++ std::vector<uint8_t> npBindBytes;+ if (!buildNpBind(set.npCommId, npBindBytes)) return false;++ std::vector<uint8_t> udsBytes;+ buildUdsUcp(set, udsBytes);++ // 1. Conf dir: /user/trophy2/nobackup/conf/<NPWR>/TROPHY.UCP+ std::string confDir = "/user/trophy2/nobackup/conf/" + set.npCommId;+ ensureDir(confDir);+ writeRawFile(confDir + "/TROPHY.UCP", ucpBytes.data(), ucpBytes.size());++ // 2. Data dir: /user/home/<userId>/trophy2/nobackup/data/<NPWR>/TRPTITLE.DAT+ // buildTrpTitleDat automatically merges existing disk trophies and timestamps (append-only)+ std::vector<uint8_t> datBytes;+ if (buildTrpTitleDat(set, userId, datBytes, ucpSha1.data())) {+ char dataDirBuf[256];+ snprintf(dataDirBuf, sizeof(dataDirBuf), "/user/home/%08x/trophy2/nobackup/data/%s",+ userId, set.npCommId.c_str());+ std::string dataDir = dataDirBuf;+ ensureDir(dataDir);+ writeRawFile(dataDir + "/TRPTITLE.DAT", datBytes.data(), datBytes.size());+ }++ // 3. Target appmeta dirs for homebrew runner+ const std::string appMetaDirs[] = {+ "/system_data/priv/appmeta/PPSA99810/trophy2",+ "/user/appmeta/PPSA99810/trophy2",+ "/user/app/PPSA99810/sce_sys/trophy2",+ "/data/homebrew/PPSA99810/sce_sys/trophy2"+ };++ for (const auto& dir : appMetaDirs) {+ ensureDir(dir);+ writeRawFile(dir + "/trophy00.ucp", ucpBytes.data(), ucpBytes.size());+ writeRawFile(dir + "/npbind.dat", npBindBytes.data(), npBindBytes.size());+ }++ // 4. Game Title appmeta dirs (PPSA01922 and set.sonyTitleId)+ std::vector<std::string> gameTitles;+ std::string targetTitle = set.sonyTitleId.empty() ? "PPSA01922" : set.sonyTitleId;+ if (!targetTitle.empty() && targetTitle != "PPSA99810") {+ gameTitles.push_back(targetTitle);+ }+ if (std::find(gameTitles.begin(), gameTitles.end(), "PPSA01922") == gameTitles.end()) {+ gameTitles.push_back("PPSA01922");+ }++ for (const auto& tid : gameTitles) {+ std::string pJson = buildParamJson(tid, (tid == targetTitle) ? set.titleName : "Fortnite");+ std::vector<uint8_t> npTitleBytes;+ buildNpTitleDat(tid, npTitleBytes);++ const std::string titleDirs[] = {+ "/system_data/priv/appmeta/" + tid,+ "/user/appmeta/" + tid,+ "/user/app/" + tid + "/sce_sys"+ };+ for (const auto& d : titleDirs) {+ ensureDir(d);+ // param.json+ writeRawFile(d + "/param.json", pJson.data(), pJson.size());+ // nptitle.dat (160 bytes, Magic NPTD, Title ID <tid>_00)+ writeRawFile(d + "/nptitle.dat", npTitleBytes.data(), npTitleBytes.size());+ // icon0.png+ std::string iconPath = d + "/icon0.png";+ struct stat st{};+ if (::stat(iconPath.c_str(), &st) != 0 || st.st_size == 0) {+ int srcFd = ::open("/tmp/fortnite_icon0.png", O_RDONLY);+ if (srcFd >= 0) {+ std::vector<uint8_t> buf(200000);+ ssize_t n = ::read(srcFd, buf.data(), buf.size());+ ::close(srcFd);+ if (n > 0) {+ writeRawFile(iconPath, buf.data(), static_cast<size_t>(n));+ } else {+ writeRawFile(iconPath, kDefaultIconPng, sizeof(kDefaultIconPng));+ }+ } else {+ writeRawFile(iconPath, kDefaultIconPng, sizeof(kDefaultIconPng));+ }+ }+ // trophy2 subdirectory: trophy00.ucp and npbind.dat+ std::string t2 = d + "/trophy2";+ ensureDir(t2);+ writeRawFile(t2 + "/trophy00.ucp", ucpBytes.data(), ucpBytes.size());+ writeRawFile(t2 + "/npbind.dat", npBindBytes.data(), npBindBytes.size());++ // uds subdirectory: uds00.ucp and npbind.dat+ std::string uds = d + "/uds";+ ensureDir(uds);+ writeRawFile(uds + "/uds00.ucp", udsBytes.data(), udsBytes.size());+ writeRawFile(uds + "/npbind.dat", npBindBytes.data(), npBindBytes.size());+ }+ }++ // 5. UDS conf dir: /user/np_uds/nobackup/conf/<NPWR>/uds.ucp+ std::string udsConfDir = "/user/np_uds/nobackup/conf/" + set.npCommId;+ ensureDir(udsConfDir);+ writeRawFile(udsConfDir + "/uds.ucp", udsBytes.data(), udsBytes.size());++ ::sync();+ ::usleep(100000); // 100ms settle for kernel filesystem caches+ XC_LOGI("trophy builder: deployed trophy pack & TRPTITLE.DAT for %s (%s, user=0x%08x) to all system dirs",+ set.titleName.c_str(), set.npCommId.c_str(), userId);+ return true;+}+++} // namespace xc::trophydiff --git a/src/trophy/trophy_builder.h b/src/trophy/trophy_builder.hnew file mode 100644index 0000000..12e7c65--- /dev/null+++ b/src/trophy/trophy_builder.h@@ -0,0 +1,51 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++#include "trophy/trophy_types.h"+#include <cstdint>+#include <map>+#include <string>+#include <vector>++namespace xc::trophy {++struct ExistingTrophyRecord {+ uint32_t trophyId = 0;+ uint32_t grade = 0;+ uint32_t state = 0; // 0 = locked, 1 = unlocked+ uint64_t timestamp = 0;+};++// Parses a TRPTITLE.DAT buffer to extract existing trophy unlock records and timestamps.+bool parseTrpTitleDat(const uint8_t* data, size_t size, std::map<uint32_t, ExistingTrophyRecord>& outTrophies);++// Builds an nptitle.dat file (160 bytes) for the given titleId.+bool buildNpTitleDat(const std::string& titleId, std::vector<uint8_t>& outNpTitle);++// Builds a Sony PS5 Trophy 2 package (TROPHY.UCP) from a TitleTrophySet.+// If outSha1 is non-null, receives the 20-byte SHA-1 digest written into the UCP header.+bool buildUcp(const TitleTrophySet& set, std::vector<uint8_t>& outUcp, std::vector<uint8_t>* outSha1 = nullptr);++// Builds an npbind.dat file for the given npCommId.+bool buildNpBind(const std::string& npCommId, std::vector<uint8_t>& outNpBind);++// Builds a Sony Universal Data System package (uds.ucp) for the given title.+bool buildUdsUcp(const TitleTrophySet& set, std::vector<uint8_t>& outUdsUcp);++// Builds a PlayStation 5 TRPTITLE.DAT database file from a TitleTrophySet for the given user.+// If ucpSha1 is non-null, writes the 20-byte SHA-1 digest into Tag 0x0100 (matching TROPHY.UCP).+// If existingDat is non-null, parses and preserves existing trophies and timestamps from it.+// If existingDat is null, attempts to read existing TRPTITLE.DAT from /user/home/<userId>/trophy2/nobackup/data/<npCommId>/TRPTITLE.DAT.+bool buildTrpTitleDat(const TitleTrophySet& set, uint32_t userId, std::vector<uint8_t>& outDat,+ const uint8_t* ucpSha1 = nullptr,+ const std::vector<uint8_t>* existingDat = nullptr);++// Builds a valid PlayStation 5 param.json metadata buffer for the given titleId and titleName.+std::string buildParamJson(const std::string& titleId, const std::string& titleName);++// Deploys the generated TROPHY.UCP, npbind.dat, TRPTITLE.DAT, and param.json to all required system directories on PS5.+bool deployTrophyPack(const TitleTrophySet& set, uint32_t userId = 0x1ea2f4da);++} // namespace xc::trophy+diff --git a/src/trophy/trophy_registry.cpp b/src/trophy/trophy_registry.cppnew file mode 100644index 0000000..7527494--- /dev/null+++ b/src/trophy/trophy_registry.cpp@@ -0,0 +1,119 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "trophy/trophy_registry.h"+#include "trophy/trophy_rules.h"++#include <algorithm>+#include <cctype>+#include <cstdio>+#include <iomanip>+#include <sstream>++namespace xc::trophy {++namespace {++const KnownTitleMapping s_knownTitles[] = {+ // Fortnite -> Official PS5 NPWR+ {"267695549", "BT5P2X999VH2", "Fortnite", "PPSA01922", "NPWR20561_00"},+ // Minecraft -> Official PS5 NPWR+ {"1828326430", "9NBLGGH537BL", "Minecraft", "PPSA03350", "NPWR18283_00"},+ // Sea of Thieves -> Official PS5 NPWR+ {"1717113201", "9P2N57MC619K", "Sea of Thieves", "PPSA16155", "NPWR17171_00"},+ // Resident Evil 2 / Biohazard+ {"2108722049", "9N5953FMWP5L", "Resident Evil", "PPSA04400", "NPWR53376_00"},+ // Cyberpunk 2077+ {"222473492", "BX3M8ZSZMFN5", "Cyberpunk 2077", "PPSA03974", "NPWR17597_00"},+ {"1492080358", "BX3M8ZSZMFN5", "Cyberpunk 2077", "PPSA03974", "NPWR17597_00"},+ // Animal Well+ {"22520", "ANIMALWELL001", "ANIMAL WELL", "PPSA22520", "NPWR36759_00"},+};++uint32_t fnv1a(const std::string& str) {+ uint32_t hash = 2166136261u;+ for (char c : str) {+ hash ^= static_cast<uint8_t>(c);+ hash *= 16777619u;+ }+ return hash;+}++} // namespace++const KnownTitleMapping* findKnownTitle(const std::string& xboxTitleId, const std::string& productId) {+ for (const auto& item : s_knownTitles) {+ if (!xboxTitleId.empty() && item.xboxTitleId == xboxTitleId) return &item;+ if (!productId.empty() && item.productId == productId) return &item;+ }+ return nullptr;+}++std::string generateNpCommId(const std::string& xboxTitleId) {+ uint32_t h = fnv1a(xboxTitleId);+ uint32_t num = 80000 + (h % 10000); // NPWR80000_00 .. NPWR89999_00+ char buf[16];+ snprintf(buf, sizeof(buf), "NPWR%05u_00", num);+ return std::string(buf);+}++std::string generateSonyTitleId(const std::string& xboxTitleId) {+ uint32_t h = fnv1a(xboxTitleId);+ uint32_t num = 80000 + (h % 10000);+ char buf[16];+ snprintf(buf, sizeof(buf), "PPSA%05u", num);+ return std::string(buf);+}++std::string normalizeTrophyName(const std::string& name) {+ std::string out;+ out.reserve(name.size());+ for (char c : name) {+ if (std::isalnum(static_cast<unsigned char>(c))) {+ out.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(c))));+ }+ }+ return out;+}++TitleTrophySet resolveTitleSet(const std::string& xboxTitleId, const std::string& productId,+ const std::string& titleName, const std::vector<xcloud::Achievement>& achievements) {+ TitleTrophySet set;+ set.xboxTitleId = xboxTitleId;+ set.productId = productId;+ set.titleName = titleName.empty() ? ("Xbox Title " + xboxTitleId) : titleName;++ const KnownTitleMapping* known = findKnownTitle(xboxTitleId, productId);+ if (known) {+ set.npCommId = known->npCommId;+ set.sonyTitleId = known->sonyTitleId;+ if (!known->titleName.empty()) set.titleName = known->titleName;+ } else {+ std::string seed = xboxTitleId.empty() ? (productId.empty() ? titleName : productId) : xboxTitleId;+ set.npCommId = generateNpCommId(seed);+ set.sonyTitleId = generateSonyTitleId(seed);+ }++ set.items.reserve(achievements.size());+ for (size_t i = 0; i < achievements.size(); ++i) {+ const auto& ach = achievements[i];+ TrophyDef def;+ def.trophyId = static_cast<int>(i + 1); // 1-based trophy id+ def.name = ach.name;+ def.description = ach.description.empty() ? ach.lockedDescription : ach.description;+ def.iconUrl = ach.iconUrl;+ def.gamerscore = ach.gamerscore;+ def.grade = scoreToGrade(ach.gamerscore);+ def.unlocked = ach.unlocked;+ def.timeUnlocked = ach.timeUnlocked;++ if (def.unlocked) {+ set.unlockedCount++;+ }+ set.items.push_back(std::move(def));+ }+ set.totalCount = static_cast<int>(set.items.size());++ return set;+}++} // namespace xc::trophydiff --git a/src/trophy/trophy_registry.h b/src/trophy/trophy_registry.hnew file mode 100644index 0000000..b7f2545--- /dev/null+++ b/src/trophy/trophy_registry.h@@ -0,0 +1,37 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++#include "trophy/trophy_types.h"+#include "xcloud/achievements.h"++#include <string>+#include <vector>++namespace xc::trophy {++struct KnownTitleMapping {+ std::string xboxTitleId;+ std::string productId;+ std::string titleName;+ std::string sonyTitleId;+ std::string npCommId;+};++// Looks up a known cross-platform title (Scenario A) by Xbox Title ID or Store Product ID.+const KnownTitleMapping* findKnownTitle(const std::string& xboxTitleId, const std::string& productId = {});++// Generates a deterministic virtual NP Communication ID for Xbox exclusives (Scenario B), e.g. NPWR9XXXX_00.+std::string generateNpCommId(const std::string& xboxTitleId);++// Generates a deterministic virtual PlayStation Title ID for Xbox exclusives, e.g. PPSA9XXXX.+std::string generateSonyTitleId(const std::string& xboxTitleId);++// Resolves or constructs a TitleTrophySet given title information and Xbox Live achievements.+TitleTrophySet resolveTitleSet(const std::string& xboxTitleId, const std::string& productId,+ const std::string& titleName, const std::vector<xcloud::Achievement>& achievements);++// Normalizes an achievement or trophy name for string correlation.+std::string normalizeTrophyName(const std::string& name);++} // namespace xc::trophydiff --git a/src/trophy/trophy_rules.cpp b/src/trophy/trophy_rules.cppnew file mode 100644index 0000000..d97b966--- /dev/null+++ b/src/trophy/trophy_rules.cpp@@ -0,0 +1,27 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "trophy/trophy_rules.h"++namespace xc::trophy {++const char* gradeToString(TrophyGrade grade) {+ switch (grade) {+ case TrophyGrade::Bronze: return "Bronze";+ case TrophyGrade::Silver: return "Silver";+ case TrophyGrade::Gold: return "Gold";+ case TrophyGrade::Platinum: return "Platinum";+ }+ return "Bronze";+}++int gradeToPoints(TrophyGrade grade) {+ switch (grade) {+ case TrophyGrade::Bronze: return 15;+ case TrophyGrade::Silver: return 30;+ case TrophyGrade::Gold: return 90;+ case TrophyGrade::Platinum: return 300;+ }+ return 15;+}++} // namespace xc::trophydiff --git a/src/trophy/trophy_rules.h b/src/trophy/trophy_rules.hnew file mode 100644index 0000000..0f45ede--- /dev/null+++ b/src/trophy/trophy_rules.h@@ -0,0 +1,28 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++#include "trophy/trophy_types.h"++namespace xc::trophy {++// Gamerscore to PlayStation TrophyGrade conversion:+// <= 50G -> Bronze+// 55G..99G -> Silver+// >= 100G -> Gold+inline TrophyGrade scoreToGrade(int gamerscore) {+ if (gamerscore >= 100) return TrophyGrade::Gold;+ if (gamerscore >= 55) return TrophyGrade::Silver;+ return TrophyGrade::Bronze;+}++// 100% achievements unlocked awards Platinum automatically+inline bool hasEarnedPlatinum(int unlockedCount, int totalCount) {+ return (totalCount > 0 && unlockedCount >= totalCount);+}++const char* gradeToString(TrophyGrade grade);++int gradeToPoints(TrophyGrade grade);++} // namespace xc::trophydiff --git a/src/trophy/trophy_sync.cpp b/src/trophy/trophy_sync.cppnew file mode 100644index 0000000..b4f9d60--- /dev/null+++ b/src/trophy/trophy_sync.cpp@@ -0,0 +1,273 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "trophy/trophy_sync.h"+#include "trophy/trophy_registry.h"+#include "trophy/trophy_rules.h"+#include "platform/platform.h"+#include "ui/strings.h"+#include "util/json.h"+#include "util/log.h"+#include "xcloud/achievements.h"++#include <chrono>+#include <set>+#include <thread>+#include <unordered_set>+#include <sys/stat.h>++namespace xc::trophy {++TrophySyncEngine::TrophySyncEngine()+ : backend_(createPlatformTrophyBackend()) {}++TrophySyncEngine::TrophySyncEngine(std::unique_ptr<ITrophyBackend> backend)+ : backend_(std::move(backend)) {}++TrophySyncEngine::~TrophySyncEngine() = default;++void TrophySyncEngine::setBackend(std::unique_ptr<ITrophyBackend> backend) {+ std::lock_guard<std::mutex> lock(mutex_);+ backend_ = std::move(backend);+ initialized_ = false;+}++std::string TrophySyncEngine::trophyCacheDir() const {+ std::string base = platform::dataDir();+ if (base.empty()) base = ".";+ std::string dir = base + "/trophies";+ ::mkdir(dir.c_str(), 0777);+ return dir;+}++std::string TrophySyncEngine::trophyCachePath(const std::string& xboxTitleId) const {+ return trophyCacheDir() + "/" + xboxTitleId + ".json";+}++bool TrophySyncEngine::init(uint32_t userId) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!backend_) backend_.reset(createPlatformTrophyBackend());+ if (backend_) {+ initialized_ = backend_->init(userId);+ }+ return initialized_;+}++bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const std::string& xuid,+ const std::string& xboxTitleId, const std::string& titleName,+ int& newlyUnlocked, std::string& err) {+ newlyUnlocked = 0;+ if (xblAuth.empty()) {+ err = "xblAuth empty";+ return false;+ }+ if (xboxTitleId.empty()) {+ err = "xboxTitleId empty";+ return false;+ }++ struct SyncGuard {+ std::atomic<bool>& f;+ SyncGuard(std::atomic<bool>& flag) : f(flag) { f = true; }+ ~SyncGuard() { f = false; }+ } guard(syncing_);++ std::lock_guard<std::mutex> lock(mutex_);+ if (!initialized_) {+ if (!backend_) backend_.reset(createPlatformTrophyBackend());+ if (backend_) initialized_ = backend_->init(0);+ }++ // 1. Query Xbox Live achievements+ xcloud::TitleAchievements ach;+ if (!xcloud::fetchTitleAchievements(xblAuth, xuid, xboxTitleId, ach, err, ui::gameLocale())) {+ XC_LOGW("trophy sync: fetchTitleAchievements failed for %s (%s): %s",+ titleName.c_str(), xboxTitleId.c_str(), err.c_str());+ return false;+ }++ // 2. Resolve trophy set mapping+ TitleTrophySet titleSet = resolveTitleSet(xboxTitleId, "", titleName, ach.items);++ // 3. Load local cache snapshot+ std::set<std::string> prevUnlocked;+ std::string cacheFile = trophyCachePath(xboxTitleId);+ std::string cacheContent;+ if (platform::readFile(cacheFile, cacheContent)) {+ if (auto j = json::parse(cacheContent); j && j->isObject()) {+ for (const auto& item : (*j)["unlockedIds"].items()) {+ if (item.isString()) prevUnlocked.insert(item.str());+ }+ }+ }++ // 4. Register title with backend+ if (backend_) {+ backend_->registerTitle(titleSet);+ }++ // 5. Compare achievements and unlock new trophies+ bool platinumAwarded = prevUnlocked.count("__PLATINUM__") > 0;+ for (size_t i = 0; i < ach.items.size() && i < titleSet.items.size(); ++i) {+ const auto& a = ach.items[i];+ const auto& def = titleSet.items[i];+ if (a.unlocked) {+ std::string key = a.id.empty() ? std::to_string(def.trophyId) : a.id;+ bool alreadyInBackend = backend_ ? backend_->isTrophyUnlocked(titleSet.npCommId, def.trophyId) : false;+ if (prevUnlocked.count(key) == 0 || !alreadyInBackend) {+ bool unlockedOk = true;+ if (backend_) {+ unlockedOk = backend_->unlockTrophy(titleSet.npCommId, def.trophyId, def.grade, def.name);+ }+ if (unlockedOk) {+ prevUnlocked.insert(key);+ newlyUnlocked++;+ }+ }+ }+ }++ // 5. Automatic Platinum award on 100% completion+ if (!platinumAwarded && hasEarnedPlatinum(ach.unlockedCount, ach.totalCount)) {+ XC_LOGI("trophy sync: 100%% achievements obtained for %s! Awarding Platinum trophy.",+ titleSet.titleName.c_str());+ bool platOk = true;+ if (backend_) {+ platOk = backend_->unlockTrophy(titleSet.npCommId, kPlatinumTrophyId, TrophyGrade::Platinum, "Platina: " + titleSet.titleName);+ }+ if (platOk) {+ prevUnlocked.insert("__PLATINUM__");+ newlyUnlocked++;+ }+ }++ // 6. Flush backend state to commit TRPTITLE.DAT to the PlayStation profile database+ if (backend_) {+ backend_->flush();+ }++ // 7. Save updated cache atomically with rich profile information+ json::Value out = json::Value::object();+ out.set("xboxTitleId", xboxTitleId);+ out.set("npCommId", titleSet.npCommId);+ out.set("sonyTitleId", titleSet.sonyTitleId);+ out.set("titleName", titleSet.titleName);+ out.set("unlockedCount", static_cast<int64_t>(ach.unlockedCount));+ out.set("totalCount", static_cast<int64_t>(ach.totalCount));+ out.set("unlockedGamerscore", static_cast<int64_t>(ach.unlockedGamerscore));+ out.set("totalGamerscore", static_cast<int64_t>(ach.totalGamerscore));+ out.set("lastSync", static_cast<int64_t>(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())));++ json::Value arr = json::Value::array();+ for (const auto& id : prevUnlocked) {+ arr.push(id);+ }+ out.set("unlockedIds", std::move(arr));++ json::Value trophiesArr = json::Value::array();+ for (const auto& def : titleSet.items) {+ json::Value t = json::Value::object();+ t.set("id", static_cast<int64_t>(def.trophyId));+ t.set("name", def.name);+ t.set("description", def.description);+ t.set("grade", gradeToString(def.grade));+ t.set("gamerscore", static_cast<int64_t>(def.gamerscore));+ t.set("unlocked", def.unlocked);+ if (!def.iconUrl.empty()) t.set("iconUrl", def.iconUrl);+ if (!def.timeUnlocked.empty()) t.set("timeUnlocked", def.timeUnlocked);+ trophiesArr.push(std::move(t));+ }+ out.set("trophies", std::move(trophiesArr));++ platform::writeFileAtomic(cacheFile, out.dump());+ return true;+}++bool TrophySyncEngine::pollActiveStream(const std::string& xblAuth, const std::string& xuid,+ const std::string& xboxTitleId, const std::string& titleName) {+ if (xboxTitleId.empty() || xblAuth.empty()) return false;+ if (pollInFlight_.exchange(true)) return false;++ std::thread([this, xblAuth, xuid, xboxTitleId, titleName]() {+ int newlyUnlocked = 0;+ std::string err;+ bool ok = syncTitleAchievements(xblAuth, xuid, xboxTitleId, titleName, newlyUnlocked, err);+ if (ok && newlyUnlocked > 0) {+ XC_LOGI("trophy poll: unlocked %d trophies during stream for %s!", newlyUnlocked, titleName.c_str());+ }+ pollInFlight_ = false;+ }).detach();+ return true;+}++bool TrophySyncEngine::syncAllAccountTrophies(const std::string& xblAuth, const std::string& xuid,+ const std::vector<ui::GameTile>& ownedGames,+ int& totalTitles, int& totalTrophies, std::string& err,+ const std::function<bool()>& cancelCheck,+ const std::function<void(int done, int total)>& progressCb) {+ totalTitles = 0;+ totalTrophies = 0;+ if (xblAuth.empty()) {+ err = "Conta não conectada / Account not signed in";+ return false;+ }++ struct SyncGuard {+ std::atomic<bool>& f;+ SyncGuard(std::atomic<bool>& flag) : f(flag) { f = true; }+ ~SyncGuard() { f = false; }+ } guard(syncing_);++ std::unordered_set<std::string> seenXboxTitles;+ std::vector<std::pair<std::string, std::string>> titlesToSync; // pair<xboxTitleId, titleName>++ // Add titles from owned library, resolving known titles if xboxTitleId is missing+ for (const auto& game : ownedGames) {+ std::string xid = game.xboxTitleId;+ if (xid.empty() && !game.productId.empty()) {+ if (const auto* k = findKnownTitle("", game.productId)) {+ xid = k->xboxTitleId;+ }+ }+ if (!xid.empty() && seenXboxTitles.insert(xid).second) {+ titlesToSync.emplace_back(xid, game.name.empty() ? ("Xbox Title " + xid) : game.name);+ }+ }++ // Always include Fortnite if not already added+ if (seenXboxTitles.insert("267695549").second) {+ titlesToSync.emplace_back("267695549", "Fortnite");+ }++ XC_LOGI("trophy back-sync: starting synchronization for %d titles", static_cast<int>(titlesToSync.size()));+ for (size_t i = 0; i < titlesToSync.size(); ++i) {+ if (cancelCheck && cancelCheck()) {+ XC_LOGI("trophy back-sync: cancelled by user after %d titles", totalTitles);+ break;+ }+ if (progressCb) {+ progressCb(static_cast<int>(i), static_cast<int>(titlesToSync.size()));+ }+ const auto& [tid, name] = titlesToSync[i];+ int newlyUnlocked = 0;+ std::string titleErr;+ if (syncTitleAchievements(xblAuth, xuid, tid, name, newlyUnlocked, titleErr)) {+ totalTitles++;+ totalTrophies += newlyUnlocked;+ } else {+ XC_LOGW("trophy back-sync: title %s (%s) sync warning: %s", name.c_str(), tid.c_str(), titleErr.c_str());+ }+ }+ if (progressCb) {+ progressCb(static_cast<int>(titlesToSync.size()), static_cast<int>(titlesToSync.size()));+ }++ XC_LOGI("trophy back-sync: completed. %d titles checked, %d trophies unlocked.", totalTitles, totalTrophies);+ return true;+}++TrophySyncEngine& syncEngine() {+ static TrophySyncEngine s_engine;+ return s_engine;+}++} // namespace xc::trophydiff --git a/src/trophy/trophy_sync.h b/src/trophy/trophy_sync.hnew file mode 100644index 0000000..c9f72e7--- /dev/null+++ b/src/trophy/trophy_sync.h@@ -0,0 +1,63 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++#include "trophy/trophy_backend.h"+#include "trophy/trophy_types.h"+#include "ui/app_ui.h"++#include <atomic>+#include <functional>+#include <memory>+#include <mutex>+#include <string>+#include <vector>++namespace xc::trophy {++class TrophySyncEngine {+public:+ TrophySyncEngine();+ explicit TrophySyncEngine(std::unique_ptr<ITrophyBackend> backend);+ ~TrophySyncEngine();++ // Initializes engine with user ID (default 0 detects active user)+ bool init(uint32_t userId = 0);++ // Sync achievements for a single title against Xbox Live and PlayStation backend+ bool syncTitleAchievements(const std::string& xblAuth, const std::string& xuid,+ const std::string& xboxTitleId, const std::string& titleName,+ int& newlyUnlocked, std::string& err);++ // Called every 20s during active stream (non-blocking async dispatch)+ bool pollActiveStream(const std::string& xblAuth, const std::string& xuid,+ const std::string& xboxTitleId, const std::string& titleName);++ // Retro-synchronization (Back-Sync) for all titles in the user's account+ bool syncAllAccountTrophies(const std::string& xblAuth, const std::string& xuid,+ const std::vector<ui::GameTile>& ownedGames,+ int& totalTitles, int& totalTrophies, std::string& err,+ const std::function<bool()>& cancelCheck = nullptr,+ const std::function<void(int done, int total)>& progressCb = nullptr);++ // Swap backend (useful for testing or platform initialization)+ void setBackend(std::unique_ptr<ITrophyBackend> backend);+ ITrophyBackend* backend() const { return backend_.get(); }++ bool isSyncing() const { return syncing_.load(); }++private:+ std::string trophyCacheDir() const;+ std::string trophyCachePath(const std::string& xboxTitleId) const;++ std::unique_ptr<ITrophyBackend> backend_;+ std::mutex mutex_;+ std::atomic<bool> pollInFlight_{false};+ std::atomic<bool> syncing_{false};+ bool initialized_ = false;+};++// Global singleton instance+TrophySyncEngine& syncEngine();++} // namespace xc::trophydiff --git a/src/trophy/trophy_types.h b/src/trophy/trophy_types.hnew file mode 100644index 0000000..d70f22b--- /dev/null+++ b/src/trophy/trophy_types.h@@ -0,0 +1,42 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++#include <cstdint>+#include <string>+#include <vector>++namespace xc::trophy {++enum class TrophyGrade {+ Bronze = 1,+ Silver = 2,+ Gold = 3,+ Platinum = 4+};++constexpr int kPlatinumTrophyId = 0;++struct TrophyDef {+ int trophyId = 0; // 0 for Platinum, 1-indexed for regular achievements (1, 2, ...)+ std::string name;+ std::string description;+ std::string iconUrl;+ TrophyGrade grade = TrophyGrade::Bronze;+ int gamerscore = 0;+ bool unlocked = false;+ std::string timeUnlocked;+};++struct TitleTrophySet {+ std::string xboxTitleId;+ std::string productId;+ std::string titleName;+ std::string npCommId;+ std::string sonyTitleId;+ int totalCount = 0;+ int unlockedCount = 0;+ std::vector<TrophyDef> items;+};++} // namespace xc::trophydiff --git a/src/trophy/trptitle_template.inc b/src/trophy/trptitle_template.incnew file mode 100644index 0000000..91f9ef1--- /dev/null+++ b/src/trophy/trptitle_template.inc@@ -0,0 +1,108 @@+// Auto-generated Animal Well TRPTITLE.DAT templates+const uint8_t kTag1PayloadTemplate[48] = {+ 0x00, 0x01, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+};++const uint8_t kTag2PayloadTemplate[96] = {+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe3, 0x1f, 0x22, 0xc0, 0x29, 0x0f, 0xa9,+ 0x00, 0xe3, 0x1f, 0x24, 0xd4, 0x18, 0xd5, 0xc0, 0x00, 0xe3, 0x1f, 0x24, 0xb6, 0xc3, 0x2c, 0xca,+ 0x39, 0x55, 0xb5, 0x60, 0x12, 0xbc, 0x18, 0xbc, 0x1e, 0xa2, 0xf4, 0xda, 0x00, 0x00, 0x00, 0x00,+ 0xe2, 0x11, 0x80, 0xcb, 0xb5, 0x2a, 0x33, 0xc3, 0xa3, 0xb0, 0x92, 0xc6, 0xd7, 0x9e, 0x30, 0x5f,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+};++const uint8_t kTag100PayloadTemplate[64] = {+ 0x0a, 0xde, 0xfa, 0x70, 0x18, 0x02, 0x80, 0xd4, 0xc3, 0x09, 0x60, 0xe1, 0x42, 0xad, 0xf4, 0x06,+ 0xd4, 0xbb, 0x43, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+};++const uint8_t kTag300PayloadTemplate[1152] = {+ 0x4e, 0x50, 0x57, 0x52, 0x33, 0x36, 0x37, 0x35, 0x39, 0x5f, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00,+ 0xb9, 0xdd, 0xe1, 0x3b, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x0a, 0x93, 0x9e,+ 0xca, 0x4f, 0xe6, 0x12, 0x95, 0xc6, 0xff, 0x69, 0xe4, 0xc3, 0x9a, 0x7b, 0xcf, 0xd4, 0x44, 0x97,+ 0x0f, 0x05, 0xce, 0xf4, 0x93, 0x1e, 0x12, 0x72, 0xe3, 0xec, 0x82, 0xf2, 0xc0, 0x37, 0x92, 0x8e,+ 0xab, 0x90, 0x25, 0x45, 0x92, 0xc1, 0xa5, 0x45, 0x74, 0x77, 0xde, 0x53, 0x4d, 0x70, 0x02, 0x49,+ 0xdd, 0x60, 0xc6, 0xb6, 0x58, 0x61, 0x3a, 0x8f, 0xe3, 0xca, 0x1e, 0x30, 0x9e, 0x27, 0x6e, 0x3c,+ 0xe4, 0x9b, 0x8f, 0x06, 0xc1, 0x5a, 0x1f, 0xdd, 0x13, 0x26, 0x49, 0xe2, 0x8d, 0x1f, 0x39, 0x24,+ 0x9a, 0x47, 0x95, 0xfb, 0xa6, 0x81, 0xd2, 0x79, 0x60, 0x54, 0x7a, 0xd1, 0xbd, 0xdd, 0x7a, 0xb9,+ 0x15, 0x09, 0xf8, 0x59, 0x26, 0x3d, 0x74, 0x38, 0x6e, 0x74, 0xfe, 0x4b, 0x16, 0x5f, 0x0a, 0x83,+ 0xd7, 0x49, 0x33, 0x88, 0x5d, 0x1f, 0x20, 0x55, 0xdc, 0x8e, 0x35, 0x00, 0xbe, 0x8f, 0x8f, 0x6b,+ 0x23, 0x48, 0x76, 0xc4, 0xac, 0xe0, 0xa8, 0x3c, 0x1d, 0x7f, 0xc9, 0xd1, 0xdd, 0x80, 0x86, 0x11,+ 0x4e, 0x50, 0x57, 0x52, 0x33, 0x36, 0x37, 0x35, 0x39, 0x5f, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0xe9, 0xf1, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0xfc, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x2f, 0x0c, 0xda, 0xb8, 0xf2, 0x32, 0x41, 0x4a, 0x54, 0x41, 0xda, 0x69, 0x7a, 0x16, 0x77, 0xf4,+ 0xae, 0xa2, 0xed, 0x19, 0x2a, 0x43, 0xff, 0x1a, 0x34, 0x6c, 0x64, 0x10, 0x97, 0x56, 0xbb, 0xf2,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0xc0, 0x2f, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x38, 0x50, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x06, 0x80, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,+};++const uint8_t kTag600PayloadTemplate[48] = {+ 0x00, 0xe3, 0x1f, 0x22, 0xc0, 0x29, 0x0f, 0x3a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,+ 0x00, 0xe3, 0x1f, 0x22, 0xdd, 0x73, 0x77, 0x80, 0x00, 0xe3, 0x1f, 0x22, 0xc0, 0x29, 0x0e, 0xeb,+ 0x00, 0xe3, 0x1f, 0x24, 0xd4, 0x18, 0xd5, 0xc0, 0x00, 0xe3, 0x1f, 0x24, 0xb6, 0xc3, 0x24, 0xd3,+};++const uint8_t kTrailerSignatureTemplate[32] = {+ 0xdf, 0x73, 0xfa, 0x0c, 0x57, 0xe5, 0x46, 0x5c, 0x61, 0xa9, 0xef, 0xf7, 0x0e, 0x34, 0xdd, 0x13,+ 0x71, 0x04, 0x84, 0x3a, 0x74, 0xaf, 0x69, 0xbf, 0x65, 0x55, 0x4a, 0x4f, 0x93, 0xf4, 0xfc, 0xdc,+};diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex e3a4da6..6246cc9 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -197,11 +197,11 @@ std::vector<SettingsRowPos> visibleGameSettingsRows(const UiCaps& caps, bool cus// The largest stick dead zone Settings offers, in percent of the travel.constexpr int kMaxDeadzone = 30;-constexpr int kSettingRows = 24; // language, resolution, region, dead zone, triggers, confirm, light bar, updates,+constexpr int kSettingRows = 25; // language, resolution, region, dead zone, triggers, confirm, light bar, updates,// sign-in country, 120 Hz output, bitrate cap, game volume, keyboard keys,// display mode (a desktop's window), controller buttons, gyro aiming, queue chime,// check sign-in, network test, support project, video decoder, audio-to-haptics,- // touchpad shortcuts, restore defaults+ // touchpad shortcuts, restore defaults, sync trophiesstruct SignInStage {std::string name;@@ -246,6 +246,7 @@ enum class Action {RefreshLibrary, // manual library refreshCheckSignIn, // run sign-in diagnostic stagesRunNetworkTest, // run regional RTT/jitter & NAT probe+ SyncTrophies, // synchronize Xbox achievements to PlayStation trophiesTestQueueAlert, // play test chime and vibration for queue-ready alertResetSettings // restore settings to default};diff --git a/src/ui/app_ui_input.cpp b/src/ui/app_ui_input.cppindex 2e54d91..78e8609 100644--- a/src/ui/app_ui_input.cpp+++ b/src/ui/app_ui_input.cpp@@ -710,6 +710,9 @@ UiEvent AppUi::onMouseDown(float x, float y, int button) {openTester(Tester::NetworkTest);ev.action = Action::RunNetworkTest;return ev;+ } else if (i == 24) {+ ev.action = Action::SyncTrophies;+ return ev;} else if (i == 19) {openTester(Tester::Donation);return ev;@@ -1071,6 +1074,8 @@ UiEvent AppUi::handle(const NavInput& in) {} else if (in.accept && settingsRow_ == 18) {openTester(Tester::NetworkTest);ev.action = Action::RunNetworkTest;+ } else if (in.accept && settingsRow_ == 24) {+ ev.action = Action::SyncTrophies;} else if (in.accept && settingsRow_ == 19) {openTester(Tester::Donation);} else if (in.accept && settingsRow_ == 7) {diff --git a/src/ui/app_ui_internal.h b/src/ui/app_ui_internal.hindex a2d156e..cc1c3af 100644--- a/src/ui/app_ui_internal.h+++ b/src/ui/app_ui_internal.h@@ -65,9 +65,9 @@ constexpr int kResolutionOrder[3] = {1, 0, 2};// stream (resolution, a desktop's display mode, 120 Hz, bitrate, region, network test);// the controller, keyboard and queue-ready alert; support and updates last. A group starts at each// kSettingsGroupStart.-constexpr int kSettingsCount = 23;-constexpr int kSettingsOrder[kSettingsCount] = {0, 2, 8, 17, 18, 1, 20, 13, 9, 10, 14, 12, 3, 15, 4, 21, 5, 6, 16, 22, 19, 7, 23};-constexpr bool kSettingsGroupStart[kSettingsCount] = {false, false, false, false, false, true, false, false, false, false,+constexpr int kSettingsCount = 24;+constexpr int kSettingsOrder[kSettingsCount] = {0, 2, 8, 17, 18, 24, 1, 20, 13, 9, 10, 14, 12, 3, 15, 4, 21, 5, 6, 16, 22, 19, 7, 23};+constexpr bool kSettingsGroupStart[kSettingsCount] = {false, false, false, false, false, false, true, false, false, false, false,true, false, false, false, false, false, false, false, false, false, true, false, true};// The game settings' rows on screen (ids: 0 profile, 1 upscaler, 2// sharpness, 3 block smoothing, 4 resolution, 5 dead zone, 6 triggers, 7diff --git a/src/ui/app_ui_settings.cpp b/src/ui/app_ui_settings.cppindex 54e4bae..538e7a5 100644--- a/src/ui/app_ui_settings.cpp+++ b/src/ui/app_ui_settings.cpp@@ -880,7 +880,7 @@ void AppUi::drawSettings(Canvas& c) {tr(Str::Gyro), tr(Str::QueueReadyNotification),tr(Str::CheckSignIn), tr(Str::NetworkTest), tr(Str::SupportProject),tr(Str::VideoDecoder), tr(Str::AudioHaptics), tr(Str::PreviewFeatures),- tr(Str::ResetSettings)};+ tr(Str::ResetSettings), tr(Str::SyncTrophies)};constexpr int kRowW = 1140, kRowH = 30, kGap = 2, kGroupGap = 4, kRowPx = 22;Rect rows[kSettingRows]; // by row idint y = 184;@@ -914,7 +914,7 @@ void AppUi::drawSettings(Canvas& c) {if (focused && !dropdownOpen_) c.strokeRect({r.x - 4, r.y - 4, r.w + 8, r.h + 8}, kWhite, 3, 16);fonts_.semibold.draw(c, labels[i], r.x + 32, ty, kRowPx, kWhite);float cx = static_cast<float>(r.x + r.w - 40), cy = static_cast<float>(r.y + r.h / 2);- if (i != 7 && i != 17 && i != 18 && i != 19) {+ if (i != 7 && i != 17 && i != 18 && i != 19 && i != 24) {c.line(cx - 8, cy - 3, cx, cy + 4, 2.5f, focused ? kWhite : kGray);c.line(cx, cy + 4, cx + 8, cy - 3, 2.5f, focused ? kWhite : kGray);}@@ -929,9 +929,9 @@ void AppUi::drawSettings(Canvas& c) {Color color = !updateAvailable_.empty() && !updateChecking_ ? rgba(120, 220, 120) : focused ? kWhite : kGray;int w = fonts_.regular.measure(value, kRowPx);fonts_.regular.draw(c, value, vx - w, fonts_.regular.centeredY(r.y, r.h, kRowPx), kRowPx, color);- } else if (i == 17 || i == 18 || i == 19) {- // Action items (Check sign-in, Network test, Support)- std::string label = (i == 17) ? tr(Str::RunCheck) : (i == 18) ? tr(Str::RunTest) : tr(Str::SupportKoFi);+ } else if (i == 17 || i == 18 || i == 19 || i == 24) {+ // Action items (Check sign-in, Network test, Support, Sync Trophies)+ std::string label = (i == 17) ? tr(Str::RunCheck) : (i == 18) ? tr(Str::RunTest) : (i == 24) ? tr(Str::RunSyncTrophies) : tr(Str::SupportKoFi);int w = fonts_.regular.measure(label, kRowPx);fonts_.regular.draw(c, label, vx - w, fonts_.regular.centeredY(r.y, r.h, kRowPx), kRowPx,focused ? kWhite : kGray);@@ -977,6 +977,7 @@ void AppUi::drawSettings(Canvas& c) {Str::SettingDescAudioHaptics,Str::SettingDescPreviewFeatures,Str::SettingDescResetSettings,+ Str::SettingDescSyncTrophies,};if (settingsRow_ >= 0 && settingsRow_ < kSettingRows) {int dy = std::max(y + 6, 922);diff --git a/src/ui/i18n/strings_de.inc b/src/ui/i18n/strings_de.incindex 4e364b1..5cbc0fb 100644--- a/src/ui/i18n/strings_de.inc+++ b/src/ui/i18n/strings_de.inc@@ -415,4 +415,8 @@ constexpr Column kGerman = {"In Warteschlange (geschätzte Wartezeit: %s • wartet seit %s)", // InQueueEstimated"Um kostenlose Spiele außer Fortnite ohne Game Pass zu streamen, aktivieren Sie 'Preview-Funktionen' in den App-Einstellungen und auf xbox.com/play.", // F2pPreviewRequiredDesc"Dieses Konto muss 'Preview-Funktionen' im Profil auf xbox.com/play aktivieren, um werbefinanziertes Free-to-Play-Streaming freizuschalten.", // F2pPreviewAccountNeededDesc+ "Trophäen synchronisieren", // SyncTrophies+ "Synchronisiert alle Xbox-Erfolge Ihres Kontos und weist entsprechende Trophäen Ihrem PlayStation-Profil zu.", // SettingDescSyncTrophies+ "Sync", // RunSyncTrophies+ "Synchronisierung abgeschlossen: %s Trophäe(n) in %s Titel(n) deinem Profil hinzugefügt!", // TrophiesSyncedToast};diff --git a/src/ui/i18n/strings_en.inc b/src/ui/i18n/strings_en.incindex ac7e29d..91a30c3 100644--- a/src/ui/i18n/strings_en.inc+++ b/src/ui/i18n/strings_en.inc@@ -415,4 +415,8 @@ constexpr Column kEnglish = {"In queue (estimated wait: %s • waiting for %s)", // InQueueEstimated"To stream free-to-play games beyond Fortnite without Game Pass, enable 'Preview Features' in app Settings and on xbox.com/play.", // F2pPreviewRequiredDesc"This account needs to enable 'Preview Features' in its profile on xbox.com/play to unlock ad-supported free-to-play streaming.", // F2pPreviewAccountNeededDesc+ "Sync Trophies", // SyncTrophies+ "Synchronizes all Xbox achievements from your account and awards matching trophies to your PlayStation profile.", // SettingDescSyncTrophies+ "Sync", // RunSyncTrophies+ "Sync complete: %s trophy(ies) across %s title(s) awarded to your profile!", // TrophiesSyncedToast};diff --git a/src/ui/i18n/strings_es.inc b/src/ui/i18n/strings_es.incindex f96002e..2110164 100644--- a/src/ui/i18n/strings_es.inc+++ b/src/ui/i18n/strings_es.inc@@ -415,4 +415,8 @@ constexpr Column kSpanish = {"En cola (tiempo estimado: %s • esperando desde hace %s)", // InQueueEstimated"Para transmitir juegos gratuitos además de Fortnite en cuentas sin Game Pass, activa 'Funciones Preview' en Ajustes y en xbox.com/play.", // F2pPreviewRequiredDesc"Esta cuenta necesita habilitar 'Funciones Preview' en su perfil en xbox.com/play para desbloquear el streaming con anuncios de juegos gratuitos.", // F2pPreviewAccountNeededDesc+ "Sincronizar Trofeos", // SyncTrophies+ "Sincroniza todos los logros de Xbox de tu cuenta y otorga los trofeos correspondientes en tu perfil de PlayStation.", // SettingDescSyncTrophies+ "Sincronizar", // RunSyncTrophies+ "¡Sincronización completada: %s trofeo(s) en %s título(s) otorgados a tu perfil!", // TrophiesSyncedToast};diff --git a/src/ui/i18n/strings_fr.inc b/src/ui/i18n/strings_fr.incindex d988ae0..1e246ed 100644--- a/src/ui/i18n/strings_fr.inc+++ b/src/ui/i18n/strings_fr.inc@@ -415,4 +415,8 @@ constexpr Column kFrench = {"En file d'attente (temps estimé : %s • attente depuis %s)", // InQueueEstimated"Pour jouer aux jeux gratuits autres que Fortnite sans Game Pass, activez les 'Fonctionnalités Preview' dans les Paramètres et sur xbox.com/play.", // F2pPreviewRequiredDesc"Ce compte doit activer les 'Fonctionnalités Preview' sur son profil sur xbox.com/play pour débloquer le streaming gratuit avec publicités.", // F2pPreviewAccountNeededDesc+ "Synchroniser les trophées", // SyncTrophies+ "Synchronise tous les succès Xbox de votre compte et attribue les trophées correspondants à votre profil PlayStation.", // SettingDescSyncTrophies+ "Synchroniser", // RunSyncTrophies+ "Synchronisation terminée : %s trophée(s) sur %s titre(s) ajoutés à votre profil !", // TrophiesSyncedToast};diff --git a/src/ui/i18n/strings_it.inc b/src/ui/i18n/strings_it.incindex 3b53f8b..00aed04 100644--- a/src/ui/i18n/strings_it.inc+++ b/src/ui/i18n/strings_it.inc@@ -415,4 +415,8 @@ constexpr Column kItalian = {"In coda (tempo stimato: %s • in attesa da %s)", // InQueueEstimated"Per giocare a titoli gratuiti oltre a Fortnite senza Game Pass, abilita 'Funzionalità Preview' nelle Impostazioni e su xbox.com/play.", // F2pPreviewRequiredDesc"Questo account deve abilitare le 'Funzionalità Preview' nel profilo su xbox.com/play per sbloccare lo streaming gratuito supportato da annunci.", // F2pPreviewAccountNeededDesc+ "Sincronizza trofei", // SyncTrophies+ "Sincronizza tutti gli obiettivi Xbox del tuo account e assegna i trofei corrispondenti al tuo profilo PlayStation.", // SettingDescSyncTrophies+ "Sincronizza", // RunSyncTrophies+ "Sincronizzazione completata: %s trofeo/i su %s titolo/i assegnati al tuo profilo!", // TrophiesSyncedToast};diff --git a/src/ui/i18n/strings_pt_br.inc b/src/ui/i18n/strings_pt_br.incindex eefcf56..4b2c9d6 100644--- a/src/ui/i18n/strings_pt_br.inc+++ b/src/ui/i18n/strings_pt_br.inc@@ -415,4 +415,8 @@ constexpr Column kPortugueseBR = {"Na fila (tempo estimado: %s • aguardando há %s)", // InQueueEstimated"Para transmitir jogos gratuitos além de Fortnite em contas sem Game Pass, ative os 'Recursos Preview' nas Configurações do app e no site xbox.com/play.", // F2pPreviewRequiredDesc"Esta conta precisa habilitar os 'Recursos Preview' no perfil em xbox.com/play para liberar o streaming com anúncios de jogos gratuitos.", // F2pPreviewAccountNeededDesc+ "Sincronizar Troféus", // SyncTrophies+ "Sincroniza todas as conquistas do Xbox da sua conta e atribui os troféus correspondentes ao perfil do PlayStation.", // SettingDescSyncTrophies+ "Sincronizar", // RunSyncTrophies+ "Sincronização concluída: %s troféu(s) em %s título(s) atribuídos ao seu perfil!", // TrophiesSyncedToast};diff --git a/src/ui/strings.h b/src/ui/strings.hindex fb212a6..dcbbffd 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -424,6 +424,10 @@ enum class Str {InQueueEstimated,F2pPreviewRequiredDesc,F2pPreviewAccountNeededDesc,+ SyncTrophies,+ SettingDescSyncTrophies,+ RunSyncTrophies,+ TrophiesSyncedToast,Count};diff --git a/src/xcloud/achievements.cpp b/src/xcloud/achievements.cppindex 0301861..9c0283b 100644--- a/src/xcloud/achievements.cpp+++ b/src/xcloud/achievements.cpp@@ -58,6 +58,15 @@ bool fetchTitleAchievements(const std::string& xblAuth, const std::string& xuid,ach.timeUnlocked = prog["timeUnlocked"].str();}+ for (const auto& ma : a["mediaAssets"].items()) {+ std::string type = ma["type"].str();+ std::string name = ma["name"].str();+ if (type == "Icon" || name == "Icon" || ach.iconUrl.empty()) {+ ach.iconUrl = ma["url"].str();+ if (type == "Icon" || name == "Icon") break;+ }+ }+for (const auto& rw : a["rewards"].items()) {std::string type = rw["type"].str();std::string name = rw["name"].str();diff --git a/src/xcloud/achievements.h b/src/xcloud/achievements.hindex e8378bb..6277c24 100644--- a/src/xcloud/achievements.h+++ b/src/xcloud/achievements.h@@ -13,6 +13,7 @@ struct Achievement {std::string name;std::string description;std::string lockedDescription;+ std::string iconUrl;int gamerscore = 0;bool unlocked = false;bool isSecret = false;diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 8b5b2ab..f7958f5 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -52,9 +52,16 @@#include "xcloud/purchase.h"#include "xcloud/regions.h"#include "xcloud/achievements.h"+#include "trophy/trophy_types.h"+#include "trophy/trophy_rules.h"+#include "trophy/trophy_registry.h"+#include "trophy/trophy_backend.h"+#include "trophy/trophy_sync.h"+#include "trophy/trophy_builder.h"#include <algorithm>#include <atomic>+#include <cstring>#include <cmath>#include <cstdio>#include <csignal>@@ -2185,21 +2192,21 @@ static void testVisibleSettingsRows() {};const ui::UiCaps ps5;auto all = ui::visibleSettingsRows(ps5);- CHECK((ids(all) == std::vector<int>{0, 2, 8, 17, 18, 1, 20, 9, 10, 14, 12, 3, 15, 4, 21, 5, 6, 16, 22, 19, 7, 23}));- CHECK((groups(all) == std::vector<bool>{false, false, false, false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, false, true, false, true}));+ CHECK((ids(all) == std::vector<int>{0, 2, 8, 17, 18, 24, 1, 20, 9, 10, 14, 12, 3, 15, 4, 21, 5, 6, 16, 22, 19, 7, 23}));+ CHECK((groups(all) == std::vector<bool>{false, false, false, false, false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, false, true, false, true}));ui::UiCaps pc;pc.lightBar = pc.triggerRumble = pc.adaptiveTriggers = pc.gyro = pc.touchpad = false;pc.upscalers = pc.sharpen = pc.deband = pc.highRefresh = pc.console = pc.selfUpdate = false;pc.openUrl = true;auto desk = ui::visibleSettingsRows(pc);- CHECK((ids(desk) == std::vector<int>{0, 2, 8, 17, 18, 1, 20, 10, 14, 12, 3, 5, 16, 22, 19, 7, 23}));- CHECK((groups(desk) == std::vector<bool>{false, false, false, false, false, true, false, false, true, false, false, false, false, false, true, false, true}));+ CHECK((ids(desk) == std::vector<int>{0, 2, 8, 17, 18, 24, 1, 20, 10, 14, 12, 3, 5, 16, 22, 19, 7, 23}));+ CHECK((groups(desk) == std::vector<bool>{false, false, false, false, false, false, true, false, false, true, false, false, false, false, false, true, false, true}));// The desktop app's window: Display mode after the resolution, in the stream's group.ui::UiCaps win = pc;win.desktopWindow = true;auto w = ui::visibleSettingsRows(win);- CHECK((ids(w) == std::vector<int>{0, 2, 8, 17, 18, 1, 20, 13, 10, 14, 12, 3, 5, 16, 22, 19, 7, 23}));- CHECK((groups(w) == std::vector<bool>{false, false, false, false, false, true, false, false, false, true, false, false, false, false, false, true, false, true}));+ CHECK((ids(w) == std::vector<int>{0, 2, 8, 17, 18, 24, 1, 20, 13, 10, 14, 12, 3, 5, 16, 22, 19, 7, 23}));+ CHECK((groups(w) == std::vector<bool>{false, false, false, false, false, false, true, false, false, false, true, false, false, false, false, false, true, false, true}));ui::UiCaps xbox = pc; // an Xbox pad: impulse triggers, no light barxbox.triggerRumble = true;auto x = ids(ui::visibleSettingsRows(xbox));@@ -2245,14 +2252,15 @@ static void testVisibleSettingsRows() {CHECK((ids(game) == std::vector<int>{0, 4, 15, 14, 5, 7, 11, 9}));CHECK((groups(game) == std::vector<bool>{false, true, false, false, true, false, false, false}));// How far down the autoplay tests walk to each row (autoplay.cpp's downsTo).- CHECK(ui::settingsRowPosition(ps5, 1) == 5 && ui::settingsRowPosition(ps5, 3) == 11);- CHECK(ui::settingsRowPosition(ps5, 16) == 17);- CHECK(ui::settingsRowPosition(ps5, 5) == 15 && ui::settingsRowPosition(ps5, 6) == 16);- CHECK(ui::settingsRowPosition(ps5, 12) == 10 && ui::settingsRowPosition(ps5, 14) == 9);- CHECK(ui::settingsRowPosition(ps5, 22) == 18);- CHECK(ui::settingsRowPosition(ps5, 7) == 20 && ui::settingsRowPosition(ps5, 19) == 19 && ui::settingsRowPosition(ps5, 2) == 1);- CHECK(ui::settingsRowPosition(ps5, 21) == 14);- CHECK(ui::settingsRowPosition(pc, 5) == 11 && ui::settingsRowPosition(pc, 6) == -1 && ui::settingsRowPosition(pc, 4) == -1);+ CHECK(ui::settingsRowPosition(ps5, 24) == 5);+ CHECK(ui::settingsRowPosition(ps5, 1) == 6 && ui::settingsRowPosition(ps5, 3) == 12);+ CHECK(ui::settingsRowPosition(ps5, 16) == 18);+ CHECK(ui::settingsRowPosition(ps5, 5) == 16 && ui::settingsRowPosition(ps5, 6) == 17);+ CHECK(ui::settingsRowPosition(ps5, 12) == 11 && ui::settingsRowPosition(ps5, 14) == 10);+ CHECK(ui::settingsRowPosition(ps5, 22) == 19);+ CHECK(ui::settingsRowPosition(ps5, 7) == 21 && ui::settingsRowPosition(ps5, 19) == 20 && ui::settingsRowPosition(ps5, 2) == 1);+ CHECK(ui::settingsRowPosition(ps5, 21) == 15);+ CHECK(ui::settingsRowPosition(pc, 5) == 12 && ui::settingsRowPosition(pc, 6) == -1 && ui::settingsRowPosition(pc, 4) == -1);}// The controller's glyphs by pad kind (ui/pad_glyphs.h).@@ -6763,7 +6771,301 @@ static void testReleaseV155Features() {std::system(("rm -rf " + testDir).c_str());}+static void testTrophySystem() {+ using namespace xc::trophy;++ // 1. Gamerscore to Trophy grade conversion rules+ // <= 50G -> Bronze+ CHECK(scoreToGrade(0) == TrophyGrade::Bronze);+ CHECK(scoreToGrade(5) == TrophyGrade::Bronze);+ CHECK(scoreToGrade(20) == TrophyGrade::Bronze);+ CHECK(scoreToGrade(50) == TrophyGrade::Bronze);+ // 55G..99G -> Silver+ CHECK(scoreToGrade(55) == TrophyGrade::Silver);+ CHECK(scoreToGrade(75) == TrophyGrade::Silver);+ CHECK(scoreToGrade(99) == TrophyGrade::Silver);+ // >= 100G -> Gold+ CHECK(scoreToGrade(100) == TrophyGrade::Gold);+ CHECK(scoreToGrade(150) == TrophyGrade::Gold);+ CHECK(scoreToGrade(200) == TrophyGrade::Gold);++ // Grade to string & points+ CHECK(std::string(gradeToString(TrophyGrade::Bronze)) == "Bronze");+ CHECK(std::string(gradeToString(TrophyGrade::Silver)) == "Silver");+ CHECK(std::string(gradeToString(TrophyGrade::Gold)) == "Gold");+ CHECK(std::string(gradeToString(TrophyGrade::Platinum)) == "Platinum");++ CHECK(gradeToPoints(TrophyGrade::Bronze) == 15);+ CHECK(gradeToPoints(TrophyGrade::Silver) == 30);+ CHECK(gradeToPoints(TrophyGrade::Gold) == 90);+ CHECK(gradeToPoints(TrophyGrade::Platinum) == 300);++ // Platinum automatic award calculation+ CHECK(!hasEarnedPlatinum(0, 0));+ CHECK(!hasEarnedPlatinum(0, 10));+ CHECK(!hasEarnedPlatinum(9, 10));+ CHECK(hasEarnedPlatinum(10, 10));+ CHECK(hasEarnedPlatinum(11, 10));++ // 2. Known cross-platform titles (Scenario A: Fortnite pilot, etc.)+ const auto* fortnite = findKnownTitle("267695549", "");+ CHECK(fortnite != nullptr);+ CHECK(fortnite->titleName == "Fortnite");+ CHECK(fortnite->npCommId == "NPWR20561_00");+ CHECK(fortnite->sonyTitleId == "PPSA01922");+ CHECK(fortnite->productId == "BT5P2X999VH2");++ const auto* fortniteByProd = findKnownTitle("", "BT5P2X999VH2");+ CHECK(fortniteByProd == fortnite);++ const auto* minecraft = findKnownTitle("1828326430", "");+ CHECK(minecraft != nullptr);+ CHECK(minecraft->npCommId == "NPWR18283_00");++ // 3. Mapping for titles without fixed known entry+ std::string haloNp = generateNpCommId("2144722883");+ std::string haloSony = generateSonyTitleId("2144722883");+ CHECK(haloNp.rfind("NPWR", 0) == 0);+ CHECK(haloNp.size() == 12); // NPWRXXXXX_00+ CHECK(haloNp.substr(haloNp.size() - 3) == "_00");+ CHECK(haloSony.rfind("PPSA", 0) == 0);+ // Deterministic: same input gives exact same output+ CHECK(haloNp == generateNpCommId("2144722883"));+ CHECK(haloSony == generateSonyTitleId("2144722883"));++ // 4. resolveTitleSet mapping+ std::vector<xcloud::Achievement> achs;+ xcloud::Achievement a1;+ a1.id = "1";+ a1.name = "Gunsmith";+ a1.gamerscore = 20;+ a1.unlocked = true;+ achs.push_back(a1);++ xcloud::Achievement a2;+ a2.id = "2";+ a2.name = "Hero";+ a2.gamerscore = 60;+ a2.unlocked = false;+ achs.push_back(a2);++ xcloud::Achievement a3;+ a3.id = "3";+ a3.name = "Legend";+ a3.gamerscore = 100;+ a3.unlocked = false;+ achs.push_back(a3);++ TitleTrophySet titleSet = resolveTitleSet("267695549", "BT5P2X999VH2", "Fortnite", achs);+ CHECK(titleSet.npCommId == "NPWR20561_00");+ CHECK(titleSet.totalCount == 3);+ CHECK(titleSet.unlockedCount == 1);+ CHECK(titleSet.items.size() == 3);+ CHECK(titleSet.items[0].grade == TrophyGrade::Bronze);+ CHECK(titleSet.items[1].grade == TrophyGrade::Silver);+ CHECK(titleSet.items[2].grade == TrophyGrade::Gold);++ // Name normalization+ CHECK(normalizeTrophyName("Gunsmith") == "gunsmith");+ CHECK(normalizeTrophyName("Take Out 10 Enemies!") == "takeout10enemies");++ // 4b. Test buildUcp and buildTrpTitleDat+ std::vector<uint8_t> ucpBytes;+ std::vector<uint8_t> sha1;+ CHECK(buildUcp(titleSet, ucpBytes, &sha1));+ CHECK(ucpBytes.size() > 1024);+ CHECK(ucpBytes[0] == 0xb2 && ucpBytes[1] == 0x28 && ucpBytes[2] == 0xc6 && ucpBytes[3] == 0x0a);+ CHECK(sha1.size() == 20);+ // UCP header at 0x1c must contain genuine SHA-1 digest+ CHECK(memcmp(ucpBytes.data() + 0x1c, sha1.data(), 20) == 0);++ std::vector<uint8_t> datBytes;+ CHECK(buildTrpTitleDat(titleSet, 0x1ea2f4da, datBytes, sha1.data()));+ CHECK(datBytes.size() > 2048);+ CHECK(memcmp(datBytes.data(), "T2PD", 4) == 0);+ CHECK(memcmp(datBytes.data() + 0x40, "T2TD", 4) == 0);+ // Tag 0x0100 in TRPTITLE.DAT must match genuine UCP SHA-1 digest+ CHECK(memcmp(datBytes.data() + 0x250, sha1.data(), 20) == 0);++ // 4c. Test buildParamJson for Fortnite and general titles+ std::string fnParam = buildParamJson("PPSA01922", "Fortnite");+ CHECK(fnParam.find("\"titleId\": \"PPSA01922\"") != std::string::npos);+ CHECK(fnParam.find("\"contentId\": \"UP1477-PPSA01922_00-FORTNITECORE0001\"") != std::string::npos);+ CHECK(fnParam.find("\"conceptId\": \"210118\"") != std::string::npos);+ CHECK(fnParam.find("\"appType\": 1") != std::string::npos);+ CHECK(fnParam.find("\"attribute3\": 1835012") != std::string::npos);+ CHECK(fnParam.find("\"titleName\": \"Fortnite\"") != std::string::npos);++ std::string genericParam = buildParamJson("PPSA12345", "Custom Game");+ CHECK(genericParam.find("\"titleId\": \"PPSA12345\"") != std::string::npos);+ CHECK(genericParam.find("\"contentId\": \"UP0001-PPSA12345_00-0000000000000000\"") != std::string::npos);+ CHECK(genericParam.find("\"titleName\": \"Custom Game\"") != std::string::npos);++ // 4d. Test buildNpTitleDat+ std::vector<uint8_t> npTitle;+ CHECK(buildNpTitleDat("PPSA01922", npTitle));+ CHECK(npTitle.size() == 160);+ CHECK(memcmp(npTitle.data(), "NPTD", 4) == 0);+ CHECK(memcmp(npTitle.data() + 0x10, "PPSA01922_00", 12) == 0);++ // 4e. Test buildTrpTitleDat append-only merging & timestamp preservation+ // Setup initial DAT where trophy 1 is unlocked with custom timestamp+ TitleTrophySet initialSet = titleSet;+ initialSet.items[0].unlocked = true;+ initialSet.items[1].unlocked = false;+ initialSet.items[2].unlocked = false;+ std::vector<uint8_t> initialDat;+ CHECK(buildTrpTitleDat(initialSet, 0x1ea2f4da, initialDat, sha1.data()));++ std::map<uint32_t, ExistingTrophyRecord> parsedInitial;+ CHECK(parseTrpTitleDat(initialDat.data(), initialDat.size(), parsedInitial));+ CHECK(parsedInitial.count(1) > 0);+ CHECK(parsedInitial[1].state == 1);+ uint64_t t1OriginalTs = parsedInitial[1].timestamp;++ // Simulate new sync where Xbox reports trophy 2 unlocked, but trophy 1 is offline/missing (unlocked=false)+ TitleTrophySet nextSet = titleSet;+ nextSet.items[0].unlocked = false; // missing in current sync!+ nextSet.items[1].unlocked = true; // newly unlocked+ nextSet.items[2].unlocked = false;++ std::vector<uint8_t> mergedDat;+ CHECK(buildTrpTitleDat(nextSet, 0x1ea2f4da, mergedDat, sha1.data(), &initialDat));++ std::map<uint32_t, ExistingTrophyRecord> parsedMerged;+ CHECK(parseTrpTitleDat(mergedDat.data(), mergedDat.size(), parsedMerged));+ // Trophy 1 MUST be preserved 100% with original timestamp!+ CHECK(parsedMerged.count(1) > 0);+ CHECK(parsedMerged[1].state == 1);+ CHECK(parsedMerged[1].timestamp == t1OriginalTs);+ // Trophy 2 MUST be newly unlocked+ CHECK(parsedMerged.count(2) > 0);+ CHECK(parsedMerged[2].state == 1);+ CHECK(parsedMerged[2].timestamp > 0);+ // Trophy 3 remains locked+ CHECK(parsedMerged.count(3) > 0);+ CHECK(parsedMerged[3].state == 0);+++ // 5. Mock ITrophyBackend & TrophySyncEngine integration+ class TestBackend : public ITrophyBackend {+ public:+ bool init(uint32_t uid) override {+ userId = uid;+ return true;+ }+ bool registerTitle(const TitleTrophySet& set) override {+ registered = true;+ return true;+ }+ bool unlockTrophy(const std::string& npComm, int tid, TrophyGrade g, const std::string& n) override {+ for (const auto& u : unlocked) {+ if (u.npCommId == npComm && u.trophyId == tid) return true;+ }+ unlocked.push_back({npComm, tid, g});+ return true;+ }+ bool isTrophyUnlocked(const std::string& npComm, int tid) override {+ for (const auto& u : unlocked) {+ if (u.npCommId == npComm && u.trophyId == tid) return true;+ }+ return false;+ }+ std::string name() const override { return "TestBackend"; }++ struct UnlockedItem {+ std::string npCommId;+ int trophyId;+ TrophyGrade grade;+ };+ uint32_t userId = 0;+ bool registered = false;+ std::vector<UnlockedItem> unlocked;+ };++ auto backendPtr = std::make_unique<TestBackend>();+ TestBackend* rawBackend = backendPtr.get();+ TrophySyncEngine engine(std::move(backendPtr));+ CHECK(engine.init(0x1ea2f4da));+ CHECK(rawBackend->userId == 0x1ea2f4da);++ std::string baseDir = platform::dataDir();+ if (baseDir.empty()) baseDir = ".";+ std::string cacheFile = baseDir + "/trophies/267695549.json";+ ::unlink(cacheFile.c_str());++ // Mock network transport for achievements+ net::setTestTransport([&](const net::Request& req) -> net::Response {+ net::Response res;+ if (req.url.find("achievements.xboxlive.com") != std::string::npos) {+ res.status = 200;+ res.body = R"({+ "achievements": [+ {+ "id": "101",+ "name": "First Step",+ "description": "Completed first step",+ "progressState": "Achieved",+ "rewards": [{"type": "Gamerscore", "value": "20"}],+ "mediaAssets": [{"name": "Icon", "url": "https://img/icon1.png"}]+ },+ {+ "id": "102",+ "name": "Big Step",+ "description": "Completed big step",+ "progressState": "Achieved",+ "rewards": [{"type": "Gamerscore", "value": "100"}],+ "mediaAssets": [{"name": "Icon", "url": "https://img/icon2.png"}]+ }+ ],+ "pagingInfo": {"totalItems": 2}+ })";+ return res;+ }+ res.status = 404;+ return res;+ });++ int newlyUnlocked = 0;+ std::string syncErr;+ bool syncOk = engine.syncTitleAchievements("Bearer mockToken", "25332749", "267695549", "Fortnite",+ newlyUnlocked, syncErr);+ CHECK(syncOk);+ // Both 101 and 102 were unlocked (2 achievements = 100% -> awards Platinum too: total 3!)+ CHECK(newlyUnlocked == 3);+ CHECK(rawBackend->unlocked.size() == 3);+ CHECK(rawBackend->unlocked[0].grade == TrophyGrade::Bronze);+ CHECK(rawBackend->unlocked[0].trophyId == 1);+ CHECK(rawBackend->unlocked[1].grade == TrophyGrade::Gold);+ CHECK(rawBackend->unlocked[1].trophyId == 2);+ CHECK(rawBackend->unlocked[2].grade == TrophyGrade::Platinum);+ CHECK(rawBackend->unlocked[2].trophyId == kPlatinumTrophyId); // Trophy ID 0++ // Verify rich JSON cache persistence+ std::string cacheSaved;+ CHECK(platform::readFile(cacheFile, cacheSaved));+ auto jCache = json::parse(cacheSaved);+ CHECK(jCache && jCache->isObject());+ CHECK((*jCache)["xboxTitleId"].str() == "267695549");+ CHECK((*jCache)["unlockedCount"].asInt() == 2);+ CHECK((*jCache)["trophies"].isArray());+ CHECK((*jCache)["trophies"].items().size() == 2);++ // Repeat sync: snapshot is cached, 0 newly unlocked+ newlyUnlocked = 0;+ syncOk = engine.syncTitleAchievements("Bearer mockToken", "25332749", "267695549", "Fortnite",+ newlyUnlocked, syncErr);+ CHECK(syncOk);+ CHECK(newlyUnlocked == 0); // No duplicate unlocks!+ CHECK(rawBackend->unlocked.size() == 3);++ // Clean up+ net::setTestTransport({});+ ::unlink(cacheFile.c_str());+}+int main() {+ testTrophySystem();testReleaseV155Features();testSizedUrl();testPhase1BugFixesAndPhase2Optimizations();diff --git a/tools/ps5/payload_patch_test/Makefile b/tools/ps5/payload_patch_test/Makefilenew file mode 100644index 0000000..592cdca--- /dev/null+++ b/tools/ps5/payload_patch_test/Makefile@@ -0,0 +1,16 @@+ifndef PS5_PAYLOAD_SDK+$(error PS5_PAYLOAD_SDK is undefined)+endif++include $(PS5_PAYLOAD_SDK)/toolchain/prospero.mk++CFLAGS := -std=c11 -O2 -g -Wall -Wextra+LDLIBS := -lkernel -lSceSystemService -lSceUserService -lpthread++all: patch_test.elf++patch_test.elf: main.c+ $(CC) $(CFLAGS) -o $@ main.c $(LDLIBS)++clean:+ rm -f patch_test.elfdiff --git a/tools/ps5/payload_patch_test/dump_shellcore.c b/tools/ps5/payload_patch_test/dump_shellcore.cnew file mode 100644index 0000000..e3ff470--- /dev/null+++ b/tools/ps5/payload_patch_test/dump_shellcore.c@@ -0,0 +1,90 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Read-only RE dump of SceShellCore for the user's own jailbroken 13.60 console.+// No patching, no unjail — pure kernel_proc_copyout of mapped ranges to /data,+// so the trophy daemon's checks/strings can be located offline (PHU-style port).+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>+#include <sys/types.h>+#include <sys/stat.h>+#include <sys/mman.h>+#include <sys/proc.h>+#include <sys/user.h>+#include <sys/sysctl.h>+#include <ps5/kernel.h>++extern void klog_printf(const char *fmt, ...);++static pid_t find_proc(const char* name) {+ int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC, 0};+ size_t sz = 0;+ if (sysctl(mib, 4, NULL, &sz, NULL, 0) != 0 || !sz) return 0;+ void* buf = malloc(sz);+ if (!buf) return 0;+ pid_t found = 0;+ if (sysctl(mib, 4, buf, &sz, NULL, 0) == 0) {+ for (void* p = buf; p < buf + sz; ) {+ struct kinfo_proc* ki = (struct kinfo_proc*)p;+ p += ki->ki_structsize;+ if (strstr(ki->ki_comm, name)) { found = ki->ki_pid; break; }+ }+ }+ free(buf);+ return found;+}++static intptr_t mapbase_of(pid_t pid) {+ int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, pid};+ size_t sz = 0;+ if (sysctl(mib, 4, NULL, &sz, NULL, 0) != 0 || !sz) return 0;+ char* buf = malloc(sz);+ if (!buf) return 0;+ intptr_t mb = 0;+ if (sysctl(mib, 4, buf, &sz, NULL, 0) == 0) {+ for (char* p = buf; p < buf + sz; ) {+ struct kinfo_vmentry* kve = (struct kinfo_vmentry*)p;+ if (kve->kve_structsize <= 0) break;+ p += kve->kve_structsize;+ if ((kve->kve_protection & 4) && kve->kve_offset == 0 && kve->kve_start < 0x200000000ULL) {+ mb = kve->kve_start; break;+ }+ }+ }+ free(buf);+ return mb;+}++static void dump_range(pid_t pid, intptr_t mb, const char* path, uintptr_t off, size_t len) {+ FILE* f = fopen(path, "wb");+ if (!f) { klog_printf("[SCDUMP] open fail %s\n", path); return; }+ uint64_t hdr[4] = {0x504d554443530ULL, (uint64_t)mb, (uint64_t)(mb + off), (uint64_t)len};+ fwrite(hdr, 1, sizeof(hdr), f);+ unsigned char* c = malloc(0x10000);+ size_t ok = 0;+ if (c) {+ for (size_t i = 0; i < len; i += 0x10000) {+ size_t n = (len - i) < 0x10000 ? (len - i) : 0x10000;+ if (kernel_proc_copyout(pid, mb + off + i, c, n) != 0) memset(c, 0, n);+ else ok += n;+ fwrite(c, 1, n, f);+ }+ free(c);+ }+ fclose(f);+ klog_printf("[SCDUMP] %s: base 0x%lx len 0x%zx readable ~0x%zx\n", path, mb + off, len, ok);+}++int main(void) {+ pid_t pid = find_proc("SceShellCore");+ intptr_t mb = mapbase_of(pid);+ klog_printf("[SCDUMP] SceShellCore pid=%d mapbase=0x%lx\n", pid, mb);+ if (pid <= 0 || mb == 0) return 1;+ // .text covering the trophy daemon + app-inventory/NP regions.+ dump_range(pid, mb, "/data/sc_text.bin", 0xb00000, 0x500000); // 0xb00000..0x1000000+ // rodata/data covering B1 strings ("AAAA00000"), vtables, dispatch tables.+ dump_range(pid, mb, "/data/sc_rodata.bin", 0x1a00000, 0x500000); // 0x1a00000..0x1f00000+ dump_range(pid, mb, "/data/sc_data.bin", 0x1f00000, 0x500000); // 0x1f00000..0x2400000+ klog_printf("[SCDUMP] done\n");+ return 0;+}diff --git a/tools/ps5/payload_patch_test/dump_shellcore.elf b/tools/ps5/payload_patch_test/dump_shellcore.elfnew file mode 100755index 0000000..22ec61aBinary files /dev/null and b/tools/ps5/payload_patch_test/dump_shellcore.elf differdiff --git a/tools/ps5/payload_patch_test/main.c b/tools/ps5/payload_patch_test/main.cnew file mode 100644index 0000000..1b1e43c--- /dev/null+++ b/tools/ps5/payload_patch_test/main.c@@ -0,0 +1,354 @@+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>+#include <sys/types.h>+#include <sys/stat.h>+#include <sys/mman.h>+#include <sys/proc.h>+#include <sys/user.h>+#include <sys/sysctl.h>+#include <ps5/kernel.h>++extern void klog_printf(const char *fmt, ...);++static pid_t find_process_by_name(const char* name) {+ int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC, 0};+ size_t buf_size = 0;+ if (sysctl(mib, 4, NULL, &buf_size, NULL, 0) != 0 || buf_size == 0) return 0;+ void *buf = malloc(buf_size);+ if (!buf) return 0;+ if (sysctl(mib, 4, buf, &buf_size, NULL, 0) != 0) {+ free(buf);+ return 0;+ }+ pid_t found = 0;+ for (void *ptr = buf; ptr < (buf + buf_size); ) {+ struct kinfo_proc *ki = (struct kinfo_proc*)ptr;+ ptr += ki->ki_structsize;+ if (strstr(ki->ki_comm, name) != NULL) {+ found = ki->ki_pid;+ break;+ }+ }+ free(buf);+ return found;+}++static intptr_t get_process_mapbase(pid_t pid) {+ int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, pid};+ size_t size = 0;+ if (sysctl(mib, 4, NULL, &size, NULL, 0) != 0 || size == 0) return 0;+ char *buf = malloc(size);+ if (!buf) return 0;+ intptr_t mapbase = 0;+ if (sysctl(mib, 4, buf, &size, NULL, 0) == 0) {+ for (char *p = buf; p < buf + size; ) {+ struct kinfo_vmentry *kve = (struct kinfo_vmentry*)p;+ if (kve->kve_structsize <= 0) break;+ p += kve->kve_structsize;+ if ((kve->kve_protection & 4) && kve->kve_offset == 0 && kve->kve_start < 0x200000000ULL) {+ mapbase = kve->kve_start;+ break;+ }+ }+ }+ free(buf);+ return mapbase;+}++static void unjail_pid(pid_t pid) {+ if (pid <= 0) return;+ intptr_t rootvnode = kernel_get_root_vnode();+ int r1 = kernel_set_proc_rootdir(pid, rootvnode);+ int r2 = kernel_set_proc_jaildir(pid, rootvnode);+ int r3 = kernel_set_ucred_uid(pid, 0);+ int r4 = kernel_set_ucred_ruid(pid, 0);+ int r5 = kernel_set_ucred_prison(pid, KERNEL_ADDRESS_PRISON0);+ uint8_t caps[16];+ memset(caps, 0xff, sizeof(caps));+ int r6 = kernel_set_ucred_caps(pid, caps);+ klog_printf("[TROPHY_PATCH] Unjailed PID %d: root=%d jail=%d uid=%d ruid=%d prison=%d caps=%d\n",+ pid, r1, r2, r3, r4, r5, r6);+}++static void apply_patch(pid_t pid, intptr_t addr, const unsigned char *patch, const unsigned char *expected_orig, size_t size, const char *name) {+ unsigned char orig[64] = {0};+ size_t check_len = size < 64 ? size : 64;+ kernel_proc_copyout(pid, addr, orig, check_len);+ klog_printf("[TROPHY_PATCH] %s at 0x%lx orig: %02x %02x %02x %02x %02x %02x\n",+ name, addr, orig[0], orig[1], orig[2], orig[3], orig[4], orig[5]);++ if (expected_orig && memcmp(orig, expected_orig, size) != 0) {+ // If already patched, verify it+ if (memcmp(orig, patch, size) == 0) {+ klog_printf("[TROPHY_PATCH] %s at 0x%lx already patched\n", name, addr);+ return;+ }+ klog_printf("[TROPHY_PATCH] ERROR: %s at 0x%lx orig bytes mismatch, skipping!\n", name, addr);+ return;+ }++ kernel_mprotect(pid, addr & ~0x3fff, 0x4000, PROT_READ | PROT_WRITE | PROT_EXEC);+ kernel_proc_copyin(pid, patch, addr, size);++ unsigned char verify[64] = {0};+ kernel_proc_copyout(pid, addr, verify, check_len);+ klog_printf("[TROPHY_PATCH] %s at 0x%lx patched: %02x %02x %02x %02x %02x %02x\n",+ name, addr, verify[0], verify[1], verify[2], verify[3], verify[4], verify[5]);+}++int main(void) {+ pid_t pid = find_process_by_name("SceShellCore");+ intptr_t mapbase = get_process_mapbase(pid);+ klog_printf("[TROPHY_PATCH] SceShellCore dynamic pid=%d, mapbase=0x%lx\n", pid, mapbase);++ if (pid <= 0 || mapbase == 0) {+ klog_printf("[TROPHY_PATCH] ERROR: Failed to resolve SceShellCore PID or mapbase\n");+ return 1;+ }++ // =====================================================================+ // SceShellCore trophy patches — CLEANED 2026-11-03.+ // From disassembling the live SceShellCore .text (RE workflows): the+ // collection/surfacing path is handler 0xe232e0 -> 0xe1a4c0 -> cache+ // ingest [cache_vtable+0x30]=0xe39310 -> fan-out 0xe34e70 (ShellUI). The+ // unlock subsystem (~0xe65xxx) is separate. REMOVED 7 past-agent patches+ // that targeted off-path / non-trophy / inert / counterproductive code:+ // old #1 0xc3ca78 account/NP gate (errors 0x8055001x), not trophy+ // old #3 0xe32600 wrong ctx-state predicate (==1; ingest uses ==0/==2)+ // old #7 0xe2175b inert null/validity guard (non-null args pass anyway)+ // old #12 0xe17a60 inert serviceLabel validator (we use label 1)+ // old #13 0xbcd5b8 generic app-manager find-by-id, not the trophy service+ // old #14 0xe17b80 inert context-param validator (valid params pass)+ // old #15 0xe4c980 serviceLabel==0 validator; bypass re-allowed label 0+ // (counterproductive vs AGENTS.md 8.3)+ // What remains below is trophy-mechanism only; final trim pends the chosen+ // surfacing approach (in-process funnel vs external service).+ // =====================================================================++ // [K1] Trophy config load/init guard (old #2):+ // Address: mapbase + 0xe6b1ff (file offset 0xe6f1ff)+ // 78 45 (js +0x45) -> 2x NOP+ const unsigned char orig_comm_info[] = {0x78, 0x45};+ const unsigned char patch_comm_info[] = {0x90, 0x90};+ apply_patch(pid, mapbase + 0xe6b1ff, patch_comm_info, orig_comm_info, sizeof(patch_comm_info), "Trophy config load guard (0xe6b1ff)");++ // [K2] Debug-unlock IPC gate (old #4):+ // Address: mapbase + 0xeb4716 (file offset 0xeb8716)+ // 75 36 (jne +0x36) -> 2x NOP+ const unsigned char orig_ipc_debug[] = {0x75, 0x36};+ const unsigned char patch_ipc_debug[] = {0x90, 0x90};+ apply_patch(pid, mapbase + 0xeb4716, patch_ipc_debug, orig_ipc_debug, sizeof(patch_ipc_debug), "Trophy debug IPC gate (0xeb4716)");++ // [K3] Debug/dev status gate a trophy handler checks; keep until the chosen path proves it unneeded.+ const unsigned char orig_debug_fn[] = {0x55, 0x48, 0x89, 0xe5, 0x53, 0x48};+ const unsigned char patch_debug_fn[] = {0xb8, 0x01, 0x00, 0x00, 0x00, 0xc3};+ apply_patch(pid, mapbase + 0xb20050, patch_debug_fn, orig_debug_fn, sizeof(patch_debug_fn), "Trophy debug/dev status gate (0xb20050)");++ // [K4] Unlock reader already-unlocked bitmap test (old #6):+ // Address: mapbase + 0xe5c1b4 (file offset 0xe601b4)+ // 0f 83 b8 00 00 00 (jae +0xb8) -> 6x NOP+ const unsigned char orig_bitmask_check[] = {0x0f, 0x83, 0xb8, 0x00, 0x00, 0x00};+ const unsigned char patch_bitmask_check[] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90};+ apply_patch(pid, mapbase + 0xe5c1b4, patch_bitmask_check, orig_bitmask_check, sizeof(patch_bitmask_check), "Unlock already-unlocked bitmap (0xe5c1b4)");++ // [K5] Unlock worker group bounds (old #8):+ // Address: mapbase + 0xe65c85 (file offset 0xe69c85)+ // 0f 83 02 01 00 00 (jae +0x102) -> 6x NOP+ const unsigned char orig_bounds1[] = {0x0f, 0x83, 0x02, 0x01, 0x00, 0x00};+ const unsigned char patch_6nop[] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90};+ apply_patch(pid, mapbase + 0xe65c85, patch_6nop, orig_bounds1, sizeof(patch_6nop), "Trophy Pack Group Check Bypass (0xe69c85)");++ // 9. Patch Trophy TrophyId Bounds Check (bypasses 0x80553904 check in 0xe69c9d):+ // Address: mapbase + 0xe65c9d (file offset 0xe69c9d)+ // 0f 83 ea 00 00 00 (jae +0xea) -> 6x NOP+ const unsigned char orig_bounds2[] = {0x0f, 0x83, 0xea, 0x00, 0x00, 0x00};+ apply_patch(pid, mapbase + 0xe65c9d, patch_6nop, orig_bounds2, sizeof(patch_6nop), "Trophy Pack TrophyId Check Bypass (0xe69c9d)");++ // 10. Patch Trophy Group ID Match Check (bypasses 0x80553999 check in 0xe69d35):+ // Address: mapbase + 0xe65d35 (file offset 0xe69d35)+ // 75 56 (jne +0x56) -> 2x NOP+ const unsigned char orig_group_match[] = {0x75, 0x56};+ const unsigned char patch_2nop[] = {0x90, 0x90};+ apply_patch(pid, mapbase + 0xe65d35, patch_2nop, orig_group_match, sizeof(patch_2nop), "Trophy Group ID Match Bypass (0xe69d35)");++ // 11. Patch Trophy Entry Size Match Check (bypasses 0x80553999 check in 0xe69d3f):+ // Address: mapbase + 0xe65d3f (file offset 0xe69d3f)+ // 75 4c (jne +0x4c) -> 2x NOP+ const unsigned char orig_size_match[] = {0x75, 0x4c};+ apply_patch(pid, mapbase + 0xe65d3f, patch_2nop, orig_size_match, sizeof(patch_2nop), "Trophy Entry Size Match Bypass (0xe69d3f)");++ // (removed old #12-#15: inert serviceLabel/param validators + the+ // counterproductive serviceLabel==0 bypass — see cleanup header above)++ // [K9] Pack-register precondition 1 (old #16):+ // Address: mapbase + 0xbf5a62 (file offset 0xbf9a62)+ // 80 7d 97 01 b8 5b b7 55 80 0f 85 cd 00 00 00 80 7d 96 00 0f 85 c3 00 00 00 -> jmp +0x17 (eb 17); 23x NOP+ const unsigned char orig_pack_check1[] = {+ 0x80, 0x7d, 0x97, 0x01, 0xb8, 0x5b, 0xb7, 0x55, 0x80, 0x0f, 0x85, 0xcd, 0x00, 0x00, 0x00,+ 0x80, 0x7d, 0x96, 0x00, 0x0f, 0x85, 0xc3, 0x00, 0x00, 0x00+ };+ const unsigned char patch_pack_check1[] = {+ 0xeb, 0x17, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90,+ 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90+ };+ apply_patch(pid, mapbase + 0xbf5a62, patch_pack_check1, orig_pack_check1, sizeof(patch_pack_check1), "Trophy Pack Check 1 Bypass (0xbf9a62)");++ // 17. Patch Trophy Context Register Pack Check 2 (bypasses 0x8055b75b in 0xbeb9a5):+ // Address: mapbase + 0xbe79a5 (file offset 0xbeb9a5)+ // 80 7d cf 01 b8 5b b7 55 80 75 56 80 7d ce 00 75 50 -> jmp +0x0f (eb 0f); 15x NOP+ const unsigned char orig_pack_check2[] = {+ 0x80, 0x7d, 0xcf, 0x01, 0xb8, 0x5b, 0xb7, 0x55, 0x80, 0x75, 0x56, 0x80, 0x7d, 0xce, 0x00, 0x75, 0x50+ };+ const unsigned char patch_pack_check2[] = {+ 0xeb, 0x0f, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90+ };+ apply_patch(pid, mapbase + 0xbe79a5, patch_pack_check2, orig_pack_check2, sizeof(patch_pack_check2), "Trophy Pack Check 2 Bypass (0xbeb9a5)");++ // [K11] RESTORE the collection ingest/commit function (old #18) @0xe1a4c0.+ // This fn IS the surfacing path (0xe232e0 -> here -> cache ingest 0xe39310+ // -> fan-out 0xe34e70 -> ShellUI). A past agent had stubbed it to+ // `xor eax,eax; ret`, disabling the only real surfacing function while+ // doing nothing for the debug-unlock path (which never reaches it). Write+ // the ORIGINAL prologue back so it stays intact. Idempotent: restores when+ // the old stub is present, and reports "already patched" once original.+ const unsigned char uds_orig[] = {0x55, 0x48, 0x89, 0xe5, 0x41, 0x57}; // real prologue+ const unsigned char uds_stub[] = {0x31, 0xc0, 0xc3, 0x90, 0x90, 0x90}; // the former no-op stub+ apply_patch(pid, mapbase + 0xe1a4c0, uds_orig, uds_stub, sizeof(uds_orig), "RESTORE collection-ingest fn (0xe1a4c0)");++ // 19. Patch Trophy Cache Auto-Enumerate Titles Check (bypasses suppression in 0xe2acea):+ // Address: mapbase + 0xe2acef (file offset 0xe2ecef)+ // 75 09 (jne +0x09) -> 2x NOP+ const unsigned char orig_enum_check[] = {0x75, 0x09};+ apply_patch(pid, mapbase + 0xe2acef, patch_2nop, orig_enum_check, sizeof(patch_2nop), "Trophy Auto-Enumerate Titles Bypass (0xe2acef)");++ // Cache Diagnostic: Inspect NpTrophy2CSCache live state+ intptr_t svc_ptr = 0;+ kernel_proc_copyout(pid, mapbase + 0x22269a0, &svc_ptr, sizeof(svc_ptr));+ klog_printf("[TROPHY_DIAG] SceShellCore NpTrophy2Service* at 0x%lx = 0x%lx\n", mapbase + 0x22269a0, svc_ptr);+ if (svc_ptr > 0) {+ intptr_t cache_ptr = 0;+ kernel_proc_copyout(pid, svc_ptr + 0x80, &cache_ptr, sizeof(cache_ptr));+ klog_printf("[TROPHY_DIAG] NpTrophy2CSCache* at 0x%lx+0x80 = 0x%lx\n", svc_ptr, cache_ptr);+ if (cache_ptr > 0) {+ uint32_t state = 0;+ kernel_proc_copyout(pid, cache_ptr + 0x30, &state, sizeof(state));+ uint8_t flags[16] = {0};+ kernel_proc_copyout(pid, cache_ptr + 0x08, flags, sizeof(flags));+ klog_printf("[TROPHY_DIAG] Cache flags: 0xc=%d, 0xd=%d, 0xe=%d, 0x14=%d, state=0x%x\n",+ flags[0x0c - 8], flags[0x0d - 8], flags[0x0e - 8], flags[0x14 - 8], state);++ unsigned char cbytes[128] = {0};+ kernel_proc_copyout(pid, cache_ptr, cbytes, sizeof(cbytes));+ klog_printf("[TROPHY_DIAG] Cache raw 00..1f: %016lx %016lx %016lx %016lx\n",+ *(uint64_t*)(cbytes+0), *(uint64_t*)(cbytes+8), *(uint64_t*)(cbytes+16), *(uint64_t*)(cbytes+24));+ klog_printf("[TROPHY_DIAG] Cache raw 20..3f: %016lx %016lx %016lx %016lx\n",+ *(uint64_t*)(cbytes+32), *(uint64_t*)(cbytes+40), *(uint64_t*)(cbytes+48), *(uint64_t*)(cbytes+56));+ klog_printf("[TROPHY_DIAG] Cache raw 40..5f: %016lx %016lx %016lx %016lx\n",+ *(uint64_t*)(cbytes+64), *(uint64_t*)(cbytes+72), *(uint64_t*)(cbytes+80), *(uint64_t*)(cbytes+88));+ klog_printf("[TROPHY_DIAG] Cache raw 60..7f: %016lx %016lx %016lx %016lx\n",+ *(uint64_t*)(cbytes+96), *(uint64_t*)(cbytes+104), *(uint64_t*)(cbytes+112), *(uint64_t*)(cbytes+120));+ }+ }++ // Scan SceShellCore heap to verify title presence+ {+ int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, pid};+ size_t size = 0;+ if (sysctl(mib, 4, NULL, &size, NULL, 0) == 0 && size > 0) {+ char *vmbuf = malloc(size);+ if (vmbuf && sysctl(mib, 4, vmbuf, &size, NULL, 0) == 0) {+ int found_aw = 0, found_fn = 0;+ for (char *p = vmbuf; p < vmbuf + size; ) {+ struct kinfo_vmentry *kve = (struct kinfo_vmentry*)p;+ if (kve->kve_structsize <= 0) break;+ p += kve->kve_structsize;+ if ((kve->kve_protection & 3) == 3 && kve->kve_start >= 0x800000000ULL && (kve->kve_end - kve->kve_start) <= 32*1024*1024) {+ size_t seg_sz = kve->kve_end - kve->kve_start;+ char *chunk = malloc(seg_sz);+ if (chunk) {+ if (kernel_proc_copyout(pid, kve->kve_start, chunk, seg_sz) == 0) {+ for (size_t i = 0; i + 12 <= seg_sz; i += 4) {+ if (!found_aw && memcmp(chunk + i, "NPWR36759_00", 12) == 0) {+ found_aw = 1;+ klog_printf("[TROPHY_DIAG] Animal Well (NPWR36759_00) found in SceShellCore heap at 0x%lx\n", kve->kve_start + i);+ }+ if (!found_fn && memcmp(chunk + i, "NPWR20561_00", 12) == 0) {+ found_fn = 1;+ klog_printf("[TROPHY_DIAG] Fortnite (NPWR20561_00) found in SceShellCore heap at 0x%lx\n", kve->kve_start + i);+ unsigned char node[128] = {0};+ kernel_proc_copyout(pid, kve->kve_start + i - 32, node, sizeof(node));+ klog_printf("[TROPHY_DIAG] Node -32..+0: %016lx %016lx %016lx %016lx\n",+ *(uint64_t*)(node+0), *(uint64_t*)(node+8), *(uint64_t*)(node+16), *(uint64_t*)(node+24));+ klog_printf("[TROPHY_DIAG] Node +0..+32: %016lx %016lx %016lx %016lx\n",+ *(uint64_t*)(node+32), *(uint64_t*)(node+40), *(uint64_t*)(node+48), *(uint64_t*)(node+56));+ klog_printf("[TROPHY_DIAG] Node +32..+64: %016lx %016lx %016lx %016lx\n",+ *(uint64_t*)(node+64), *(uint64_t*)(node+72), *(uint64_t*)(node+80), *(uint64_t*)(node+88));+ }+ }+ }+ free(chunk);+ }+ }+ }+ klog_printf("[TROPHY_DIAG] SceShellCore heap scan result: AnimalWell=%d, Fortnite=%d\n", found_aw, found_fn);+ }+ if (vmbuf) free(vmbuf);+ }+ }++ // Permissions for homebrew trophy dirs+ chmod("/user/app", 0777);+ chmod("/user/app/PPSA99810", 0777);+ chmod("/user/app/PPSA99810/sce_sys", 0777);+ chmod("/user/app/PPSA99810/sce_sys/trophy2", 0777);+ chmod("/user/app/PPSA99810/sce_sys/trophy2/npbind.dat", 0666);+ chmod("/user/app/PPSA99810/sce_sys/trophy2/trophy00.ucp", 0666);+ chmod("/user/appmeta/PPSA99810", 0777);+ chmod("/user/appmeta/PPSA99810/trophy2", 0777);+ chmod("/user/appmeta/PPSA99810/trophy2/npbind.dat", 0666);+ chmod("/user/appmeta/PPSA99810/trophy2/trophy00.ucp", 0666);+ chmod("/system_data/priv", 0777);+ chmod("/system_data/priv/appmeta", 0777);+ chmod("/system_data/priv/appmeta/PPSA99810", 0777);+ chmod("/system_data/priv/appmeta/PPSA99810/trophy2", 0777);+ chmod("/system_data/priv/appmeta/PPSA99810/trophy2/npbind.dat", 0666);+ chmod("/system_data/priv/appmeta/PPSA99810/trophy2/trophy00.ucp", 0666);++ // Permissions for Fortnite PPSA01922 trophy dirs+ chmod("/user/app/PPSA01922", 0777);+ chmod("/user/app/PPSA01922/sce_sys", 0777);+ chmod("/user/app/PPSA01922/sce_sys/param.json", 0666);+ chmod("/user/app/PPSA01922/sce_sys/trophy2", 0777);+ chmod("/user/app/PPSA01922/sce_sys/trophy2/npbind.dat", 0666);+ chmod("/user/app/PPSA01922/sce_sys/trophy2/trophy00.ucp", 0666);+ chmod("/user/appmeta/PPSA01922", 0777);+ chmod("/user/appmeta/PPSA01922/param.json", 0666);+ chmod("/user/appmeta/PPSA01922/trophy2", 0777);+ chmod("/user/appmeta/PPSA01922/trophy2/npbind.dat", 0666);+ chmod("/user/appmeta/PPSA01922/trophy2/trophy00.ucp", 0666);+ chmod("/system_data/priv/appmeta/PPSA01922", 0777);+ chmod("/system_data/priv/appmeta/PPSA01922/param.json", 0666);+ chmod("/system_data/priv/appmeta/PPSA01922/trophy2", 0777);+ chmod("/system_data/priv/appmeta/PPSA01922/trophy2/npbind.dat", 0666);+ chmod("/system_data/priv/appmeta/PPSA01922/trophy2/trophy00.ucp", 0666);++ // Unjail eboot.bin from pidfile+ FILE* f = fopen("/data/psbox/eboot_pid.txt", "r");+ if (f) {+ pid_t eboot_pid = 0;+ if (fscanf(f, "%d", &eboot_pid) == 1 && eboot_pid > 0) {+ unjail_pid(eboot_pid);+ }+ fclose(f);+ }++ // Also search for running eboot.bin if any+ pid_t scan_pid = find_process_by_name("eboot.bin");+ if (scan_pid > 0) {+ unjail_pid(scan_pid);+ }++ return 0;+}diff --git a/tools/ps5/payload_patch_test/patch_test.elf b/tools/ps5/payload_patch_test/patch_test.elfnew file mode 100755index 0000000..e8456a2Binary files /dev/null and b/tools/ps5/payload_patch_test/patch_test.elf differdiff --git a/tools/ps5/ps5_dev.py b/tools/ps5/ps5_dev.pyindex a1b43f0..0e3d3c1 100755--- a/tools/ps5/ps5_dev.py+++ b/tools/ps5/ps5_dev.py@@ -187,7 +187,7 @@ def cmd_test(args):"tunetest", "confirmtest", "pickertest", "menutest", "regiontest","friendstest", "publishertest", "scrolltest", "quicktest", "tlscheck","padspktest", "queuetest", "queueuitest", "wishlisttest", "block1test",- "block2test", "block3test", "bitratetest", "touchpadtest", "mw4test", "v150test", "claimtest",+ "block2test", "block3test", "bitratetest", "touchpadtest", "mw4test", "v150test", "claimtest", "trophytest",}bitrate_opt = f" bitrate={args.bitrate}" if getattr(args, "bitrate", 0) > 0 else ""if target.startswith("AUTOTEST") or target.startswith("BENCH") or " " in target:@@ -235,14 +235,25 @@ def cmd_test(args):"stream_menu_touchpad.ppm", "launch_screen_hint.ppm", "search_mw4.ppm", "details_mw4.ppm","v150_settings.ppm", "v150_search_free.ppm","claim1_details_before.ppm", "claim2_details_playable.ppm", "claim3_my_games_unrefreshed.ppm",- "claim4_launching.ppm", "claim5_stream.ppm"):+ "claim4_launching.ppm", "claim5_stream.ppm", "trophy_settings.ppm", "trophy_synced.ppm"):try:ftp.sendcmd(f"DELE {name}")except (error_perm, error_reply):pass- # Write autoplay.txt+ if "trophytest" in autoplay_cmd:+ try:+ ftp.sendcmd("DELE trophies/267695549.json")+ except (error_perm, error_reply):+ pass++ # Write autoplay.txt to both data directoriesftp.storbinary("STOR autoplay.txt", io.BytesIO(autoplay_cmd.encode() + b"\n"))+ try:+ ftp.cwd(f"/data/homebrew/{TITLE_ID}")+ ftp.storbinary("STOR autoplay.txt", io.BytesIO(autoplay_cmd.encode() + b"\n"))+ except Exception:+ passftp.quit()print(f" 4. Launching test on console ({autoplay_cmd})...")@@ -280,7 +291,7 @@ def cmd_test(args):"stream_menu_touchpad.ppm", "launch_screen_hint.ppm", "search_mw4.ppm", "details_mw4.ppm","v150_settings.ppm", "v150_search_free.ppm","claim1_details_before.ppm", "claim2_details_playable.ppm", "claim3_my_games_unrefreshed.ppm",- "claim4_launching.ppm", "claim5_stream.ppm"]+ "claim4_launching.ppm", "claim5_stream.ppm", "trophy_settings.ppm", "trophy_synced.ppm"]ftp = get_ftp(host, port)ftp.cwd("/data/psbox")for name in ppm_names + ["xcloud.log"]:diff --git a/tools/ps5/register_title_db.py b/tools/ps5/register_title_db.pynew file mode 100644index 0000000..9a5aa74--- /dev/null+++ b/tools/ps5/register_title_db.py@@ -0,0 +1,343 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-3.0-or-later+# Copyright (C) 2026 RafaelNGP+"""+Registers a game title (e.g. Fortnite PPSA01922) into /system_data/priv/mms/app.db+and appinfo.db so the PS5 OS Trophy application enumerates and displays it.+Modeled on official PS5 titles in the user database (Animal Well PPSA22520).+"""++import io+import json+import os+import sqlite3+import sys+from ftplib import FTP++DEFAULT_HOST = os.environ.get("PS5_HOST", "192.168.15.17")+DEFAULT_PORT = int(os.environ.get("FTP_PORT", "2121"))+++def get_ftp(host=DEFAULT_HOST, port=DEFAULT_PORT):+ ftp = FTP()+ ftp.connect(host, port, timeout=15)+ ftp.login()+ return ftp+++def backup_and_download(ftp, remote_path, local_path):+ print(f"Downloading {remote_path} -> {local_path}...")+ bio = io.BytesIO()+ ftp.retrbinary(f"RETR {remote_path}", bio.write)+ data = bio.getvalue()+ with open(local_path, "wb") as f:+ f.write(data)+ # Also backup on PS5 if not already backed up+ bak_path = remote_path + ".bak"+ try:+ ftp.sendcmd(f"RNFR {remote_path}")+ # do not rename, upload copy as .bak+ except Exception:+ pass+ try:+ ftp.storbinary(f"STOR {bak_path}", io.BytesIO(data))+ print(f"Backed up {remote_path} to {bak_path} on console.")+ except Exception as e:+ print(f"Notice: backup to {bak_path} failed: {e}")+ return local_path+++def upload_file(ftp, local_path, remote_path):+ print(f"Uploading {local_path} -> {remote_path}...")+ with open(local_path, "rb") as f:+ ftp.storbinary(f"STOR {remote_path}", f)+ print(f"Successfully uploaded {remote_path}")+++def register_title_app_db(local_db_path, model_title_id="PPSA22520",+ target_title_id="PPSA01922",+ target_title_name="Fortnite",+ target_content_id="UP1477-PPSA01922_00-FORTNITECORE0001",+ target_concept_id=210118,+ target_local_concept_id="cid:scp:00000000000334c6"):+ conn = sqlite3.connect(local_db_path)+ conn.row_factory = sqlite3.Row+ c = conn.cursor()++ # 1. tbl_contentinfo+ c.execute("SELECT * FROM tbl_contentinfo WHERE titleId = ?", (target_title_id,))+ if c.fetchone() is None:+ c.execute("SELECT * FROM tbl_contentinfo WHERE titleId = ?", (model_title_id,))+ model_row = dict(c.fetchone())+ new_row = dict(model_row)+ new_row["titleId"] = target_title_id+ new_row["contentId"] = target_content_id+ new_row["titleName"] = target_title_name+ new_row["metaDataPath"] = f"/system_data/priv/appmeta/{target_title_id}"+ new_row["conceptId"] = target_concept_id+ new_row["localConceptId"] = target_local_concept_id+ new_row["pprDeeplinkUri"] = f"psgm:play?id={target_title_id}"+ new_row["pprHubAppUri"] = f"pshome:gamehub?titleId={target_title_id}"+ new_row["snd0Info"] = f"/user/appmeta/{target_title_id}/snd0.at9"+ new_row["icon0Info"] = f"/user/app/{target_title_id}/sce_sys/icon0.png"+ new_row["pic0Info"] = f"/user/app/{target_title_id}/sce_sys/pic0.png"+ new_row["appType"] = 1 # 1 = Game++ if new_row.get("AppInfoJson"):+ try:+ info = json.loads(new_row["AppInfoJson"])+ info["TITLE_ID"] = target_title_id+ info["TITLE"] = target_title_name+ info["CONTENT_ID"] = target_content_id+ info["CONCEPT_ID"] = target_concept_id+ info["APP_TYPE"] = 1+ info["ATTRIBUTE3"] = 1835012+ info["DEEPLINK_URI"] = f"psgm:play?id={target_title_id}"+ info["HUBAPP_URI"] = f"pshome:gamehub?titleId={target_title_id}"+ info["_metadata_path"] = f"/system_data/priv/appmeta/{target_title_id}"+ info["_org_path"] = f"/user/app/{target_title_id}"+ info["_local_concept_id"] = target_local_concept_id+ for k in list(info.keys()):+ if k.startswith("TITLE_") and k != "TITLE_ID":+ info[k] = target_title_name+ new_row["AppInfoJson"] = json.dumps(info)+ except Exception as e:+ print(f"Warning: AppInfoJson parse failed: {e}")++ cols = list(new_row.keys())+ placeholders = ", ".join(["?"] * len(cols))+ c.execute(f"INSERT INTO tbl_contentinfo ({', '.join(cols)}) VALUES ({placeholders})",+ [new_row[col] for col in cols])+ print(f"Inserted {target_title_id} into tbl_contentinfo")+ else:+ print(f"{target_title_id} already exists in tbl_contentinfo, updating...")+ c.execute("SELECT AppInfoJson FROM tbl_contentinfo WHERE titleId = ?", (target_title_id,))+ row = c.fetchone()+ app_json_str = None+ if row and row["AppInfoJson"]:+ try:+ info = json.loads(row["AppInfoJson"])+ info["TITLE_ID"] = target_title_id+ info["TITLE"] = target_title_name+ info["CONTENT_ID"] = target_content_id+ info["CONCEPT_ID"] = target_concept_id+ info["APP_TYPE"] = 1+ info["ATTRIBUTE3"] = 1835012+ for k in list(info.keys()):+ if k.startswith("TITLE_") and k != "TITLE_ID":+ info[k] = target_title_name+ app_json_str = json.dumps(info)+ except Exception:+ pass+ if app_json_str:+ c.execute("UPDATE tbl_contentinfo SET appType = 1, titleName = ?, contentId = ?, conceptId = ?, AppInfoJson = ? WHERE titleId = ?",+ (target_title_name, target_content_id, target_concept_id, app_json_str, target_title_id))+ else:+ c.execute("UPDATE tbl_contentinfo SET appType = 1, titleName = ?, contentId = ?, conceptId = ? WHERE titleId = ?",+ (target_title_name, target_content_id, target_concept_id, target_title_id))++ # 2. All tbl_iconinfo_* tables+ c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'tbl_iconinfo_%'")+ icon_tables = [r[0] for r in c.fetchall()]+ for tbl in icon_tables:+ c.execute(f"SELECT * FROM {tbl} WHERE titleId = ?", (target_title_id,))+ if c.fetchone() is None:+ c.execute(f"SELECT * FROM {tbl} WHERE titleId = ?", (model_title_id,))+ model_row = c.fetchone()+ if model_row:+ new_row = dict(model_row)+ new_row["titleId"] = target_title_id+ new_row["titleName"] = target_title_name+ new_row["contentId"] = target_content_id+ new_row["conceptId"] = target_concept_id+ new_row["localConceptId"] = target_local_concept_id+ new_row["visible"] = 1+ new_row["installStatus"] = 2+ new_row["appDrmType"] = 5+ new_row["deeplinkUri"] = f"psgm:play?id={target_title_id}"+ new_row["hubAppUri"] = f"pshome:gamehub?titleId={target_title_id}"++ cols = list(new_row.keys())+ placeholders = ", ".join(["?"] * len(cols))+ c.execute(f"INSERT INTO {tbl} ({', '.join(cols)}) VALUES ({placeholders})",+ [new_row[col] for col in cols])+ print(f"Inserted {target_title_id} into {tbl}")+ else:+ print(f"{target_title_id} already exists in {tbl}, updating...")+ c.execute(f"UPDATE {tbl} SET conceptId = ?, localConceptId = ?, contentId = ?, titleName = ?, visible = 1, installStatus = 2, appDrmType = 5 WHERE titleId = ?",+ (target_concept_id, target_local_concept_id, target_content_id, target_title_name, target_title_id))++ # 3. All tbl_concepticoninfo_* tables+ c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'tbl_concepticoninfo_%'")+ concept_tables = [r[0] for r in c.fetchall()]+ for tbl in concept_tables:+ c.execute(f"SELECT * FROM {tbl} WHERE primaryTitleId = ?", (target_title_id,))+ if c.fetchone() is None:+ c.execute(f"SELECT * FROM {tbl} WHERE primaryTitleId = ?", (model_title_id,))+ model_row = c.fetchone()+ if model_row:+ new_row = dict(model_row)+ new_row["localConceptId"] = target_local_concept_id+ new_row["conceptId"] = target_concept_id+ new_row["conceptName"] = target_title_name+ new_row["primaryTitleId"] = target_title_id+ new_row["primaryTitleName"] = target_title_name+ new_row["deeplinkUri"] = f"psgm:play?id={target_title_id}"+ new_row["hubAppUri"] = f"pshome:gamehub?titleId={target_title_id}"+ new_row["metaDataPath"] = f"/system_data/priv/appmeta/{target_title_id}"+ new_row["icon0Info"] = f"/user/app/{target_title_id}/sce_sys/icon0.png"+ new_row["pic0Info"] = f"/user/app/{target_title_id}/sce_sys/pic0.png"+ new_row["snd0Info"] = f"/user/app/{target_title_id}/sce_sys/snd0.at9"++ cols = list(new_row.keys())+ placeholders = ", ".join(["?"] * len(cols))+ c.execute(f"INSERT INTO {tbl} ({', '.join(cols)}) VALUES ({placeholders})",+ [new_row[col] for col in cols])+ print(f"Inserted {target_title_id} into {tbl}")+ else:+ print(f"{target_title_id} already exists in {tbl}, updating...")+ c.execute(f"UPDATE {tbl} SET conceptId = ?, conceptName = ?, primaryTitleName = ? WHERE primaryTitleId = ?",+ (target_concept_id, target_title_name, target_title_name, target_title_id))++ conn.commit()+ # Check integrity+ c.execute("PRAGMA integrity_check")+ res = c.fetchone()[0]+ if res != "ok":+ raise RuntimeError(f"Database integrity check failed: {res}")+ print("app.db integrity check passed: ok")+ conn.close()+++def register_title_appinfo_db(local_db_path, model_title_id="PPSA22520",+ target_title_id="PPSA01922",+ target_title_name="Fortnite",+ target_content_id="UP1477-PPSA01922_00-FORTNITECORE0001",+ target_concept_id=210118,+ target_local_concept_id="cid:scp:00000000000334c6"):+ conn = sqlite3.connect(local_db_path)+ c = conn.cursor()++ c.execute("SELECT COUNT(*) FROM tbl_appinfo WHERE titleId = ?", (target_title_id,))+ count = c.fetchone()[0]+ if count == 0:+ c.execute("SELECT metaDataId, key, val FROM tbl_appinfo WHERE titleId = ?", (model_title_id,))+ rows = c.fetchall()+ for metaDataId, key, val in rows:+ new_val = val+ if isinstance(val, str):+ if val == model_title_id:+ new_val = target_title_id+ elif "ANIMAL WELL" in val:+ new_val = val.replace("ANIMAL WELL", target_title_name)+ elif "JP8399-PPSA22520_00-0036675864053061" in val:+ new_val = target_content_id+ elif "cid:scp:000000000098a83e" in val:+ new_val = target_local_concept_id+ elif f"/user/app/{model_title_id}" in val:+ new_val = val.replace(f"/user/app/{model_title_id}", f"/user/app/{target_title_id}")+ elif key == "CONCEPT_ID":+ new_val = target_concept_id+ c.execute("INSERT OR REPLACE INTO tbl_appinfo (titleId, metaDataId, key, val) VALUES (?, ?, ?, ?)",+ (target_title_id, metaDataId, key, new_val))+ print(f"Inserted {len(rows)} key/value entries for {target_title_id} into tbl_appinfo")+ else:+ print(f"{target_title_id} already has {count} entries in tbl_appinfo, updating values...")+ c.execute("UPDATE tbl_appinfo SET val = ? WHERE titleId = ? AND key = 'CONTENT_ID'",+ (target_content_id, target_title_id))+ c.execute("UPDATE tbl_appinfo SET val = ? WHERE titleId = ? AND key = 'CONCEPT_ID'",+ (target_concept_id, target_title_id))+ c.execute("UPDATE tbl_appinfo SET val = ? WHERE titleId = ? AND key = 'TITLE_ID'",+ (target_title_id, target_title_id))+ c.execute("UPDATE tbl_appinfo SET val = ? WHERE titleId = ? AND key = 'APP_TYPE'",+ (1, target_title_id))+ c.execute("UPDATE tbl_appinfo SET val = ? WHERE titleId = ? AND key = 'ATTRIBUTE3'",+ (1835012, target_title_id))+ c.execute("UPDATE tbl_appinfo SET val = ? WHERE titleId = ? AND key = '_local_concept_id'",+ (target_local_concept_id, target_title_id))+++ conn.commit()+ c.execute("PRAGMA integrity_check")+ res = c.fetchone()[0]+ if res != "ok":+ raise RuntimeError(f"appinfo.db integrity check failed: {res}")+ print("appinfo.db integrity check passed: ok")+ conn.close()+++def ensure_ftp_dirs(ftp, paths):+ for path in paths:+ parts = path.strip("/").split("/")+ cur = ""+ for p in parts:+ cur += "/" + p+ try:+ ftp.mkd(cur)+ except Exception:+ pass+++def main():+ host = os.environ.get("PS5_HOST", DEFAULT_HOST)+ port = int(os.environ.get("FTP_PORT", str(DEFAULT_PORT)))+ print(f"Connecting to PS5 FTP at {host}:{port}...")+ ftp = get_ftp(host, port)++ # 1. Register in app.db+ local_app_db = "/tmp/ps5_app.db"+ backup_and_download(ftp, "/system_data/priv/mms/app.db", local_app_db)+ register_title_app_db(local_app_db)+ upload_file(ftp, local_app_db, "/system_data/priv/mms/app.db")++ # 2. Register in appinfo.db+ local_appinfo_db = "/tmp/ps5_appinfo.db"+ backup_and_download(ftp, "/system_data/priv/mms/appinfo.db", local_appinfo_db)+ register_title_appinfo_db(local_appinfo_db)+ upload_file(ftp, local_appinfo_db, "/system_data/priv/mms/appinfo.db")++ # 3. Ensure directories for PPSA01922+ target_dirs = [+ "/system_data/priv/appmeta/PPSA01922",+ "/system_data/priv/appmeta/PPSA01922/trophy2",+ "/system_data/priv/appmeta/PPSA01922/uds",+ "/user/appmeta/PPSA01922",+ "/user/appmeta/PPSA01922/trophy2",+ "/user/appmeta/PPSA01922/uds",+ "/user/app/PPSA01922",+ "/user/app/PPSA01922/sce_sys",+ "/user/app/PPSA01922/sce_sys/trophy2",+ "/user/app/PPSA01922/sce_sys/uds",+ "/user/np_uds/nobackup/conf/NPWR20561_00",+ ]+ ensure_ftp_dirs(ftp, target_dirs)++ # 4. Upload genuine icon and banner if available locally+ for icon_name, local_path in [("icon0.png", "/tmp/fortnite_icon0.png"), ("pic0.png", "/tmp/fortnite_pic0.png")]:+ if os.path.exists(local_path):+ with open(local_path, "rb") as f:+ data = f.read()+ for remote_dir in ["/system_data/priv/appmeta/PPSA01922", "/user/app/PPSA01922/sce_sys"]:+ try:+ ftp.storbinary(f"STOR {remote_dir}/{icon_name}", io.BytesIO(data))+ print(f"Uploaded {icon_name} to {remote_dir}")+ except Exception as e:+ print(f"Failed to upload {icon_name} to {remote_dir}: {e}")++ # 5. Upload UDS package if available locally+ if os.path.exists("/tmp/fortnite_uds.ucp"):+ with open("/tmp/fortnite_uds.ucp", "rb") as f:+ uds_data = f.read()+ try:+ ftp.storbinary("STOR /user/np_uds/nobackup/conf/NPWR20561_00/uds.ucp", io.BytesIO(uds_data))+ ftp.storbinary("STOR /user/app/PPSA01922/sce_sys/uds/uds00.ucp", io.BytesIO(uds_data))+ print("Uploaded uds.ucp to /user/np_uds/ and /user/app/uds/")+ except Exception as e:+ print(f"Failed to upload uds.ucp: {e}")++ ftp.quit()+ print("All title registrations and assets deployed successfully!")+++if __name__ == "__main__":+ main()