Compare commits

...
250 changed files with 8259 additions and 1192 deletions

No files matched your search

+120
View File
@@ -1,5 +1,125 @@
# 更新日志
## client 2.38.11+client.0.2.19 · 2026-11-12
> type: update
### en_us: Version 2.38.11 and farm editing improvements
- Update the game client and resources to 2.38.11.
- Add rotation and removal for multiple selected objects in the farm editor, including removing editable buildings below their usual minimum count.
- Gather friend online indicators, pass reward popups, My Room wallpaper fixes, commission navigation fixes, startup window preferences and performance overlay controls in BetterExperience. Each module can be enabled or disabled separately.
- Refresh extracted sound banks when the game resources or sound quality change, fixing stale audio after updates.
- Keep inventory and storage capacity checks aligned with the server's item stack rules, including unlimited stacks, and refresh changed stacks correctly.
### zh_cn: 2.38.11 更新与农场编辑优化
- 游戏客户端和资源更新至 2.38.11。
- 农场编辑器支持对多选物件整体旋转和批量移除,并可移除原本受最低保留数量限制的可编辑建筑。
- 好友在线标记、通行证领奖弹窗、小屋墙纸修复、委托导航修复、启动窗口偏好和性能浮层控制统一归入 BetterExperience,各模块可独立开关。
- 游戏资源或音质设置变化后刷新已提取的音频库,修复更新后沿用旧音频缓存的问题。
- 背包和仓库容量判断与服务器的物品堆叠规则同步,支持无限堆叠,并正确刷新发生变化的堆叠。
### zh_tw: 2.38.11 更新與農場編輯改善
- 遊戲用戶端與資源更新至 2.38.11。
- 農場編輯器支援整體旋轉及批次移除多選物件,並可移除原本受最低保留數量限制的可編輯建築。
- 好友上線標記、通行證領獎視窗、小屋牆紙修正、委託導航修正、啟動視窗偏好及效能浮層控制統一移至 BetterExperience,各模組可獨立開關。
- 遊戲資源或音質設定變更後更新已擷取的音效資料,修正更新後仍使用舊音效快取的問題。
- 背包及倉庫容量判斷與伺服器的物品堆疊規則同步,支援無限堆疊,並正確更新發生變化的堆疊。
### ja_jp: 2.38.11対応と農場編集の改善
- ゲームクライアントとリソースを2.38.11に更新しました。
- 農場エディターで複数選択したオブジェクトの一括回転と撤去に対応しました。編集可能な建物は通常の最低設置数を下回って撤去できます。
- フレンドのオンライン表示、パス報酬のポップアップ、マイルームの壁紙修正、依頼のナビゲーション修正、起動時のウィンドウ設定、パフォーマンス表示の制御をBetterExperienceにまとめました。各機能を個別に切り替えられます。
- リソースや音質設定の変更時に展開済みのサウンドデータを更新し、アップデート後も古い音声キャッシュが使われる問題を修正しました。
- インベントリと倉庫の容量判定をサーバーのスタック設定に合わせ、無制限スタックとスタック変更後の表示更新に対応しました。
### ko_kr: 2.38.11 업데이트 및 농장 편집 개선
- 게임 클라이언트와 리소스를 2.38.11로 업데이트했습니다.
- 농장 편집기에서 여러 오브젝트를 선택해 함께 회전하거나 일괄 제거할 수 있습니다. 편집 가능한 건물은 기본 최소 배치 수 아래로도 제거할 수 있습니다.
- 친구 온라인 표시, 패스 보상 팝업, 마이룸 벽지 수정, 의뢰 길 안내 수정, 시작 시 창 모드 설정과 성능 표시 제어를 BetterExperience로 모았습니다. 각 모듈을 개별적으로 켜고 끌 수 있습니다.
- 게임 리소스나 음질 설정이 바뀌면 추출된 사운드 데이터를 갱신하여 업데이트 후에도 오래된 오디오 캐시가 사용되던 문제를 수정했습니다.
- 인벤토리와 창고의 용량 판정을 서버의 아이템 중첩 규칙과 동기화하고 무제한 중첩 및 변경된 중첩의 표시 갱신을 지원합니다.
## server 2.38.11+server.0.2.6 · 2026-11-12
> type: update
> migration: irreversible
> backup: yes
### en_us: Element draws, battle sharing and gameplay fixes
- Update game content, event schedules and gameplay rules for 2.38.11. Back up and migrate 2.37.13 saves before starting this version; reverting only the server program cannot roll back an upgraded save.
- Support element-selected draws using the required tickets, with rewards restricted to the selected element. Retrying the same draw preserves its result and avoids repeated payment.
- Save shop favorites to the account and import favorites previously stored by the client.
- Add separate attack and defense presets for Mirror War, including slot expansion, names, icons and skill settings. Support Golden Colosseum's direct opponent matching and its season's first-turn rules.
- Preserve turn counts across multi-phase battles, fixing disconnects when entering the next boss phase.
- Create, look up and delete battle record sharing codes, retaining a history of up to ten codes. Correct costume burst levels and potentials in previously saved battle records.
- Restore missing permanent content unlock tickets from earned progression and reward records, covering story packs, avatar onboarding, cafeteria introductions and fishing trap unlocks. Check timed tickets against their expiration.
- Correct event and guide mission completion totals, including progress restored from rewards already claimed. Send expired daily and weekly mission compensation mail in the player's game language.
- Correct fishing trap timers and settlement. Boat upgrades collect the current catch, honor auto-sell and apply fishing experience; selling fish also updates the fish inventory correctly.
- Support removing editable farm buildings below their minimum count with BetterExperience, and keep inventory stack limits consistent with each account's rules.
- Add a collaboration avatar gift with matching outfit pieces, skipping characters and pieces already owned when claimed.
### zh_cn: 属性抽取、战斗分享与玩法修复
- 游戏内容、活动日程和玩法规则更新至 2.38.11。启动前须备份并迁移 2.37.13 存档;存档升级后,仅回退服务端程序无法恢复旧版本。
- 支持使用指定门票进行属性选择抽取,奖励限定为所选属性;相同抽取请求重试时保留原结果,避免重复扣券。
- 商店收藏随账号保存,并导入旧客户端本地保存的收藏。
- 镜中之战新增独立的进攻、防守预设,支持扩展栏位、名称、图标和技能设置;黄金竞技场支持直接匹配对手,并正确遵循赛季先后手规则。
- 多阶段战斗切换时正确保留回合数,修复进入 Boss 下一阶段时断开连接的问题。
- 支持创建、查询和删除战斗记录分享码,保留最多十条分享码历史;修正旧战斗记录中的服装爆发等级与潜能显示。
- 依据已达成进度和已领取奖励记录恢复缺失的永久玩法解锁凭证,涵盖剧情卡带、虚拟形象初始选择、餐厅介绍和鱼篓解锁;限时凭证按有效期校验。
- 修正活动及引导任务的完成数量统计,已领取奖励对应的进度也能恢复;日常、周常任务到期补发邮件按玩家游戏语言发送。
- 修正鱼篓计时和结算;升级钓鱼船时结算当前渔获,遵循自动出售选项并发放钓鱼经验,出售鱼类后正确更新鱼类背包。
- 配合 BetterExperience 支持移除低于最低保留数量的可编辑农场建筑,并保持物品堆叠上限与账号规则一致。
- 新增联动虚拟形象及配套服饰赠礼,领取时跳过已拥有的角色和部件。
### zh_tw: 屬性抽取、戰鬥分享與玩法修正
- 遊戲內容、活動日程及玩法規則更新至 2.38.11。啟動前須備份並遷移 2.37.13 存檔;存檔升級後,僅退回伺服器程式無法還原舊版本。
- 支援使用指定票券進行屬性選擇抽取,獎勵限定為所選屬性;重試相同抽取請求時保留原結果,避免重複扣券。
- 商店收藏隨帳號儲存,並匯入舊用戶端保存在本機的收藏。
- 鏡中之戰新增獨立的進攻、防守預設,支援擴充欄位、名稱、圖示及技能設定;黃金競技場支援直接配對對手,並正確遵循賽季先後手規則。
- 多階段戰鬥切換時正確保留回合數,修正進入 Boss 下一階段時斷線的問題。
- 支援建立、查詢及刪除戰鬥記錄分享碼,保留最多十筆分享碼歷史;修正舊戰鬥記錄中的服裝爆發等級及潛能顯示。
- 依據已達成進度與已領取獎勵記錄,恢復遺失的永久玩法解鎖憑證,涵蓋劇情卡帶、虛擬形象初始選擇、餐廳介紹及魚簍解鎖;限時憑證依有效期限驗證。
- 修正活動及引導任務的完成數量統計,也能恢復已領獎對應的進度;日常、週常任務到期補發郵件依玩家遊戲語言寄送。
- 修正魚簍計時及結算;升級釣魚船時結算目前漁獲,遵循自動出售選項並發放釣魚經驗,出售魚類後正確更新魚類背包。
- 配合 BetterExperience 支援移除低於最低保留數量的可編輯農場建築,並維持物品堆疊上限與帳號規則一致。
- 新增聯動虛擬形象及配套服飾贈禮,領取時略過已擁有的角色及部件。
### ja_jp: 属性選択ガチャ、戦闘共有と不具合修正
- ゲームコンテンツ、イベント日程、各種ルールを2.38.11に更新しました。起動前に2.37.13のセーブデータをバックアップして移行してください。移行後はサーバープログラムだけを戻しても旧バージョンには戻せません。
- 専用チケットを使う属性選択ガチャに対応し、選択した属性の報酬を抽選します。同じ抽選の再送時は結果を保持し、チケットの重複消費を防ぎます。
- ショップのお気に入りをアカウントに保存し、旧クライアントのローカル設定を取り込みます。
- 鏡戦争に攻撃用と防御用の独立したプリセットを追加し、枠の拡張、名前、アイコン、スキル設定に対応しました。黄金の闘技場の直接マッチングと、シーズンごとの先攻・後攻ルールに対応しました。
- 複数段階の戦闘でターン数を維持し、ボスの次段階に移る際に切断される問題を修正しました。
- 戦闘記録の共有コードの作成、検索、削除に対応し、最大10件のコード履歴を保持します。以前の戦闘記録でコスチュームのバーストレベルと潜在能力が入れ替わる問題を修正しました。
- 達成済みの進行や受取済みの報酬を基に、不足した永続コンテンツ解放チケットを復元します。ストーリーパック、アバターの初回選択、食堂の紹介、魚かごの解放に対応し、期限付きチケットの有効期限も確認します。
- イベントとガイドミッションの完了数を修正し、受取済み報酬からも進捗を復元します。期限切れの日次・週次ミッションの補填メールをプレイヤーのゲーム言語で送ります。
- 魚かごのタイマーと受取処理を修正しました。釣り船の強化時に現在の漁獲を回収し、自動売却設定と釣り経験値を反映します。魚の売却後も所持一覧を正しく更新します。
- BetterExperienceと組み合わせて、編集可能な農場建物を最低設置数未満まで撤去できます。アイテムのスタック上限もアカウントの設定に合わせます。
- コラボアバターと対応する衣装パーツのプレゼントを追加しました。受取時に所持済みのキャラクターとパーツを除外します。
### ko_kr: 속성 선택 뽑기, 전투 공유 및 플레이 수정
- 게임 콘텐츠, 이벤트 일정과 플레이 규칙을 2.38.11로 업데이트했습니다. 실행 전에 2.37.13 저장 데이터를 백업하고 이전해야 합니다. 저장 데이터 업그레이드 후에는 서버 프로그램만 되돌려 이전 버전으로 복구할 수 없습니다.
- 지정된 티켓을 사용하는 속성 선택 뽑기를 지원하며 선택한 속성의 보상만 추첨합니다. 동일한 뽑기 요청을 재시도하면 기존 결과를 유지하고 티켓 중복 소모를 방지합니다.
- 상점 즐겨찾기를 계정에 저장하고 이전 클라이언트의 로컬 즐겨찾기를 가져옵니다.
- 거울전쟁에 공격용과 방어용 프리셋을 따로 추가하고 슬롯 확장, 이름, 아이콘과 스킬 설정을 지원합니다. 황금 투기장의 직접 상대 매칭과 시즌별 선후공 규칙을 지원합니다.
- 다단계 전투에서 턴 수를 유지하여 보스의 다음 단계로 넘어갈 때 연결이 끊기던 문제를 수정했습니다.
- 전투 기록 공유 코드 생성, 조회와 삭제를 지원하고 최대 10개의 코드 이력을 보관합니다. 이전 전투 기록의 코스튬 버스트 레벨 및 잠재력 표시를 수정했습니다.
- 달성한 진행도와 수령한 보상 기록을 바탕으로 누락된 영구 콘텐츠 해금 티켓을 복구합니다. 스토리팩, 아바타 최초 선택, 식당 소개와 통발 해금에 적용하며 기간제 티켓의 만료 여부도 확인합니다.
- 이벤트 및 가이드 미션 완료 수를 수정하고 이미 받은 보상에 해당하는 진행도도 복구합니다. 일일·주간 미션 만료 보상 우편을 플레이어의 게임 언어로 보냅니다.
- 통발 타이머와 정산을 수정했습니다. 낚싯배를 강화하면 현재 어획물을 수령하며 자동 판매 설정과 낚시 경험치를 반영합니다. 물고기 판매 후 보유 목록도 올바르게 갱신합니다.
- BetterExperience와 함께 편집 가능한 농장 건물을 최소 배치 수 아래로 제거할 수 있습니다. 아이템 중첩 한도도 계정별 규칙에 맞게 유지합니다.
- 콜라보 아바타 및 전용 의상 부위 선물을 추가했습니다. 수령 시 이미 보유한 캐릭터와 부위는 제외합니다.
## client 2.37.13+client.0.2.18 · 2026-10-26
> type: update
+1 -1
View File
@@ -1,4 +1,4 @@
{
"key_id": "6ba6c06138973875",
"signature": "9jF/rjjzQsTpkEge8JBtNEvoU0XHJTXYhpsNCy6YXox8mhfe9vgYDNwh+K5TT+2yoseOMeuNH74ktO9ZnKfFAg=="
"signature": "AKkgjfc9EXyzGzIpCx6KDVWrCisdW7IexP8t0c07wer5ScwC4vYfXVQQjw6FvgBFWkwjLyTgLRxg8jQP3KC7Cg=="
}
+3 -1
View File
@@ -56,6 +56,8 @@
- `plugins/CaptureEnvironment/`:独立原版对照客户端的抓包插件,不要装进本地服务端客户端。
- `plugins/GameNames`/`plugins/GameSdk`: 插件开发工具链,让开发过程中使用反混淆名改善开发体验,只有 `GameNames` 需要随同安装。
所有随启动器发布的插件都登记在 `plugins/registry.json`:项目路径、目标框架、输出 DLL、版本键和依赖。新增插件只需在这里加一项,并在 `versions.json` 的 `plugins` 里写上它的版本;只有要求旧插件必须升级时,才在 `minimum_plugins` 里写最低版本。`tools` 里的项目(如 `CaptureEnvironment`)只参与 `check-csharp`,不打包也不下发。
## 可视化客户端工具
BD2 Launcher 是使用 Wails 的独立桌面游戏启动器。Windows 使用系统 WebView2 Runtime,macOS 使用系统 WKWebView。它提供以下操作:
@@ -63,7 +65,7 @@ BD2 Launcher 是使用 Wails 的独立桌面游戏启动器。Windows 使用系
- 选择并验证 Brown Dust II 安装目录。
- 填写服务器 origin 和端口,自动写入游戏目录下的 `BepInEx/config/bd2.client.json`。
- 应用带原文件备份的客户端入口补丁。
- 检查 BepInEx 后安装或更新 `BD2LocalIdentity.dll`、`BD2LoginUI.dll`、`BD2CashShop.dll` 及其共享运行时 `BD2.GameNames.dll`。
- 检查 BepInEx 后安装或更新 `plugins/registry.json` 登记的插件及其共享运行时 `BD2.GameNames.dll`。
- 选择官方 CDN、服务器资源源或本地已下载资源。
服主同步官方资源、自建静态 CDN 或配置缓存反代的步骤见 [资源与 CDN 配置指南](RESOURCES.md)。
+1 -1
View File
@@ -1 +1 @@
{"fingerprint":{"client_version":"2.37.13+client.0.2.18","game":{"build_origins":["https://cdn.dev.bd2.pmang.cloud","https://dl.dev.bd2.pmang.cloud"],"bundle_version":"20261022174708","catalog_bytes":67513445,"catalog_hash":"ae57bde3e9e5cf6ac57f9b0c0ea39b2f","catalog_sha256":"3e19c645e28b90d3601cd0ed7413dc516399ba2b658e0fa509686527048407b8","data_bytes":194804246,"data_sha256":"f3313a066dd2637678f728136d448adfd413259ae7129a79e109e7332b61a57d","game_bytes":413694732,"game_data_version":"20261021182514","game_path":"/Build/Windows/20261023/StandaloneWindows64.2.37.13.zip","game_sha256":"8f65954eb323fcffb1c29be13205d373d4f8fba3354e2e8d431d263bb2a6ca56","game_version":"2.37.13","platform":"StandaloneWindows64","resource_files":[{"path":"GameData/20261021182514/design.version","sha256":"816a6eaf2766663c792300ae0fc9333e8bf6c2c68b508b4e4f0400adfb194ee8","size":67},{"path":"GameData/20261021182514/release/common-dbdata.bin","sha256":"f3313a066dd2637678f728136d448adfd413259ae7129a79e109e7332b61a57d","size":194804246},{"path":"GameData/20261021182514/release/common-dbdata.info","sha256":"12168a51d330ab2858a765c60853a7feb123681d2d529d321834df97b6e05e4d","size":10},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/catalog_alpha.hash","sha256":"06d64c1f79022d9fc117fc45dc233e14ddbbf23ad1383d38f91006a1e4553ada","size":32},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/catalog_alpha.json","sha256":"3e19c645e28b90d3601cd0ed7413dc516399ba2b658e0fa509686527048407b8","size":67513445},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-avatar-char-group0_assets_charavatar.bundle","sha256":"c723a309b7b61bc2189f539f6911c852b21783b5fcb0a7a167e2f1d073fc2b5f","size":101738625},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-avatar-char-group0_scenes_charavatar.bundle","sha256":"56676c7f48d3d7c90f8956b02bc3f15f3074af7e8ff0ef64e1f9b8289eb08d52","size":31379},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-avatarfishingicon_1_assets_all.bundle","sha256":"3407127468d588ff84e5158d31f2b791fb144582fc914340d307e7b79b96be22","size":44897},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-avatarfishingicon_l_1_assets_all.bundle","sha256":"78ebf960a6b4f3b83fe28de1597e36f9ba7db1142bc1c0acdc9c65cd974cbbb4","size":2932480},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-avataricon_1_assets_all.bundle","sha256":"6bde00a738630d05afb42ee0fe84dd124b16de5b3ba16d62c08f5ea2657452ac","size":2888529},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-avatarlifehousing_1_assets_all.bundle","sha256":"1c844bc153dabe18b153157e466d7f7f0fa12e40c3b3ef6fc00af31abcf354e0","size":42443},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-avatarlifehousing_l_1_assets_all.bundle","sha256":"c12e4bae20aedf8889d7f916cca0b3d55167a4b787bd649e07f10d21db0c49bc","size":2334709},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-avatarlifeicon_1_assets_all.bundle","sha256":"bf6b432dc821a6e864993f649fedc1d03244d1ee2c93310bd0ce55d99ab8b743","size":16286},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-avatarlifeicon_l_1_assets_all.bundle","sha256":"528dec1ed0c867bb6dcd59b985dc3911280f5f560c0d4b000a1e979f46f6e335","size":824161},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-bgmalbum_1_assets_all.bundle","sha256":"16d606338d9b9e53a8d99d063613a8830dc943cb4225047f23b060f11614a7fc","size":614361},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-bundlecommon-effect-animation_assets_all.bundle","sha256":"8fb500400acf16f22516a298afbef6435c42c30969c762d7eee92c1d936cf06c","size":26191},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-bundlecommon-effect-animator_assets_all.bundle","sha256":"098045676a9b7d2c58703745bd608b2f9856027dd461012d3bde66d2f8266a16","size":6987},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-bundlecommon-effect-mesh_assets_all.bundle","sha256":"32a77141ffce92a510deb79f6af3309624b274c6e66493832946169a20612075","size":1617979},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-bundlecommon-effect-meterial_assets_all.bundle","sha256":"d4a379b7ee71e24a6eeecbd9967eeeb5f543b67d2403f736317b40ca281ed416","size":385296},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-bundlecommon-effect-prefab-group10_assets_all_8c26128b1b05c223d044c2f1d7f0e9dd.bundle","sha256":"71724987a41def2769d3bbdf79f1fb02933a0eb557d7f34a87c1e612e355c605","size":524718},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-bundlecommon-effect-prefab-group11_assets_all_7aa567cac538a20349cead4ca6de9a81.bundle","sha256":"31689c4ca268c96fd04e35d45f0bde1261b2810f32e339761889d1bebaaecfb6","size":665927},{"path":"ServerData/StandaloneWindows64/HD/20261022174708/common-bundlecommon-effect-prefab-group12_assets_all_4913582d39e677c63c907a62c69f82cd.bundle","sha256":"e86c377fd87f65a6092545e559a6bdd483e932741c03fe42538e9b9bc7b5dcc0","size":526015},{"pLine truncated
{"fingerprint":{"client_version":"2.38.11+client.0.2.19","game":{"build_origins":["https://cdn.dev.bd2.pmang.cloud","https://dl.dev.bd2.pmang.cloud"],"bundle_version":"20261104191902","catalog_bytes":68479722,"catalog_hash":"f5e10494590d083c48143e0ab39dd591","catalog_sha256":"e8c133e073a92bddc4da77666bdc3f9def5105181a6cee5df75f8fe6cc02ae5c","data_bytes":199215117,"data_sha256":"97f7290bb183cf15099e80646ff9f16cdb0e3b083be69c30548fb364f23c2786","game_bytes":414205628,"game_data_version":"20261104152727","game_path":"/Build/Windows/20261030/StandaloneWindows64.2.38.11.zip","game_sha256":"9ab7d137f4d4222ee59726b0764a814d23d446e6c2780a8d54ee21cccd8bf256","game_version":"2.38.11","platform":"StandaloneWindows64","resource_files":[{"path":"GameData/20261104152727/design.version","sha256":"58f886079eab72fc02461133fa70983572f7e2b3bc24f4318f59ec91c4419b72","size":67},{"path":"GameData/20261104152727/release/common-dbdata.bin","sha256":"97f7290bb183cf15099e80646ff9f16cdb0e3b083be69c30548fb364f23c2786","size":199215117},{"path":"GameData/20261104152727/release/common-dbdata.info","sha256":"67150871ea41492da55caadba8d6983a9a63c17b8a943e879bc6b775d09089d9","size":10},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/catalog_alpha.hash","sha256":"207ffba680e7730abcba0c1d1c257ee5d9e6706ac10b9aa6cd55efa18b9b8fa7","size":32},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/catalog_alpha.json","sha256":"e8c133e073a92bddc4da77666bdc3f9def5105181a6cee5df75f8fe6cc02ae5c","size":68479722},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-avatar-char-group0_assets_charavatar.bundle","sha256":"0f36ce395d140681b8e607270dc64ce3d9882874224c715830733be507e9eede","size":104133543},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-avatar-char-group0_scenes_charavatar.bundle","sha256":"56676c7f48d3d7c90f8956b02bc3f15f3074af7e8ff0ef64e1f9b8289eb08d52","size":31379},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-avatarfishingicon_1_assets_all.bundle","sha256":"3407127468d588ff84e5158d31f2b791fb144582fc914340d307e7b79b96be22","size":44897},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-avatarfishingicon_l_1_assets_all.bundle","sha256":"78ebf960a6b4f3b83fe28de1597e36f9ba7db1142bc1c0acdc9c65cd974cbbb4","size":2932480},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-avataricon_1_assets_all.bundle","sha256":"44aafb1aa68d8e1fede0d029692dd3124c2548d41d3c2ec49f66d28f76f2aa24","size":3019726},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-avatarlifehousing_1_assets_all.bundle","sha256":"1c844bc153dabe18b153157e466d7f7f0fa12e40c3b3ef6fc00af31abcf354e0","size":42443},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-avatarlifehousing_l_1_assets_all.bundle","sha256":"c12e4bae20aedf8889d7f916cca0b3d55167a4b787bd649e07f10d21db0c49bc","size":2334709},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-avatarlifeicon_1_assets_all.bundle","sha256":"bf6b432dc821a6e864993f649fedc1d03244d1ee2c93310bd0ce55d99ab8b743","size":16286},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-avatarlifeicon_l_1_assets_all.bundle","sha256":"528dec1ed0c867bb6dcd59b985dc3911280f5f560c0d4b000a1e979f46f6e335","size":824161},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-bgmalbum_1_assets_all.bundle","sha256":"16d606338d9b9e53a8d99d063613a8830dc943cb4225047f23b060f11614a7fc","size":614361},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-bundlecommon-effect-animation_assets_all.bundle","sha256":"8fb500400acf16f22516a298afbef6435c42c30969c762d7eee92c1d936cf06c","size":26191},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-bundlecommon-effect-animator_assets_all.bundle","sha256":"098045676a9b7d2c58703745bd608b2f9856027dd461012d3bde66d2f8266a16","size":6987},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-bundlecommon-effect-mesh_assets_all.bundle","sha256":"32a77141ffce92a510deb79f6af3309624b274c6e66493832946169a20612075","size":1617979},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-bundlecommon-effect-meterial_assets_all.bundle","sha256":"e88778e8b0d749616c532752ea12a1472f1eeeac54d7a51dc011bf4fc8ab02db","size":386188},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-bundlecommon-effect-prefab-group10_assets_all_7319a1e21888e7fc467791e593f84b00.bundle","sha256":"71724987a41def2769d3bbdf79f1fb02933a0eb557d7f34a87c1e612e355c605","size":524718},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-bundlecommon-effect-prefab-group11_assets_all_2aa68a2f154061e149df58c1040cc192.bundle","sha256":"31689c4ca268c96fd04e35d45f0bde1261b2810f32e339761889d1bebaaecfb6","size":665927},{"path":"ServerData/StandaloneWindows64/HD/20261104191902/common-bundlecommon-effect-prefab-group12_assets_all_79b1a93d2c4654866edce35c30ac3bc8.bundle","sha256":"e86c377fd87f65a6092545e559a6bdd483e932741c03fe42538e9b9bc7b5dcc0","size":526015},{"pLine truncated
+11 -17
View File
@@ -3,7 +3,6 @@ package main
import (
"context"
"fmt"
"path/filepath"
"slices"
"bd2server/internal/client/plugin"
@@ -11,7 +10,16 @@ import (
)
func (t task) checkCSharp(projects []string) error {
allowed := csharpProjects()
registry, err := plugin.Load(t.root)
if err != nil {
return err
}
files := map[string]string{}
var allowed []string
for _, project := range registry.Projects(t.root) {
files[project.Name] = project.File
allowed = append(allowed, project.Name)
}
if len(projects) == 0 {
projects = allowed
}
@@ -26,13 +34,7 @@ func (t task) checkCSharp(projects []string) error {
continue
}
seen[project] = true
file := filepath.Join(t.root, "plugins", project, project+".csproj")
for _, definition := range plugin.Definitions() {
if definition.Name() == project {
file = definition.ProjectFile(t.root)
break
}
}
file := files[project]
build, format := "csharp:build:"+project, "csharp:style:"+project
tasks = append(tasks,
taskgraph.Task{Name: build, Run: func(context.Context) error {
@@ -48,11 +50,3 @@ func (t task) checkCSharp(projects []string) error {
tasks = append(tasks, taskgraph.Task{Name: "check-csharp", DependsOn: targets})
return t.execute("check-csharp", tasks...)
}
func csharpProjects() []string {
projects := []string{"GameSdk", "CaptureEnvironment"}
for _, d := range plugin.Definitions() {
projects = append(projects, d.Name())
}
return projects
}
+5 -1
View File
@@ -81,7 +81,11 @@ func (t task) runClient2(args []string) error {
if err := clientplugin.BuildDevelopment(ctx, t.root, game, os.Stdout); err != nil {
return err
}
_, err := clientsetup.InstallPlugins(instance.GameDirectory, clientplugin.Development(t.root))
plugins, err := clientplugin.Development(t.root)
if err != nil {
return err
}
_, err = clientsetup.InstallPlugins(instance.GameDirectory, plugins)
return err
}},
taskgraph.Task{Name: "instance:launcher", DependsOn: []string{"instance:plugins"}, Run: func(context.Context) error {
+15 -3
View File
@@ -152,7 +152,11 @@ func (r *release) stageAssets() error {
return err
}
}
for _, artifact := range clientplugin.Development(root) {
plugins, err := clientplugin.Development(root)
if err != nil {
return err
}
for _, artifact := range plugins {
if err := copyFile(artifact.Source, filepath.Join(r.client, "plugins", artifact.Name)); err != nil {
return err
}
@@ -223,15 +227,23 @@ func (r *release) writePluginStore() error {
if err != nil {
return err
}
plugins, err := clientplugin.Development(r.task.root)
if err != nil {
return err
}
byID := versions.Plugins.ByID()
store := clientplugin.Store{Version: versions.ClientVersion}
for _, artifact := range clientplugin.Development(r.task.root) {
for _, artifact := range plugins {
version, found := byID[artifact.VersionKey]
if artifact.VersionKey != "" && !found {
return fmt.Errorf("versions.json has no plugins.%s for %s", artifact.VersionKey, artifact.Name)
}
sum, err := util.SHA256File(filepath.Join(r.client, "plugins", artifact.Name))
if err != nil {
return err
}
id := artifact.ID
store.Files = append(store.Files, clientplugin.StoredFile{ID: id, Name: artifact.Name, Version: byID[artifact.VersionKey], SHA256: sum})
store.Files = append(store.Files, clientplugin.StoredFile{ID: id, Name: artifact.Name, Version: version, SHA256: sum})
}
raw, err := json.MarshalIndent(store, "", " ")
if err != nil {
-1
View File
@@ -309,7 +309,6 @@ func (t task) releasePublish(args []string) error {
server := &releasepkg.Component{Version: versions.ServerVersion, Date: date(serverEntry), Notes: serverEntry.Notes(), Image: opts.image,
Migration: &releasepkg.Migration{Kind: serverEntry.Migration, Backup: serverEntry.Backup}, MinimumPlugins: versions.MinimumPlugins.ByID()}
delete(server.MinimumPlugins, "capture_environment")
if serverEntry.Migration != releasepkg.MigrationNone {
server.Migration.Note = i18n.Text{}
for locale, notes := range serverEntry.Notes() {
+7 -7
View File
@@ -227,7 +227,7 @@ func memberTokens(m *member) []string {
}
return m.tokens
}
func compareText(old, new string, context int, strict bool, oldSymbols, newSymbols map[string]string) fileResult {
func compareText(old, new string, context int, strict bool, oldSymbols, newSymbols map[string]string, text diffText) fileResult {
result := fileResult{Status: "unchanged", Members: []diffEntry{}, Noise: []diffEntry{}}
a, b := tokenize(old, oldSymbols), tokenize(new, newSymbols)
if slices.Equal(a, b) {
@@ -275,10 +275,10 @@ func compareText(old, new string, context int, strict bool, oldSymbols, newSymbo
}
}
if !strict && !ambiguous && (left != nil && right != nil && slices.Equal(ca, cb) || simpleUsing) {
entry.Reason = "局部名 / 冗余括号 / 推断泛型 / 生成编号 / 标签 / 属性顺序(启发式,需审阅)"
entry.Reason = text("reason.normalized")
entry.Diff = unified(rawA, rawB, "old", "new", context)
if simpleUsing {
entry.Reason = "using 声明变化,未做名称绑定证明,保留复核"
entry.Reason = text("reason.using")
result.Review = append(result.Review, entry)
} else {
result.Noise = append(result.Noise, entry)
@@ -300,9 +300,9 @@ func compareText(old, new string, context int, strict bool, oldSymbols, newSymbo
}
}
if structural || ambiguous {
entry.Reason = "async / 状态机导出结构不同,需复核正文"
entry.Reason = text("reason.async")
if ambiguous {
entry.Reason = "导出代码含同一作用域重名局部,绑定无法可靠恢复"
entry.Reason = text("reason.ambiguous")
}
result.Review = append(result.Review, entry)
} else {
@@ -329,11 +329,11 @@ func compareText(old, new string, context int, strict bool, oldSymbols, newSymbo
}
orderA, orderB := order(da, db, false), order(db, da, false)
if !slices.Equal(orderA, orderB) {
result.Members = append(result.Members, diffEntry{Name: "声明 / 初始化顺序", Kind: "order", Diff: unified(orderA, orderB, "old order", "new order", context)})
result.Members = append(result.Members, diffEntry{Name: text("member.declaration_order"), Kind: "order", Diff: unified(orderA, orderB, "old order", "new order", context)})
}
methodA, methodB := order(da, db, true), order(db, da, true)
if !slices.Equal(methodA, methodB) {
result.Noise = append(result.Noise, diffEntry{Name: "方法 / using 排列顺序", Kind: "order", Reason: "同名成员分别比较,声明顺序单独记录", Diff: unified(methodA, methodB, "old order", "new order", context)})
result.Noise = append(result.Noise, diffEntry{Name: text("member.method_order"), Kind: "order", Reason: text("reason.order"), Diff: unified(methodA, methodB, "old order", "new order", context)})
}
if len(result.Members) > 0 {
result.Status = "modified"
+25 -11
View File
@@ -12,6 +12,8 @@ import (
"strings"
"sync"
"time"
"bd2server/internal/common/i18n"
)
type repeatedFlag []string
@@ -22,6 +24,7 @@ func (s *repeatedFlag) Set(v string) error { *s = append(*s, v); return nil }
type diffReport struct {
Tool string `json:"tool"`
Output string `json:"output"`
Locale string `json:"locale"`
Schema int `json:"schema"`
OldRoot string `json:"old_root"`
NewRoot string `json:"new_root"`
@@ -40,6 +43,7 @@ const diffTool = "bd2.cleandiff_client_source"
func RunDiff(args []string, out io.Writer) error {
f := flag.NewFlagSet("diff", flag.ContinueOnError)
f.SetOutput(out)
localeFlag := f.String("locale", "zh_cn", "report language: en_us, ko_kr, ja_jp, zh_tw, zh_cn")
aFlag := f.String("a", "", "old C# source tree")
bFlag := f.String("b", "", "new C# source tree")
outputFlag := f.String("out", "cleandiff-report.txt", "summary path; also writes .html/.json/.diff/.noise.diff/.review.diff")
@@ -55,6 +59,16 @@ func RunDiff(args []string, out io.Writer) error {
}
return e
}
if !i18n.Supported(*localeFlag) {
return fmt.Errorf("unsupported report locale: %s", *localeFlag)
}
catalog, e := loadDiffLanguages()
if e != nil {
return e
}
text := diffText(func(key string, args ...any) string {
return catalog.Translate(*localeFlag, key, args...)
})
if f.NArg() != 0 {
return errors.New("diff does not accept positional arguments")
}
@@ -106,12 +120,12 @@ func RunDiff(args []string, out io.Writer) error {
if e != nil {
return e
}
tasks, symbolsA, symbolsB, warnings := pairTrees(a, b, ia, ib)
tasks, symbolsA, symbolsB, warnings := pairTrees(a, b, ia, ib, text)
workers := *workersFlag
if workers == 0 {
workers = min(8, runtime.NumCPU())
}
if _, e = fmt.Fprintf(out, "旧版 %d / 新版 %d C# 文件;%d workers\n", len(ia), len(ib), workers); e != nil {
if _, e = io.WriteString(out, text("cli.inventory", len(ia), len(ib), workers)); e != nil {
return e
}
results := make([]fileResult, len(tasks))
@@ -120,7 +134,7 @@ func RunDiff(args []string, out io.Writer) error {
for w := 0; w < min(workers, max(1, len(tasks))); w++ {
wg.Go(func() {
for i := range jobs {
results[i] = compareFile(a, b, tasks[i], *contextFlag, *strictFlag, symbolsA, symbolsB)
results[i] = compareFile(a, b, tasks[i], *contextFlag, *strictFlag, symbolsA, symbolsB, text)
}
})
}
@@ -140,12 +154,12 @@ func RunDiff(args []string, out io.Writer) error {
renamed++
}
}
report := diffReport{Tool: diffTool, Output: output, Schema: 1, OldRoot: a, NewRoot: b, Workers: workers, Strict: *strictFlag, ElapsedSeconds: time.Since(start).Seconds(), Counts: counts, Warnings: warnings, RenamedPaths: renamed, Files: results}
if e = writeReports(output, report); e != nil {
report := diffReport{Tool: diffTool, Output: output, Locale: *localeFlag, Schema: 1, OldRoot: a, NewRoot: b, Workers: workers, Strict: *strictFlag, ElapsedSeconds: time.Since(start).Seconds(), Counts: counts, Warnings: warnings, RenamedPaths: renamed, Files: results}
if e = writeReports(output, report, text); e != nil {
return e
}
countJSON, _ := json.Marshal(counts)
if _, e = fmt.Fprintf(out, "%s\n匹配混淆后缀路径 %d;比较 %.2fs;总计 %.2fs\n摘要: %s\n可视化: %s\n", countJSON, renamed, report.ElapsedSeconds, time.Since(start).Seconds(), output, strings.TrimSuffix(output, filepath.Ext(output))+".html"); e != nil {
if _, e = io.WriteString(out, text("cli.complete", countJSON, renamed, report.ElapsedSeconds, time.Since(start).Seconds(), output, strings.TrimSuffix(output, filepath.Ext(output))+".html")); e != nil {
return e
}
if counts["error"] > 0 {
@@ -182,7 +196,7 @@ func checkReportOutput(output string) error {
}
return nil
}
func writeReports(output string, report diffReport) (retErr error) {
func writeReports(output string, report diffReport, text diffText) (retErr error) {
if e := checkReportOutput(output); e != nil {
return e
}
@@ -203,9 +217,9 @@ func writeReports(output string, report diffReport) (retErr error) {
summary, patch, noise, review := strings.Builder{}, strings.Builder{}, strings.Builder{}, strings.Builder{}
fmt.Fprintf(&summary, "# %s\n# → %s\n\n", report.OldRoot, report.NewRoot)
counts, _ := json.Marshal(report.Counts)
fmt.Fprintf(&summary, "%s\n耗时 %.2fs / %d workers\n行号为归一化成员行号;疑似噪声不等于已证明语义相同。\n\n", counts, report.ElapsedSeconds, report.Workers)
summary.WriteString(text("summary.timing", counts, report.ElapsedSeconds, report.Workers))
for _, w := range report.Warnings {
fmt.Fprintf(&summary, "警告: %s\n", w)
summary.WriteString(text("summary.warning", w))
}
for _, r := range report.Files {
if r.Status == "unchanged" {
@@ -231,12 +245,12 @@ func writeReports(output string, report diffReport) (retErr error) {
}
}
}
fmt.Fprintf(&summary, "\n主差异: %s\n需复核结构: %s\n疑似噪声: %s\n可视化: %s\n结构化报告: %s\n", paths[3], paths[5], paths[4], paths[2], paths[1])
summary.WriteString(text("summary.paths", paths[3], paths[5], paths[4], paths[2], paths[1]))
jsonData, e := json.MarshalIndent(report, "", " ")
if e != nil {
return e
}
htmlData, e := renderHTML(report)
htmlData, e := renderHTML(report, text)
if e != nil {
return e
}
+42 -14
View File
@@ -4,23 +4,51 @@ import (
"bytes"
"encoding/json"
"html/template"
"strings"
)
func renderHTML(report diffReport) ([]byte, error) {
files := []fileResult{}
func renderHTML(report diffReport, text diffText) ([]byte, error) {
type htmlFile struct {
fileResult
Title string `json:"title"`
Paths string `json:"paths"`
}
files := []htmlFile{}
for _, f := range report.Files {
if f.Status != "unchanged" {
files = append(files, f)
if f.Status == "unchanged" {
continue
}
oldPath, newPath := "∅", "∅"
if f.OldPath != nil {
oldPath = *f.OldPath
}
if f.NewPath != nil {
newPath = *f.NewPath
}
files = append(files, htmlFile{f,
text("html.file_summary", text("status."+f.Status), f.Path, len(f.Members), len(f.Review), len(f.Noise)),
text("html.file_paths", oldPath, newPath),
})
}
payload, e := json.Marshal(files)
if e != nil {
return nil, e
}
labels := map[string]string{}
for _, key := range []string{"title", "instructions", "search", "changes", "review", "noise", "all", "previous", "next", "raw", "files", "members", "group_review", "group_noise"} {
labels[key] = text("html." + key)
}
labelJSON, e := json.Marshal(labels)
if e != nil {
return nil, e
}
data := struct {
Report diffReport
Payload template.JS
}{report, template.JS(payload)}
Report diffReport
Language string
Text map[string]string
Payload template.JS
Labels template.JS
}{report, strings.ReplaceAll(report.Locale, "_", "-"), labels, template.JS(payload), template.JS(labelJSON)}
t, e := template.New("report").Parse(reportHTML)
if e != nil {
return nil, e
@@ -30,19 +58,19 @@ func renderHTML(report diffReport) ([]byte, error) {
return out.Bytes(), e
}
const reportHTML = `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>客户端源码 Clean Diff</title>
const reportHTML = `<!doctype html><html lang="{{.Language}}"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{.Text.title}}</title>
<style>body{font:15px system-ui;margin:0;background:#10151d;color:#e0e6ed}header{padding:20px 24px;position:sticky;top:0;background:#17202df5;z-index:1}h1{font-size:24px;margin:0 0 12px}input,select,button{padding:9px;background:#10151d;color:#e0e6ed;border:1px solid #506079;border-radius:5px}button{cursor:pointer}button:disabled{opacity:.4}input{width:min(45vw,600px)}main{padding:10px 24px}details.file{border:1px solid #344256;border-radius:7px;margin:12px 0}summary{cursor:pointer;padding:12px;overflow-wrap:anywhere}details.member{margin:8px 16px;border-left:2px solid #526581}pre{font:13px/1.6 Consolas,monospace;overflow:auto;margin:0;padding:12px;background:#0c1118}.add{display:block;background:#163d2b;color:#b9f3c7}.del{display:block;background:#48212a;color:#ffc3c9}.hunk{display:block;color:#8bc4ff}.line{display:block}.muted{color:#9eafc2}.raw{margin:10px 14px}#count{margin-left:12px}nav{padding-top:12px}.reason{margin:10px 16px;color:#e8c079}</style>
<header><h1>客户端源码 Clean Diff</h1><p>{{range $k,$v := .Report.Counts}}{{$k}}: {{$v}} / {{end}}</p><p class="muted">{{.Report.OldRoot}} → {{.Report.NewRoot}}</p><p class="muted">按文件 → 成员展开。行号为归一化成员行号;局部变量显示为 localN,可展开保留原名称的 diff。复核区保留 async / 状态机与无法确定的结构变化。</p>
<input id="q" placeholder="搜索路径、成员、差异文本"><select id="filter"><option value="changes">主差异</option><option value="review">需复核结构</option><option value="noise">疑似写法噪声</option><option value="all">全部</option></select><span id="count"></span><nav><button id="prev">上一页</button> <span id="page"></span> <button id="next">下一页</button></nav></header><main id="files"></main>{{range .Report.Warnings}}<p class="reason">{{.}}</p>{{end}}
<script type="application/json" id="data">{{.Payload}}</script><script>
<header><h1>{{.Text.title}}</h1><p>{{range $k,$v := .Report.Counts}}{{$k}}: {{$v}} / {{end}}</p><p class="muted">{{.Report.OldRoot}} → {{.Report.NewRoot}}</p><p class="muted">{{.Text.instructions}}</p>
<input id="q" placeholder="{{.Text.search}}"><select id="filter"><option value="changes">{{.Text.changes}}</option><option value="review">{{.Text.review}}</option><option value="noise">{{.Text.noise}}</option><option value="all">{{.Text.all}}</option></select><span id="count"></span><nav><button id="prev">{{.Text.previous}}</button> <span id="page"></span> <button id="next">{{.Text.next}}</button></nav></header><main id="files"></main>{{range .Report.Warnings}}<p class="reason">{{.}}</p>{{end}}
<script type="application/json" id="data">{{.Payload}}</script><script type="application/json" id="labels">{{.Labels}}</script><script>
const data=JSON.parse(document.querySelector('#data').textContent);document.querySelector('#data').remove();
const q=document.querySelector('#q'),filter=document.querySelector('#filter'),list=document.querySelector('#files');
const labels={modified:'变化',added:'新增',removed:'删除',noise:'疑似噪声',review:'需复核',error:'读取失败'};
const labels=JSON.parse(document.querySelector('#labels').textContent);document.querySelector('#labels').remove();
let matches=[],page=0,timer;const size=100;
function node(tag,text,cls){const el=document.createElement(tag);if(text!==undefined)el.textContent=text;if(cls)el.className=cls;return el}
function showDiff(diff){const pre=node('pre');for(const line of diff.split('\n')){const cls=line.startsWith('+')?'add':line.startsWith('-')?'del':line.startsWith('@@')?'hunk':'line';pre.append(node('span',line||' ',cls))}return pre}
function member(entry,title){const el=node('details',undefined,'member');el.append(node('summary',title+' · '+entry.name));el.addEventListener('toggle',()=>{if(!el.open||el.dataset.loaded)return;el.dataset.loaded='1';if(entry.reason)el.append(node('p',entry.reason,'reason'));el.append(showDiff(entry.diff));if(entry.source_diff&&entry.source_diff!==entry.diff){const raw=node('details',undefined,'raw');raw.append(node('summary','查看保留局部名 / 括号 / 泛型的差异'));raw.addEventListener('toggle',()=>{if(raw.open&&!raw.dataset.loaded){raw.dataset.loaded='1';raw.append(showDiff(entry.source_diff))}});el.append(raw)}});return el}
function draw(){list.replaceChildren();const mode=filter.value;for(const item of matches.slice(page*size,(page+1)*size)){const el=node('details',undefined,'file');el.append(node('summary',labels[item.status]+' · '+item.path+' ('+item.members.length+' 变化 / '+(item.review||[]).length+' 复核 / '+item.noise.length+' 噪声)'));el.addEventListener('toggle',()=>{if(!el.open||el.dataset.loaded)return;el.dataset.loaded='1';el.append(node('p','旧: '+(item.old_path||'∅')+' → 新: '+(item.new_path||'∅'),'muted raw'));if(item.error)el.append(node('pre',item.error));for(const [key,title] of [['members','变化'],['review','需复核'],['noise','疑似噪声']]){if(mode==='review'&&key!=='review'||mode==='noise'&&key!=='noise')continue;for(const entry of item[key]||[])el.append(member(entry,title))}});list.append(el)}document.querySelector('#count').textContent=matches.length+' 文件';document.querySelector('#page').textContent=(matches.length?page+1:0)+' / '+Math.ceil(matches.length/size);document.querySelector('#prev').disabled=page===0;document.querySelector('#next').disabled=(page+1)*size>=matches.length}
function member(entry,title){const el=node('details',undefined,'member');el.append(node('summary',title+' · '+entry.name));el.addEventListener('toggle',()=>{if(!el.open||el.dataset.loaded)return;el.dataset.loaded='1';if(entry.reason)el.append(node('p',entry.reason,'reason'));el.append(showDiff(entry.diff));if(entry.source_diff&&entry.source_diff!==entry.diff){const raw=node('details',undefined,'raw');raw.append(node('summary',labels.raw));raw.addEventListener('toggle',()=>{if(raw.open&&!raw.dataset.loaded){raw.dataset.loaded='1';raw.append(showDiff(entry.source_diff))}});el.append(raw)}});return el}
function draw(){list.replaceChildren();const mode=filter.value;for(const item of matches.slice(page*size,(page+1)*size)){const el=node('details',undefined,'file');el.append(node('summary',item.title));el.addEventListener('toggle',()=>{if(!el.open||el.dataset.loaded)return;el.dataset.loaded='1';el.append(node('p',item.paths,'muted raw'));if(item.error)el.append(node('pre',item.error));for(const [key,title] of [['members',labels.members],['review',labels.group_review],['noise',labels.group_noise]]){if(mode==='review'&&key!=='review'||mode==='noise'&&key!=='noise')continue;for(const entry of item[key]||[])el.append(member(entry,title))}});list.append(el)}document.querySelector('#count').textContent=matches.length+' '+labels.files;document.querySelector('#page').textContent=(matches.length?page+1:0)+' / '+Math.ceil(matches.length/size);document.querySelector('#prev').disabled=page===0;document.querySelector('#next').disabled=(page+1)*size>=matches.length}
function search(){page=0;const s=q.value.toLowerCase(),mode=filter.value;matches=data.filter(item=>{if(mode==='changes'&&!['modified','added','removed','error'].includes(item.status))return false;if(mode==='noise'&&!item.noise.length)return false;if(mode==='review'&&!(item.review||[]).length)return false;if(!s||item.path.toLowerCase().includes(s))return true;return ['members','review','noise'].some(key=>(item[key]||[]).some(m=>(m.name+' '+m.diff+' '+(m.source_diff||'')).toLowerCase().includes(s)))});draw()}
q.addEventListener('input',()=>{clearTimeout(timer);timer=setTimeout(search,150)});filter.addEventListener('change',search);document.querySelector('#prev').onclick=()=>{page--;draw()};document.querySelector('#next').onclick=()=>{page++;draw()};search();
</script></html>`
+38
View File
@@ -0,0 +1,38 @@
{
"reason.normalized": "Local names / redundant parentheses / inferred generics / generated numbering / labels / attribute order (heuristic; review required)",
"reason.using": "using declarations changed; name binding is unproven, retained for review",
"reason.async": "async / state-machine export structures differ; review the body",
"reason.ambiguous": "Exported code has duplicate local names in the same scope; bindings cannot be reliably recovered",
"member.declaration_order": "Declaration / initialization order",
"member.method_order": "Method / using order",
"reason.order": "Members with matching names are compared individually; declaration order is recorded separately",
"member.whole_file": "Entire file",
"warning.unpaired": "Types with the same name could not be uniquely paired; retained as a separate %s file: %s",
"cli.inventory": "Old %d / new %d C# files; %d workers\n",
"cli.complete": "%s\nMatched obfuscation-suffix paths %d; comparison %.2fs; total %.2fs\nSummary: %s\nVisualization: %s\n",
"summary.timing": "%s\nElapsed %.2fs / %d workers\nLine numbers refer to normalized members; suspected noise does not prove semantic equivalence.\n\n",
"summary.warning": "Warning: %s\n",
"summary.paths": "\nMain differences: %s\nStructures for review: %s\nSuspected noise: %s\nVisualization: %s\nStructured report: %s\n",
"html.title": "Client Source Clean Diff",
"html.instructions": "Expand files, then members. Line numbers refer to normalized members; locals appear as localN. Expand the source diff to retain original names. The review section retains async / state-machine and uncertain structural changes.",
"html.search": "Search paths, members and diff text",
"html.changes": "Main differences",
"html.review": "Structures for review",
"html.noise": "Suspected style noise",
"html.all": "All",
"html.previous": "Previous",
"html.next": "Next",
"html.raw": "View differences retaining local names / parentheses / generics",
"html.files": "files",
"html.members": "Changes",
"html.group_review": "Review required",
"html.group_noise": "Suspected noise",
"html.file_summary": "%s · %s (%d changes / %d for review / %d noise)",
"html.file_paths": "Old: %s → New: %s",
"status.modified": "Changed",
"status.added": "Added",
"status.removed": "Removed",
"status.noise": "Suspected noise",
"status.review": "Review required",
"status.error": "Read failed"
}
+38
View File
@@ -0,0 +1,38 @@
{
"reason.normalized": "ローカル名 / 冗長な括弧 / 推論されたジェネリック / 生成番号 / ラベル / 属性順序(ヒューリスティック、要確認)",
"reason.using": "using 宣言の変更。名前の束縛を証明できないため要確認として保持",
"reason.async": "async / ステートマシンのエクスポート構造が異なるため本文の確認が必要",
"reason.ambiguous": "エクスポートコードの同一スコープに同名のローカル変数があり、束縛を確実に復元できません",
"member.declaration_order": "宣言 / 初期化順序",
"member.method_order": "メソッド / using の並び順",
"reason.order": "同名メンバーを個別に比較し、宣言順序を別途記録",
"member.whole_file": "ファイル全体",
"warning.unpaired": "同名の型を一意に対応付けられないため、%s 側の独立ファイルとして保持: %s",
"cli.inventory": "旧版 %d / 新版 %d C# ファイル;%d ワーカー\n",
"cli.complete": "%s\n難読化接尾辞のパス一致 %d;比較 %.2fs;合計 %.2fs\n概要: %s\n可視化: %s\n",
"summary.timing": "%s\n所要時間 %.2fs / %d ワーカー\n行番号は正規化したメンバー内の行番号です。ノイズの可能性は意味の同一性の証明ではありません。\n\n",
"summary.warning": "警告: %s\n",
"summary.paths": "\n主な差分: %s\n要確認の構造: %s\nノイズの可能性: %s\n可視化: %s\n構造化レポート: %s\n",
"html.title": "クライアントソース Clean Diff",
"html.instructions": "ファイル → メンバーの順に展開します。行番号は正規化したメンバー内の行番号です。ローカル変数は localN と表示され、元の名前を保持した差分も展開できます。要確認欄には async / ステートマシンや不確定な構造変更を保持します。",
"html.search": "パス、メンバー、差分テキストを検索",
"html.changes": "主な差分",
"html.review": "要確認の構造",
"html.noise": "記述ノイズの可能性",
"html.all": "すべて",
"html.previous": "前のページ",
"html.next": "次のページ",
"html.raw": "ローカル名 / 括弧 / ジェネリックを保持した差分を表示",
"html.files": "ファイル",
"html.members": "変更",
"html.group_review": "要確認",
"html.group_noise": "ノイズの可能性",
"html.file_summary": "%s · %s (変更 %d / 要確認 %d / ノイズ %d)",
"html.file_paths": "旧: %s → 新: %s",
"status.modified": "変更",
"status.added": "追加",
"status.removed": "削除",
"status.noise": "ノイズの可能性",
"status.review": "要確認",
"status.error": "読み取り失敗"
}
+38
View File
@@ -0,0 +1,38 @@
{
"reason.normalized": "지역 이름 / 불필요한 괄호 / 추론된 제네릭 / 생성 번호 / 레이블 / 특성 순서 (휴리스틱, 검토 필요)",
"reason.using": "using 선언 변경: 이름 바인딩이 증명되지 않아 검토 대상으로 유지",
"reason.async": "async / 상태 머신 내보내기 구조가 달라 본문 검토 필요",
"reason.ambiguous": "내보낸 코드의 같은 범위에 동일한 지역 이름이 있어 바인딩을 정확히 복원할 수 없음",
"member.declaration_order": "선언 / 초기화 순서",
"member.method_order": "메서드 / using 정렬 순서",
"reason.order": "동일한 이름의 멤버는 개별 비교하고 선언 순서는 별도로 기록",
"member.whole_file": "전체 파일",
"warning.unpaired": "동일한 이름의 형식을 고유하게 연결하지 못해 %s 측 독립 파일로 유지: %s",
"cli.inventory": "이전 %d / 새 %d C# 파일; 작업자 %d개\n",
"cli.complete": "%s\n난독화 접미사 경로 일치 %d; 비교 %.2fs; 전체 %.2fs\n요약: %s\n시각화: %s\n",
"summary.timing": "%s\n소요 시간 %.2fs / 작업자 %d개\n줄 번호는 정규화된 멤버 내 줄 번호입니다. 노이즈 의심은 의미가 동일하다는 증명이 아닙니다.\n\n",
"summary.warning": "경고: %s\n",
"summary.paths": "\n주요 차이: %s\n검토할 구조: %s\n의심되는 노이즈: %s\n시각화: %s\n구조화 보고서: %s\n",
"html.title": "클라이언트 소스 Clean Diff",
"html.instructions": "파일 → 멤버 순으로 펼칩니다. 줄 번호는 정규화된 멤버 내 줄 번호이며 지역 변수는 localN으로 표시됩니다. 원래 이름을 유지한 차이도 펼칠 수 있습니다. 검토 영역에는 async / 상태 머신과 불확실한 구조 변경을 유지합니다.",
"html.search": "경로, 멤버, 차이 텍스트 검색",
"html.changes": "주요 차이",
"html.review": "검토할 구조",
"html.noise": "표현 방식 노이즈 의심",
"html.all": "전체",
"html.previous": "이전 페이지",
"html.next": "다음 페이지",
"html.raw": "지역 이름 / 괄호 / 제네릭을 유지한 차이 보기",
"html.files": "파일",
"html.members": "변경",
"html.group_review": "검토 필요",
"html.group_noise": "의심되는 노이즈",
"html.file_summary": "%s · %s (변경 %d / 검토 %d / 노이즈 %d)",
"html.file_paths": "이전: %s → 새: %s",
"status.modified": "변경",
"status.added": "추가",
"status.removed": "삭제",
"status.noise": "의심되는 노이즈",
"status.review": "검토 필요",
"status.error": "읽기 실패"
}
+38
View File
@@ -0,0 +1,38 @@
{
"reason.normalized": "局部名 / 冗余括号 / 推断泛型 / 生成编号 / 标签 / 属性顺序(启发式,需审阅)",
"reason.using": "using 声明变化,未做名称绑定证明,保留复核",
"reason.async": "async / 状态机导出结构不同,需复核正文",
"reason.ambiguous": "导出代码含同一作用域重名局部,绑定无法可靠恢复",
"member.declaration_order": "声明 / 初始化顺序",
"member.method_order": "方法 / using 排列顺序",
"reason.order": "同名成员分别比较,声明顺序单独记录",
"member.whole_file": "整个文件",
"warning.unpaired": "同名类型未能唯一配对,保留为%s独立文件: %s",
"cli.inventory": "旧版 %d / 新版 %d C# 文件;%d workers\n",
"cli.complete": "%s\n匹配混淆后缀路径 %d;比较 %.2fs;总计 %.2fs\n摘要: %s\n可视化: %s\n",
"summary.timing": "%s\n耗时 %.2fs / %d workers\n行号为归一化成员行号;疑似噪声不等于已证明语义相同。\n\n",
"summary.warning": "警告: %s\n",
"summary.paths": "\n主差异: %s\n需复核结构: %s\n疑似噪声: %s\n可视化: %s\n结构化报告: %s\n",
"html.title": "客户端源码 Clean Diff",
"html.instructions": "按文件 → 成员展开。行号为归一化成员行号;局部变量显示为 localN,可展开保留原名称的 diff。复核区保留 async / 状态机与无法确定的结构变化。",
"html.search": "搜索路径、成员、差异文本",
"html.changes": "主差异",
"html.review": "需复核结构",
"html.noise": "疑似写法噪声",
"html.all": "全部",
"html.previous": "上一页",
"html.next": "下一页",
"html.raw": "查看保留局部名 / 括号 / 泛型的差异",
"html.files": "文件",
"html.members": "变化",
"html.group_review": "需复核",
"html.group_noise": "疑似噪声",
"html.file_summary": "%s · %s (%d 变化 / %d 复核 / %d 噪声)",
"html.file_paths": "旧: %s → 新: %s",
"status.modified": "变化",
"status.added": "新增",
"status.removed": "删除",
"status.noise": "疑似噪声",
"status.review": "需复核",
"status.error": "读取失败"
}
+38
View File
@@ -0,0 +1,38 @@
{
"reason.normalized": "區域名稱 / 冗餘括號 / 推斷泛型 / 產生編號 / 標籤 / 屬性順序(啟發式,需審閱)",
"reason.using": "using 宣告變化,未做名稱繫結證明,保留複核",
"reason.async": "async / 狀態機匯出結構不同,需複核本文",
"reason.ambiguous": "匯出程式碼含同一範圍內重名區域變數,無法可靠還原繫結",
"member.declaration_order": "宣告 / 初始化順序",
"member.method_order": "方法 / using 排列順序",
"reason.order": "同名成員分別比較,宣告順序單獨記錄",
"member.whole_file": "整個檔案",
"warning.unpaired": "同名型別未能唯一配對,保留為%s獨立檔案: %s",
"cli.inventory": "舊版 %d / 新版 %d C# 檔案;%d workers\n",
"cli.complete": "%s\n匹配混淆後綴路徑 %d;比較 %.2fs;總計 %.2fs\n摘要: %s\n視覺化: %s\n",
"summary.timing": "%s\n耗時 %.2fs / %d workers\n行號為正規化成員行號;疑似雜訊不等於已證明語意相同。\n\n",
"summary.warning": "警告: %s\n",
"summary.paths": "\n主要差異: %s\n需複核結構: %s\n疑似雜訊: %s\n視覺化: %s\n結構化報告: %s\n",
"html.title": "用戶端原始碼 Clean Diff",
"html.instructions": "依檔案 → 成員展開。行號為正規化成員行號;區域變數顯示為 localN,可展開保留原名稱的 diff。複核區保留 async / 狀態機與無法確定的結構變化。",
"html.search": "搜尋路徑、成員、差異文字",
"html.changes": "主要差異",
"html.review": "需複核結構",
"html.noise": "疑似寫法雜訊",
"html.all": "全部",
"html.previous": "上一頁",
"html.next": "下一頁",
"html.raw": "檢視保留區域名稱 / 括號 / 泛型的差異",
"html.files": "檔案",
"html.members": "變化",
"html.group_review": "需複核",
"html.group_noise": "疑似雜訊",
"html.file_summary": "%s · %s (%d 變化 / %d 複核 / %d 雜訊)",
"html.file_paths": "舊: %s → 新: %s",
"status.modified": "變化",
"status.added": "新增",
"status.removed": "刪除",
"status.noise": "疑似雜訊",
"status.review": "需複核",
"status.error": "讀取失敗"
}
+17
View File
@@ -0,0 +1,17 @@
package sourcetools
import (
"embed"
"sync"
"bd2server/internal/common/i18n"
)
//go:embed lang/*.json
var diffLanguages embed.FS
var loadDiffLanguages = sync.OnceValues(func() (*i18n.Catalog, error) {
return i18n.Load(diffLanguages, "lang")
})
type diffText func(string, ...any) string
+5 -5
View File
@@ -92,7 +92,7 @@ func inventory(root string, includes, excludes []string) ([]string, error) {
type fileTask struct{ logical, old, new string }
func pairTrees(a, b string, ia, ib []string) ([]fileTask, map[string]string, map[string]string, []string) {
func pairTrees(a, b string, ia, ib []string, text diffText) ([]fileTask, map[string]string, map[string]string, []string) {
ga, gb := map[string][]string{}, map[string][]string{}
for _, p := range ia {
logical := suffixPattern.ReplaceAllString(p, "")
@@ -291,7 +291,7 @@ func pairTrees(a, b string, ia, ib []string) ([]fileTask, map[string]string, map
side = "new"
}
for _, p := range sortedSet(remainder) {
warnings = append(warnings, fmt.Sprintf("同名类型未能唯一配对,保留为%s独立文件: %s", side, p))
warnings = append(warnings, text("warning.unpaired", side, p))
tag := sha256.Sum256([]byte(p))
ext := filepath.Ext(logical)
key := strings.TrimSuffix(logical, ext) + fmt.Sprintf("__unpaired_%s_%x", side, tag[:6]) + ext
@@ -306,7 +306,7 @@ func pairTrees(a, b string, ia, ib []string) ([]fileTask, map[string]string, map
sort.Slice(tasks, func(i, j int) bool { return tasks[i].logical < tasks[j].logical })
return tasks, symbolsA, symbolsB, warnings
}
func compareFile(a, b string, t fileTask, context int, strict bool, symbolsA, symbolsB map[string]string) fileResult {
func compareFile(a, b string, t fileTask, context int, strict bool, symbolsA, symbolsB map[string]string, text diffText) fileResult {
result := fileResult{Path: t.logical, Status: "unchanged", Members: []diffEntry{}, Noise: []diffEntry{}}
if t.old != "" {
p := t.old
@@ -338,10 +338,10 @@ func compareFile(a, b string, t fileTask, context int, strict bool, symbolsA, sy
} else {
oldName = "/dev/null"
}
result.Members = append(result.Members, diffEntry{Name: "整个文件", Kind: result.Status, Diff: unified(render(tokenize(old, symbolsA)), render(tokenize(new, symbolsB)), oldName, newName, context)})
result.Members = append(result.Members, diffEntry{Name: text("member.whole_file"), Kind: result.Status, Diff: unified(render(tokenize(old, symbolsA)), render(tokenize(new, symbolsB)), oldName, newName, context)})
return result
}
compared := compareText(old, new, context, strict, symbolsA, symbolsB)
compared := compareText(old, new, context, strict, symbolsA, symbolsB, text)
compared.Path, compared.OldPath, compared.NewPath = result.Path, result.OldPath, result.NewPath
return compared
}
+5 -1
View File
@@ -127,10 +127,14 @@ func runClientDevelopmentCommand(args []string) (bool, error) {
return buildDevelopmentPlugins(ctx, root, gameDir)
}},
taskgraph.Task{Name: "client:options", DependsOn: []string{"client:plugins"}, Run: func(context.Context) error {
plugins, err := clientplugin.Development(root)
if err != nil {
return err
}
options = clientRunOptions{
versionConfigPath: filepath.Join(root, "versions.json"),
logExecutablePath: filepath.Join(root, "data", "bd2client-dev"),
plugins: clientplugin.Development(root),
plugins: plugins,
}
return nil
}},
+7 -15
View File
@@ -23,14 +23,8 @@ type Config struct {
MinimumPlugins pluginVersions `json:"minimum_plugins"`
}
type pluginVersions struct {
LocalIdentity string `json:"local_identity"`
CaptureEnvironment string `json:"capture_environment"`
LoginUI string `json:"login_ui"`
CashShop string `json:"cash_shop"`
FChat string `json:"fchat"`
FBattle string `json:"fbattle,omitempty"`
}
// pluginVersions maps plugin version keys to versions.
type pluginVersions map[string]string
func readConfig(path string, config *Config) error {
raw, err := os.ReadFile(path)
@@ -54,7 +48,7 @@ func GameVersion(path string) (string, error) {
if err := readConfig(path, &config); err != nil {
return "", err
}
if _, err := config.validate("local_identity"); err != nil {
if _, err := config.validate(""); err != nil {
return "", err
}
return config.GameVersion, nil
@@ -106,13 +100,11 @@ namespace Bd2Build
}
func (c Config) validate(plugin string) (string, error) {
plugins := map[string]string{"local_identity": c.Plugins.LocalIdentity, "capture_environment": c.Plugins.CaptureEnvironment, "login_ui": c.Plugins.LoginUI, "cash_shop": c.Plugins.CashShop, "fchat": c.Plugins.FChat}
if c.Plugins.FBattle != "" {
plugins["fbattle"] = c.Plugins.FBattle
}
// An empty plugin validates the file without selecting a version.
plugins := c.Plugins
selected, found := plugins[plugin]
if !found {
return "", fmt.Errorf("unsupported plugin %q", plugin)
if plugin != "" && !found {
return "", fmt.Errorf("versions.json has no plugins.%s", plugin)
}
semver := regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
resource := regexp.MustCompile(`^[0-9]{14}$`)
+10 -1
View File
@@ -216,7 +216,16 @@ func (s *Studio) Browse(input Request) (Response, error) {
if dir == "" {
return success("Selection cancelled", nil), nil
}
return success("Installation directory selected", clientsetup.GameStatus{GameDirectory: dir}), nil
// An empty directory is a valid install target, so a failed check
// only reports what is missing instead of rejecting the selection.
status, inspectErr := clientsetup.Inspect(dir, s.versions(dir))
if status.GameDirectory == "" {
status.GameDirectory = dir
}
if inspectErr != nil {
s.log().Info("selected directory is not a ready game client", "directory", dir, "reason", inspectErr)
}
return success("Installation directory selected", status), nil
})
}
+13 -11
View File
@@ -23,9 +23,6 @@ import (
// BuildDevelopment compiles the client plugins as one dependency graph, sharing
// the game SDK and version preparation across the entry projects.
func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Writer) error {
if err := validateDefinitions(); err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
@@ -38,6 +35,11 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
if err != nil {
return err
}
registry, err := Load(root)
if err != nil {
return err
}
definitions := registry.Plugins
managed := filepath.Join(installation.Data, "Managed")
identity := sha256.Sum256([]byte(root + "\x00" + managed + "\x00" + installation.BepInEx))
work := filepath.Join(root, ".build", "client-plugins", hex.EncodeToString(identity[:12]))
@@ -54,7 +56,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
defer func() { _ = digests.save(digestPath) }()
_, _ = fmt.Fprintln(progress, "Client plugins: checking source, game DLL and output fingerprints...")
cacheStarted := time.Now()
inputs, err := snapshotInputs(root, managed, installation.BepInEx, digests)
inputs, err := snapshotInputs(root, managed, installation.BepInEx, registry, digests)
if err != nil {
return err
}
@@ -75,8 +77,8 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
compileInputsDir := filepath.Join(work, "compile-inputs")
sdkInputs := filepath.Join(compileInputsDir, "sdk.g.cs")
namesInputs := filepath.Join(compileInputsDir, "names.g.cs")
sdkFingerprint := dependencyFingerprint(root, inputs, "GameSdk")
namesFingerprint := dependencyFingerprint(root, inputs, "GameNames")
sdkFingerprint := dependencyFingerprint(root, definitions, inputs, "GameSdk")
namesFingerprint := dependencyFingerprint(root, definitions, inputs, "GameNames")
sdkInputsKey := map[string]string{"sdk": sdkFingerprint, "game_version": gameVersion}
for file, sum := range inputs {
if strings.HasPrefix(file, managed+string(filepath.Separator)) || strings.HasPrefix(file, installation.BepInEx+string(filepath.Separator)) {
@@ -140,7 +142,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
if err := buildversion.Generate(versionConfig, filepath.Join(versionDir, project.VersionKey+".g.cs"), project.VersionKey); err != nil {
return err
}
inputStamp, err := projectFingerprint(root, inputs, project.Name(), filepath.Join(versionDir, project.VersionKey+".g.cs"))
inputStamp, err := projectFingerprint(root, definitions, inputs, project.Name(), filepath.Join(versionDir, project.VersionKey+".g.cs"))
if err != nil {
return err
}
@@ -154,7 +156,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
}},
taskgraph.Task{Name: "pluginsCompile", DependsOn: []string{"versionSources"}, Run: func(context.Context) error {
compileStarted := time.Now()
if err := writeAggregateProject(filepath.Join(work, "ClientPlugins.proj"), root); err != nil {
if err := writeAggregateProject(filepath.Join(work, "ClientPlugins.proj"), root, definitions); err != nil {
return err
}
_, _ = fmt.Fprintf(progress, "Client plugins: compiling all %d plugins as one parallel dependency graph...\n", len(definitions))
@@ -190,7 +192,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
outputs = append(outputs, filepath.Join(versionDir, project.VersionKey+".g.cs"), filepath.Join(compileInputsDir, project.VersionKey+".g.cs"))
}
}
if err := verifyDependencyOutputs(root); err != nil {
if err := verifyDependencyOutputs(root, definitions); err != nil {
return err
}
sums := make(map[string]string, len(outputs))
@@ -201,7 +203,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
}
sums[output] = sum
}
finalInputs, err := snapshotInputs(root, managed, installation.BepInEx, digests)
finalInputs, err := snapshotInputs(root, managed, installation.BepInEx, registry, digests)
if err != nil {
return err
}
@@ -289,7 +291,7 @@ func runPluginBuild(ctx context.Context, root string, progress io.Writer, args .
return nil
}
func writeAggregateProject(path, root string) error {
func writeAggregateProject(path, root string, definitions []Definition) error {
var content, properties bytes.Buffer
content.WriteString("<Project DefaultTargets=\"Build\"><ItemGroup>")
properties.WriteString("<Project>")
+14 -10
View File
@@ -68,8 +68,8 @@ func (cache fileDigestCache) save(path string) error {
return saveBuildJSON(path, data)
}
func snapshotInputs(root, managed, bep string, cache fileDigestCache) (map[string]string, error) {
files, err := developmentInputs(root, managed, bep)
func snapshotInputs(root, managed, bep string, registry Registry, cache fileDigestCache) (map[string]string, error) {
files, err := developmentInputs(root, managed, bep, registry)
if err != nil {
return nil, err
}
@@ -84,7 +84,7 @@ func snapshotInputs(root, managed, bep string, cache fileDigestCache) (map[strin
return inputs, nil
}
func projectFingerprint(root string, inputs map[string]string, project, versionSource string) (string, error) {
func projectFingerprint(root string, definitions []Definition, inputs map[string]string, project, versionSource string) (string, error) {
var definition Definition
for _, candidate := range definitions {
if candidate.Name() == project {
@@ -92,7 +92,7 @@ func projectFingerprint(root string, inputs map[string]string, project, versionS
break
}
}
relevant := selectDependencyInputs(root, inputs, definition)
relevant := selectDependencyInputs(root, definitions, inputs, definition)
if versionSource != "" {
sum, err := util.SHA256File(versionSource)
if err != nil {
@@ -103,8 +103,8 @@ func projectFingerprint(root string, inputs map[string]string, project, versionS
return digestInputs(relevant), nil
}
func selectDependencyInputs(root string, inputs map[string]string, definition Definition) map[string]string {
projects := definition.dependencyProjects()
func selectDependencyInputs(root string, definitions []Definition, inputs map[string]string, definition Definition) map[string]string {
projects := definition.dependencyProjects(definitions)
relevant := make(map[string]string)
for file, sum := range inputs {
if strings.HasSuffix(file, ".go") || file == filepath.Join(root, "versions.json") || file == filepath.Join(root, "go", "go.mod") || file == filepath.Join(root, "go", "go.sum") {
@@ -140,7 +140,7 @@ func selectDependencyInputs(root string, inputs map[string]string, definition De
return relevant
}
func dependencyFingerprint(root string, inputs map[string]string, project string) string {
func dependencyFingerprint(root string, definitions []Definition, inputs map[string]string, project string) string {
definition := Definition{ProjectPath: project + "/" + project + ".csproj"}
for _, candidate := range definitions {
if candidate.Name() == project {
@@ -156,18 +156,22 @@ func dependencyFingerprint(root string, inputs map[string]string, project string
}
definition.UsesGameSdk = true
}
return digestInputs(selectDependencyInputs(root, inputs, definition))
return digestInputs(selectDependencyInputs(root, definitions, inputs, definition))
}
func developmentInputs(root, managed, bep string) ([]string, error) {
func developmentInputs(root, managed, bep string, registry Registry) ([]string, error) {
var files []string
tools := map[string]bool{}
for _, tool := range registry.Tools {
tools[filepath.Join(root, "plugins", filepath.Dir(filepath.FromSlash(tool.ProjectPath)))] = true
}
for _, directory := range []string{filepath.Join(root, "plugins"), filepath.Join(root, "go", "internal", "client", "plugin"), filepath.Join(root, "go", "internal", "buildversion")} {
err := filepath.WalkDir(directory, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
if entry.Name() == "bin" || entry.Name() == "obj" || entry.Name() == ".git" || entry.Name() == "CaptureEnvironment" || entry.Name() == "samples" {
if entry.Name() == "bin" || entry.Name() == "obj" || entry.Name() == ".git" || tools[path] || entry.Name() == "samples" {
return filepath.SkipDir
}
return nil
+6 -1
View File
@@ -28,6 +28,7 @@ func TestVerifiedPluginCacheSkipsSDKVersionAndCompilationStages(t *testing.T) {
write("game/BrownDust II_Data/Managed/Assembly-CSharp.dll", "fixture")
write("game/BepInEx/core/BepInEx.dll", "fixture")
write("plugins/LocalIdentity/Plugin.cs", "fixture")
write(RegistryFile, `{"plugins":[{"id":"local_identity","project":"LocalIdentity/LocalIdentity.csproj","framework":"netstandard2.1","file":"BD2LocalIdentity.dll","version_key":"local_identity"}],"tools":[]}`)
write("go/internal/client/plugin/build.go", "fixture")
write("go/internal/buildversion/version.go", "fixture")
write("versions.json", "invalid JSON must not be read when cache is current")
@@ -49,7 +50,11 @@ func TestVerifiedPluginCacheSkipsSDKVersionAndCompilationStages(t *testing.T) {
if work == "" {
t.Fatal("build did not establish a cache workspace")
}
inputs, err := snapshotInputs(root, filepath.Join(game, "BrownDust II_Data", "Managed"), filepath.Join(game, "BepInEx"), make(fileDigestCache))
registry, err := Load(root)
if err != nil {
t.Fatal(err)
}
inputs, err := snapshotInputs(root, filepath.Join(game, "BrownDust II_Data", "Managed"), filepath.Join(game, "BepInEx"), registry, make(fileDigestCache))
if err != nil {
t.Fatal(err)
}
+96 -32
View File
@@ -1,57 +1,90 @@
package plugin
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"bd2server/internal/common/util"
)
// RegistryFile lists every client plugin project. Adding a plugin only needs
// an entry here and its version in versions.json.
const RegistryFile = "plugins/registry.json"
type Definition struct {
ID, ProjectPath, Framework, FileName, VersionKey string
UsesGameSdk bool
SharedRuntime bool
Dependencies []string
ID string `json:"id"`
ProjectPath string `json:"project"`
Framework string `json:"framework"`
FileName string `json:"file"`
VersionKey string `json:"version_key,omitempty"`
UsesGameSdk bool `json:"game_sdk,omitempty"`
SharedRuntime bool `json:"shared_runtime,omitempty"`
Dependencies []string `json:"dependencies,omitempty"`
}
var definitions = []Definition{
{ID: "game_names", ProjectPath: "GameNames/GameNames.csproj", Framework: "netstandard2.0", FileName: "BD2.GameNames.dll", SharedRuntime: true},
{ID: "local_identity", ProjectPath: "LocalIdentity/LocalIdentity.csproj", Framework: "netstandard2.1", FileName: "BD2LocalIdentity.dll", VersionKey: "local_identity", UsesGameSdk: true, Dependencies: []string{"game_names"}},
{ID: "login_ui", ProjectPath: "LoginUI/LoginUI.csproj", Framework: "netstandard2.1", FileName: "BD2LoginUI.dll", VersionKey: "login_ui", UsesGameSdk: true, Dependencies: []string{"game_names"}},
{ID: "cash_shop", ProjectPath: "CashShop/CashShop.csproj", Framework: "netstandard2.1", FileName: "BD2CashShop.dll", VersionKey: "cash_shop", UsesGameSdk: true, Dependencies: []string{"game_names"}},
{ID: "fchat", ProjectPath: "FChat/FChat.csproj", Framework: "netstandard2.1", FileName: "BD2FChat.dll", VersionKey: "fchat", UsesGameSdk: true, Dependencies: []string{"game_names", "login_ui"}},
{ID: "fbattle", ProjectPath: "FBattle/FBattle.csproj", Framework: "netstandard2.1", FileName: "BD2FBattle.dll", VersionKey: "fbattle", UsesGameSdk: true, Dependencies: []string{"game_names", "local_identity"}},
{ID: "brown_dust_x_accel", ProjectPath: "BrownDustXAccel/BrownDustXAccel.csproj", Framework: "netstandard2.1", FileName: "BD2BrownDustXAccel.dll"},
// Tool is a C# project that is checked with the plugins but never shipped
// and never an input of the plugin build.
type Tool struct {
ProjectPath string `json:"project"`
}
func Definitions() []Definition {
out := slices.Clone(definitions)
for i := range out {
out[i].Dependencies = slices.Clone(out[i].Dependencies)
type Registry struct {
Plugins []Definition `json:"plugins"`
Tools []Tool `json:"tools"`
}
// Load reads and validates the plugin registry below the repository root.
func Load(root string) (Registry, error) {
var registry Registry
path := filepath.Join(root, filepath.FromSlash(RegistryFile))
raw, err := os.ReadFile(path)
if err != nil {
return registry, fmt.Errorf("clientplugin: read registry: %w", err)
}
return out
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&registry); err != nil {
return registry, fmt.Errorf("clientplugin: %s: %w", path, err)
}
if decoder.More() {
return registry, fmt.Errorf("clientplugin: %s must contain exactly one JSON object", path)
}
if err := registry.validate(); err != nil {
return registry, err
}
return registry, nil
}
func validateDefinitions() error {
byID := make(map[string]Definition, len(definitions))
outputs, projects := map[string]bool{}, map[string]bool{}
for _, d := range definitions {
func (r Registry) validate() error {
if len(r.Plugins) == 0 {
return errors.New("clientplugin: registry lists no plugins")
}
byID := make(map[string]Definition, len(r.Plugins))
outputs, projects, versionKeys := map[string]bool{}, map[string]bool{}, map[string]bool{}
for _, d := range r.Plugins {
if err := validateName(d.FileName); err != nil {
return err
}
if d.ID == "" || d.Name() == "" || d.ProjectPath == "" || filepath.IsAbs(d.ProjectPath) || strings.HasPrefix(filepath.Clean(d.ProjectPath), "..") {
if d.ID == "" || d.Framework == "" || !validProject(d.ProjectPath) {
return fmt.Errorf("clientplugin: invalid project definition %q", d.ID)
}
_, duplicate := byID[d.ID]
if duplicate || outputs[strings.ToLower(d.FileName)] || projects[d.Name()] {
if duplicate || outputs[strings.ToLower(d.FileName)] || projects[d.Name()] || d.VersionKey != "" && versionKeys[d.VersionKey] {
return fmt.Errorf("clientplugin: duplicate plugin definition %s", d.ID)
}
byID[d.ID], outputs[strings.ToLower(d.FileName)], projects[d.Name()] = d, true, true
byID[d.ID], outputs[strings.ToLower(d.FileName)], projects[d.Name()], versionKeys[d.VersionKey] = d, true, true, true
}
for _, tool := range r.Tools {
name := Definition{ProjectPath: tool.ProjectPath}.Name()
if !validProject(tool.ProjectPath) || projects[name] || name == "GameSdk" {
return fmt.Errorf("clientplugin: invalid tool project %q", tool.ProjectPath)
}
projects[name] = true
}
visited, visiting := map[string]bool{}, map[string]bool{}
var visit func(string) error
@@ -75,7 +108,7 @@ func validateDefinitions() error {
visiting[id], visited[id] = false, true
return nil
}
for _, d := range definitions {
for _, d := range r.Plugins {
if err := visit(d.ID); err != nil {
return err
}
@@ -83,6 +116,28 @@ func validateDefinitions() error {
return nil
}
func validProject(project string) bool {
clean := filepath.Clean(filepath.FromSlash(project))
return project != "" && strings.EqualFold(filepath.Ext(clean), ".csproj") && !filepath.IsAbs(clean) &&
clean != ".." && !strings.HasPrefix(clean, ".."+string(filepath.Separator)) && strings.Contains(filepath.ToSlash(clean), "/")
}
// Project is one C# project the repository checks.
type Project struct{ Name, File string }
// Projects lists every C# project in check order: the shared SDK, the tools,
// then the plugins.
func (r Registry) Projects(root string) []Project {
projects := []Project{{"GameSdk", filepath.Join(root, "plugins", "GameSdk", "GameSdk.csproj")}}
for _, tool := range r.Tools {
projects = append(projects, Project{Definition{ProjectPath: tool.ProjectPath}.Name(), filepath.Join(root, "plugins", filepath.FromSlash(tool.ProjectPath))})
}
for _, d := range r.Plugins {
projects = append(projects, Project{d.Name(), d.ProjectFile(root)})
}
return projects
}
func (d Definition) Name() string {
return strings.TrimSuffix(filepath.Base(d.ProjectPath), filepath.Ext(d.ProjectPath))
}
@@ -95,7 +150,7 @@ func (d Definition) Output(root string) string {
return filepath.Join(filepath.Dir(d.ProjectFile(root)), "bin", "Release", d.Framework, d.FileName)
}
func (d Definition) dependencyProjects() map[string]bool {
func (d Definition) dependencyProjects(definitions []Definition) map[string]bool {
projects := map[string]bool{d.Name(): true}
var visit func(Definition)
visit = func(current Definition) {
@@ -112,9 +167,9 @@ func (d Definition) dependencyProjects() map[string]bool {
return projects
}
func verifyDependencyOutputs(root string) error {
func verifyDependencyOutputs(root string, definitions []Definition) error {
for _, d := range definitions {
projects := d.dependencyProjects()
projects := d.dependencyProjects(definitions)
for _, dependency := range definitions {
if !dependency.SharedRuntime || d.ID == dependency.ID || !projects[dependency.Name()] {
continue
@@ -141,9 +196,18 @@ type Artifact struct {
type Set []Artifact
func Development(root string) Set {
set := make(Set, 0, len(definitions))
for _, d := range definitions {
// Development lists the plugin outputs built from the repository at root.
func Development(root string) (Set, error) {
registry, err := Load(root)
if err != nil {
return nil, err
}
return registry.Development(root), nil
}
func (r Registry) Development(root string) Set {
set := make(Set, 0, len(r.Plugins))
for _, d := range r.Plugins {
set = append(set, Artifact{ID: d.ID, Name: d.FileName, Source: d.Output(root), VersionKey: d.VersionKey})
}
return set
+2 -1
View File
@@ -23,7 +23,8 @@ const (
// Schema describes a document for generic editors. Generic constraints
// (options, ranges, uniqueness and map keys) are enforced by Check, so a
// document states each such rule once; cross-field rules remain in the
// document's own validation function.
// document's own validation function. Presentation text uses catalog keys,
// resolved by the editor; technical placeholders may remain literal.
type Schema struct {
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
+20
View File
@@ -0,0 +1,20 @@
package logging
import (
"errors"
"log/slog"
)
// ErrorAttributes keeps diagnostic context when an error crosses a transport boundary.
func ErrorAttributes(err error) []slog.Attr {
attrs := []slog.Attr{slog.Any("error", err)}
var diagnostic interface {
DiagnosticAttributes() []slog.Attr
DiagnosticCause() error
}
if errors.As(err, &diagnostic) {
attrs[0] = slog.Any("error", diagnostic.DiagnosticCause())
attrs = append(attrs, diagnostic.DiagnosticAttributes()...)
}
return attrs
}
+4 -10
View File
@@ -83,12 +83,6 @@ var migrationKinds = map[string]string{
MigrationNone: MigrationNone, MigrationReversible: MigrationReversible, MigrationIrreversible: MigrationIrreversible,
}
// defaultTitles name an untitled language block: "Server 0.3.0 update".
var defaultTitles = map[string]map[string]string{
ComponentServer: {"en_us": "Server %s update", "ko_kr": "서버 %s 업데이트", "ja_jp": "サーバー %s アップデート", "zh_tw": "伺服器 %s 更新", "zh_cn": "服务端 %s 更新"},
ComponentClient: {"en_us": "Client %s update", "ko_kr": "클라이언트 %s 업데이트", "ja_jp": "クライアント %s アップデート", "zh_tw": "用戶端 %s 更新", "zh_cn": "客户端 %s 更新"},
}
type changelogParser struct {
entries []Entry
current *Entry
@@ -197,7 +191,7 @@ func (p *changelogParser) finishLanguage() error {
}
if text.Title == "" {
v, _ := ParseVersion(p.current.Version)
text.Title = fmt.Sprintf(defaultTitles[p.current.Component][p.locale], v.Short())
text.Title = texts.Translate(p.locale, "release."+p.current.Component+".title", v.Short())
}
p.current.Text[p.locale] = text
p.locale, p.body = "", nil
@@ -405,10 +399,10 @@ func ChangelogTemplate(component, version string, date time.Time) string {
b.WriteString("> migration: none\n")
}
v, _ := ParseVersion(version)
sections := map[string][3]string{"en_us": {"Added", "Changed", "Fixed"}, "zh_cn": {"新增", "调整", "修复"}}
for _, locale := range []string{"en_us", "zh_cn"} {
fmt.Fprintf(&b, "\n### %s: %s\n", locale, fmt.Sprintf(defaultTitles[component][locale], v.Short()))
for _, heading := range sections[locale] {
fmt.Fprintf(&b, "\n### %s: %s\n", locale, texts.Translate(locale, "release."+component+".title", v.Short()))
for _, section := range []string{"added", "changed", "fixed"} {
heading := texts.Translate(locale, "release.section."+section)
fmt.Fprintf(&b, "\n#### %s\n\n- \n", heading)
}
}
@@ -0,0 +1,7 @@
{
"release.server.title": "Server %s update",
"release.client.title": "Client %s update",
"release.section.added": "Added",
"release.section.changed": "Changed",
"release.section.fixed": "Fixed"
}
@@ -0,0 +1,7 @@
{
"release.server.title": "サーバー %s アップデート",
"release.client.title": "クライアント %s アップデート",
"release.section.added": "追加",
"release.section.changed": "変更",
"release.section.fixed": "修正"
}
@@ -0,0 +1,7 @@
{
"release.server.title": "서버 %s 업데이트",
"release.client.title": "클라이언트 %s 업데이트",
"release.section.added": "추가",
"release.section.changed": "변경",
"release.section.fixed": "수정"
}
@@ -0,0 +1,7 @@
{
"release.server.title": "服务端 %s 更新",
"release.client.title": "客户端 %s 更新",
"release.section.added": "新增",
"release.section.changed": "调整",
"release.section.fixed": "修复"
}
@@ -0,0 +1,7 @@
{
"release.server.title": "伺服器 %s 更新",
"release.client.title": "用戶端 %s 更新",
"release.section.added": "新增",
"release.section.changed": "調整",
"release.section.fixed": "修復"
}
+17
View File
@@ -0,0 +1,17 @@
package release
import (
"bd2server/internal/common/i18n"
"embed"
)
//go:embed lang/*.json
var languageFiles embed.FS
var texts = func() *i18n.Catalog {
catalog, err := i18n.Load(languageFiles, "lang")
if err != nil {
panic(err)
}
return catalog
}()
+19 -37
View File
@@ -5,6 +5,7 @@ package versionconfig
import (
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"regexp"
@@ -20,6 +21,7 @@ var (
semanticVersion = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
releaseVersion = regexp.MustCompile(`^([0-9]+\.[0-9]+\.[0-9]+)\+(client|server)\.([0-9]+\.[0-9]+\.[0-9]+)$`)
resourceVersion = regexp.MustCompile(`^[0-9]{14}$`)
pluginKey = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
currentMu sync.RWMutex
current *Config
)
@@ -40,14 +42,9 @@ type Config struct {
SourcePath string `json:"-"`
}
type PluginVersions struct {
LocalIdentity string `json:"local_identity"`
CaptureEnvironment string `json:"capture_environment"`
LoginUI string `json:"login_ui"`
CashShop string `json:"cash_shop"`
FChat string `json:"fchat"`
FBattle string `json:"fbattle,omitempty"`
}
// PluginVersions maps each plugin's version key (see plugins/registry.json)
// to its three-part version.
type PluginVersions map[string]string
// Load reads one explicit version file. Unknown fields and trailing JSON are
// rejected so a misspelled version key cannot silently select stale data.
@@ -74,25 +71,23 @@ func GameData() string { return Current().GameDataVersion }
func Bundle() string { return Current().BundleVersion }
func (c Config) Validate() error {
for name, value := range map[string]string{
"game_version": c.GameVersion,
"plugins.local_identity": c.Plugins.LocalIdentity,
"plugins.capture_environment": c.Plugins.CaptureEnvironment,
"plugins.login_ui": c.Plugins.LoginUI,
"plugins.fchat": c.Plugins.FChat,
} {
if !semanticVersion.MatchString(value) {
return fmt.Errorf("%s must be a numeric three-part version", name)
if !semanticVersion.MatchString(c.GameVersion) {
return errors.New("game_version must be a numeric three-part version")
}
if len(c.Plugins) == 0 {
return errors.New("plugins must list at least one plugin version")
}
for id, version := range c.Plugins {
if !pluginKey.MatchString(id) || !semanticVersion.MatchString(version) {
return fmt.Errorf("plugins.%s must be a numeric three-part version", id)
}
}
for id, pair := range c.Plugins.pairs(c.MinimumPlugins) {
if !semanticVersion.MatchString(pair[1]) || compareSemantic(pair[1], pair[0]) > 0 {
for id, minimum := range c.MinimumPlugins {
current, found := c.Plugins[id]
if !found || !semanticVersion.MatchString(minimum) || compareSemantic(minimum, current) > 0 {
return fmt.Errorf("minimum_plugins.%s must be a numeric three-part version no newer than plugins.%s", id, id)
}
}
if c.Plugins.FBattle != "" && !semanticVersion.MatchString(c.Plugins.FBattle) {
return errors.New("plugins.fbattle must be a numeric three-part version")
}
if err := validateReleaseVersion("client_version", c.ClientVersion, c.GameVersion, "client"); err != nil {
return err
}
@@ -116,22 +111,9 @@ func (c Config) Validate() error {
return nil
}
// ByID lists the plugin versions under their versions.json keys.
// ByID returns a copy of the versions under their versions.json keys.
func (p PluginVersions) ByID() map[string]string {
versions := map[string]string{"local_identity": p.LocalIdentity, "capture_environment": p.CaptureEnvironment, "login_ui": p.LoginUI, "cash_shop": p.CashShop, "fchat": p.FChat}
if p.FBattle != "" {
versions["fbattle"] = p.FBattle
}
return versions
}
func (p PluginVersions) pairs(minimum PluginVersions) map[string][2]string {
current, lowest := p.ByID(), minimum.ByID()
out := map[string][2]string{}
for id, version := range current {
out[id] = [2]string{version, lowest[id]}
}
return out
return maps.Clone(map[string]string(p))
}
func compareSemantic(a, b string) int {
+1
View File
@@ -54,6 +54,7 @@ type Player struct {
AccountID string `json:"account_id"`
UID string `json:"uid"`
Name string `json:"name"`
NameKey string `json:"name_key,omitempty"`
Active bool `json:"active"`
}
+3 -3
View File
@@ -34,9 +34,9 @@ type Ability struct {
}
var abilities = []Ability{
{Key: PermissionPlayers, Label: "查看玩家", Help: "查看玩家列表、UID 与背包设置。", Default: true},
{Key: PermissionMail, Label: "邮件发放", Help: "给自己的账号寄送物品和货币;只有服主能给其他玩家寄送。", Requires: []string{PermissionPlayers}},
{Key: PermissionItemStacks, Label: "不限物品堆叠", Help: "开关自己账号的物品堆叠上限,只能修改自己的账号。", Requires: []string{PermissionMail}},
{Key: PermissionPlayers, Label: "console.permission.players.view.label", Help: "console.permission.players.view.help", Default: true},
{Key: PermissionMail, Label: "console.permission.mail.send.label", Help: "console.permission.mail.send.help", Requires: []string{PermissionPlayers}},
{Key: PermissionItemStacks, Label: "console.permission.players.item_stacks.label", Help: "console.permission.players.item_stacks.help", Requires: []string{PermissionMail}},
}
type ConfigurationGrant struct {
+16 -13
View File
@@ -155,7 +155,8 @@ const clone = value => value === undefined ? undefined : JSON.parse(JSON.stringi
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const fmt = n => Number(n).toLocaleString(tag());
const dateTime = value => new Date(value).toLocaleString(tag());
const playerLabel = p => p ? (p.uid ? 'UID ' + p.uid : '') + (p.name ? ' · ' + p.name : '') : '';
const playerName = p => p?.name_key ? t(p.name_key) : p?.name || '';
const playerLabel = p => p ? (p.uid ? 'UID ' + p.uid : '') + (playerName(p) ? ' · ' + playerName(p) : '') : '';
/* ---------- Sign-in and routing ---------- */
let loginTimer;
@@ -423,7 +424,7 @@ const mailTool = (() => {
const display = $('uid-display');
display.textContent = player ? player.uid || '——' : '——'; display.classList.toggle('none', !player);
$('slip-uid').textContent = player ? player.uid : '—';
$('recipient-note').textContent = player ? (player.name || '') : t('console.mail.recipient.none');
$('recipient-note').textContent = player ? playerName(player) : t('console.mail.recipient.none');
}
$('uid-display').onclick = async () => { if (target && target.uid) await copy(target.uid, 'UID'); };
// The stack switch always belongs to the signed-in account, whoever the mail is for.
@@ -542,12 +543,12 @@ const roster = (() => {
$('roster-head-row').replaceChildren(...['console.roster.col.uid', 'console.roster.col.name', 'console.roster.col.role', owner ? 'console.roster.col.admin' : null, '']
.filter(h => h !== null).map((h, i) => el('th', {class: i >= 3 && h ? 'c' : ''}, h ? t(h) : '')));
const q = $('player-q').value.trim().toLowerCase();
const rows = state.players.filter(p => !q || (p.uid + ' ' + p.name).toLowerCase().includes(q));
const rows = state.players.filter(p => !q || (p.uid + ' ' + playerName(p)).toLowerCase().includes(q));
$('roster').replaceChildren(...rendered(await Promise.all(rows.map(async p => {
const adminCell = owner ? el('td', {class: 'c'}, p.owner ? el('span', {class: 'muted'}, '—') : toggle(p.administrator, !p.active || state.session.mode !== 'oauth', async event => await setAdministrator(p, event.target), t('console.role.admin'))) : null;
return el('tr', {class: p.active ? '' : 'inactive'},
el('td', {class: 'uid-cell'}, p.uid || '—'),
el('td', {}, p.name || ''),
el('td', {}, playerName(p)),
el('td', {}, p.owner ? el('span', {class: 'pill owner'}, t('console.role.owner')) : null,
p.administrator ? el('span', {class: 'pill member', title: owner ? await summary(p) : ''}, t('console.role.admin')) : null,
p.active ? null : el('span', {class: 'pill'}, t('console.roster.inactive')),
@@ -608,7 +609,7 @@ const roster = (() => {
} catch (error) { if (error !== staleRender) throw error; }
};
await draw();
if (!await ask({title: await dynamicText('console.permissions.title', player.uid), body: player.name || '', extra: editor, ok: t('console.permissions.save')})) return;
if (!await ask({title: await dynamicText('console.permissions.title', player.uid), body: playerName(player), extra: editor, ok: t('console.permissions.save')})) return;
try {
const {value} = await api('players/' + encodeURIComponent(player.account_id) + '/administrator', {method: 'PUT', body: {administrator: true, permissions: [...granted]}});
player.permissions = value.permissions; await render(); await toast(Component.translatable('console.roster.permissions_updated', String(player.uid)));
@@ -624,14 +625,13 @@ const config = (() => {
const doc = () => docs.find(d => d.name === current);
const fields = d => d.schema.sections.flatMap(s => s.fields);
const dirtyDoc = d => drafts[d.name] !== undefined && !same(drafts[d.name], d.view.value);
// Schema text comes from the server in one language; translations are keyed by its structure.
const valueKey = value => typeof value === 'string' ? value : JSON.stringify(value);
const docTitle = d => tr(`config.${d.name}.title`, d.schema.title);
const docSummary = d => tr(`config.${d.name}.summary`, d.schema.summary);
const sectionText = (d, s, part) => tr(`config.${d.name}.section.${s.id}.${part}`, s[part]);
const fieldText = (d, f, part) => tr(`config.${d.name}.field.${f.path}.${part}`, f[part]);
const optionText = (d, f, o, part, kind = 'option') => tr(`config.${d.name}.field.${f.path}.${kind}.${valueKey(o.value)}.${part}`, o[part]);
const lockReason = (d, lock) => tr(`config.${d.name}.lock.${lock.path}`, lock.reason);
const schemaText = key => key ? t(key) : '';
const docTitle = d => schemaText(d.schema.title);
const docSummary = d => schemaText(d.schema.summary);
const sectionText = (d, s, part) => schemaText(s[part]);
const fieldText = (d, f, part) => schemaText(f[part]);
const optionText = (d, f, o, part) => schemaText(o[part]);
const lockReason = (d, lock) => schemaText(lock.reason);
function getPath(object, path) { return path.split('.').reduce((value, key) => value == null ? undefined : value[key], object); }
function setPath(object, path, value) {
const keys = path.split('.'); let node = object;
@@ -678,6 +678,9 @@ const config = (() => {
'must be an object': 'object',
'must be present': 'present',
'a section outside your access is invalid': 'hidden_section',
'check interval must be at least 10m, for example 6h': 'update_interval',
'countdown must be 0 (immediate maintenance) or at least 5 minutes': 'update_countdown',
'install method must be native, docker or none': 'update_method',
};
async function describe(problem, field, d) {
const m = problem.message || '';
@@ -515,5 +515,18 @@
"config.game.section.spine_recording.title": "Interaction recording",
"config.game.section.spine_recording.help": "Save players’ interactive illustration actions for playback in the game. Restart the server after changing this setting.",
"config.game.field.spine_recording.download_base_url.label": "Recording download base URL",
"config.game.field.spine_recording.download_base_url.help": "Leave empty to use this server. A custom address must reverse proxy to /client/spine-recordings/ on this server; recording paths and access credentials are appended automatically. Public addresses must use HTTPS."
"config.game.field.spine_recording.download_base_url.help": "Leave empty to use this server. A custom address must reverse proxy to /client/spine-recordings/ on this server; recording paths and access credentials are appended automatically. Public addresses must use HTTPS.",
"console.players.local": "Local player",
"config.authentication.field.providers.key.discord.label": "Discord",
"config.authentication.field.providers.key.google.label": "Google",
"config.updates.field.countdown_minutes.help": "0 starts maintenance immediately; otherwise allow at least 5 minutes, because idle clients check the server only once every 3 minutes.",
"config.dev-tools.title": "Development overrides",
"config.dev-tools.section.format.title": "Format",
"config.dev-tools.field.version.label": "Format version",
"config.dev-tools.field.accounts.label": "Accounts",
"config.dev-tools.field.accounts.*.items.label": "Items",
"config.dev-tools.field.accounts.*.items.unlimited_stacks.label": "Unlimited item stacks",
"config.problem.message.update_interval": "The check interval must be at least 10m, for example 6h.",
"config.problem.message.update_countdown": "The countdown must be 0 (immediate maintenance) or at least 5 minutes.",
"config.problem.message.update_method": "The install method must be native, docker or none."
}
@@ -515,5 +515,18 @@
"config.game.section.spine_recording.title": "インタラクション録画",
"config.game.section.spine_recording.help": "プレイヤーのイラスト操作を保存し、ゲーム内で再生します。変更後はサーバーを再起動してください。",
"config.game.field.spine_recording.download_base_url.label": "録画ダウンロードのベース URL",
"config.game.field.spine_recording.download_base_url.help": "空欄の場合はこのサーバーを使用します。独自のアドレスは、このサーバーの /client/spine-recordings/ にリバースプロキシしてください。録画パスとアクセス資格情報は自動で追加されます。外部公開には HTTPS が必要です。"
"config.game.field.spine_recording.download_base_url.help": "空欄の場合はこのサーバーを使用します。独自のアドレスは、このサーバーの /client/spine-recordings/ にリバースプロキシしてください。録画パスとアクセス資格情報は自動で追加されます。外部公開には HTTPS が必要です。",
"console.players.local": "ローカルプレイヤー",
"config.authentication.field.providers.key.discord.label": "Discord",
"config.authentication.field.providers.key.google.label": "Google",
"config.updates.field.countdown_minutes.help": "0 は即時メンテナンスです。それ以外は最低 5 分にしてください。待機中のクライアントは 3 分ごとにサーバーを確認します。",
"config.dev-tools.title": "開発用設定の上書き",
"config.dev-tools.section.format.title": "形式",
"config.dev-tools.field.version.label": "形式バージョン",
"config.dev-tools.field.accounts.label": "アカウント",
"config.dev-tools.field.accounts.*.items.label": "アイテム",
"config.dev-tools.field.accounts.*.items.unlimited_stacks.label": "アイテムのスタック数を無制限にする",
"config.problem.message.update_interval": "確認間隔は 10m 以上にしてください(例:6h)。",
"config.problem.message.update_countdown": "カウントダウンは 0(即時メンテナンス)または 5 分以上にしてください。",
"config.problem.message.update_method": "インストール方法は native、docker、none のいずれかにしてください。"
}
@@ -515,5 +515,18 @@
"config.game.section.spine_recording.title": "상호작용 녹화",
"config.game.section.spine_recording.help": "플레이어의 일러스트 상호작용을 저장하여 게임에서 재생합니다. 설정을 변경한 후 서버를 다시 시작하세요.",
"config.game.field.spine_recording.download_base_url.label": "녹화 다운로드 기본 URL",
"config.game.field.spine_recording.download_base_url.help": "비워 두면 이 서버를 사용합니다. 사용자 지정 주소는 이 서버의 /client/spine-recordings/ 로 역방향 프록시해야 합니다. 녹화 경로와 접근 자격 정보는 자동으로 추가됩니다. 외부 공개 주소에는 HTTPS가 필요합니다."
"config.game.field.spine_recording.download_base_url.help": "비워 두면 이 서버를 사용합니다. 사용자 지정 주소는 이 서버의 /client/spine-recordings/ 로 역방향 프록시해야 합니다. 녹화 경로와 접근 자격 정보는 자동으로 추가됩니다. 외부 공개 주소에는 HTTPS가 필요합니다.",
"console.players.local": "로컬 플레이어",
"config.authentication.field.providers.key.discord.label": "Discord",
"config.authentication.field.providers.key.google.label": "Google",
"config.updates.field.countdown_minutes.help": "0이면 즉시 점검을 시작합니다. 대기 중인 클라이언트는 3분마다 서버를 확인하므로 그 외에는 최소 5분으로 설정하세요.",
"config.dev-tools.title": "개발 설정 재정의",
"config.dev-tools.section.format.title": "형식",
"config.dev-tools.field.version.label": "형식 버전",
"config.dev-tools.field.accounts.label": "계정",
"config.dev-tools.field.accounts.*.items.label": "아이템",
"config.dev-tools.field.accounts.*.items.unlimited_stacks.label": "아이템 중첩 제한 해제",
"config.problem.message.update_interval": "확인 간격은 10m 이상이어야 합니다(예: 6h).",
"config.problem.message.update_countdown": "카운트다운은 0(즉시 점검) 또는 5분 이상이어야 합니다.",
"config.problem.message.update_method": "설치 방식은 native, docker 또는 none이어야 합니다."
}
@@ -515,5 +515,18 @@
"config.game.section.spine_recording.title": "互动录制",
"config.game.section.spine_recording.help": "保存玩家的互动立绘操作记录,并供原生客户端回放。修改后重启服务端生效。",
"config.game.field.spine_recording.download_base_url.label": "录制下载基础 URL",
"config.game.field.spine_recording.download_base_url.help": "留空使用本服地址。自定义地址须反向代理到本服的 /client/spine-recordings/;系统会在其后追加录制路径和访问凭据。公网须使用 HTTPS。"
"config.game.field.spine_recording.download_base_url.help": "留空使用本服地址。自定义地址须反向代理到本服的 /client/spine-recordings/;系统会在其后追加录制路径和访问凭据。公网须使用 HTTPS。",
"console.players.local": "本地玩家",
"config.authentication.field.providers.key.discord.label": "Discord",
"config.authentication.field.providers.key.google.label": "Google",
"config.updates.field.countdown_minutes.help": "0 表示立即维护;否则至少 5 分钟,挂机玩家的客户端每 3 分钟才查询一次服务器。",
"config.dev-tools.title": "开发覆盖",
"config.dev-tools.section.format.title": "格式",
"config.dev-tools.field.version.label": "格式版本",
"config.dev-tools.field.accounts.label": "账号",
"config.dev-tools.field.accounts.*.items.label": "物品",
"config.dev-tools.field.accounts.*.items.unlimited_stacks.label": "不限物品堆叠",
"config.problem.message.update_interval": "检查间隔至少 10m,例如 6h。",
"config.problem.message.update_countdown": "倒计时为 0(立即维护)或至少 5 分钟。",
"config.problem.message.update_method": "部署方式必须是 native、docker 或 none。"
}
@@ -515,5 +515,18 @@
"config.game.section.spine_recording.title": "互動錄製",
"config.game.section.spine_recording.help": "儲存玩家的互動立繪操作記錄,供原生客戶端重播。修改後重新啟動伺服器生效。",
"config.game.field.spine_recording.download_base_url.label": "錄製下載基礎 URL",
"config.game.field.spine_recording.download_base_url.help": "留空使用本服位址。自訂位址須反向代理至本服的 /client/spine-recordings/;系統會在其後附加錄製路徑與存取憑證。公網須使用 HTTPS。"
"config.game.field.spine_recording.download_base_url.help": "留空使用本服位址。自訂位址須反向代理至本服的 /client/spine-recordings/;系統會在其後附加錄製路徑與存取憑證。公網須使用 HTTPS。",
"console.players.local": "本機玩家",
"config.authentication.field.providers.key.discord.label": "Discord",
"config.authentication.field.providers.key.google.label": "Google",
"config.updates.field.countdown_minutes.help": "0 表示立即維護;否則至少 5 分鐘,掛機玩家的用戶端每 3 分鐘才查詢一次伺服器。",
"config.dev-tools.title": "開發覆寫",
"config.dev-tools.section.format.title": "格式",
"config.dev-tools.field.version.label": "格式版本",
"config.dev-tools.field.accounts.label": "帳號",
"config.dev-tools.field.accounts.*.items.label": "物品",
"config.dev-tools.field.accounts.*.items.unlimited_stacks.label": "不限物品堆疊",
"config.problem.message.update_interval": "檢查間隔至少 10m,例如 6h。",
"config.problem.message.update_countdown": "倒數計時須為 0(立即維護)或至少 5 分鐘。",
"config.problem.message.update_method": "部署方式必須是 native、docker 或 none。"
}
@@ -0,0 +1,101 @@
//go:build integration
package app
import (
"bytes"
"context"
"testing"
"bd2server/internal/server/domain/battle"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/outbox"
)
func recordBytes(body []byte, field int) []byte {
v, _, _ := wire.Bytes(body, field)
return v
}
func recordCodeEvents(t *testing.T, g *puzzleGameplay) []outbox.Pending {
t.Helper()
tx, err := g.owner.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
pending, err := outbox.Read(tx, 128)
if err != nil {
t.Fatal(err)
}
var out []outbox.Pending
for _, event := range pending {
if event.Envelope.Event.Topic == battle.RecordCodeTopic {
out = append(out, event)
}
}
return out
}
// A 2.38.11 record code shares the owner's saved boss record with any player
// until the owner deletes it; a new save needs a new code while older codes
// keep the snapshot they shared.
func TestBattleRecordCodesShareSnapshotsAcrossAccounts(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
shared, err := openSharedRuntime(context.Background(), factory.options, factory.design)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = shared.store.Close() })
factory.shared, factory.pvpSource = shared, shared.pvp
a := newSquareGameplay(t, factory, accounts[0])
b := newSquareGameplay(t, factory, accounts[1])
stage := wire.AppendVarint(wire.AppendVarint(nil, 2, 8), 3, 10001)
char := wire.AppendVarint(nil, 1, 300)
history := wire.AppendBytes(nil, 1, wire.AppendBytes(wire.AppendVarint(nil, 1, 1), 2, char))
turn := wire.AppendBytes(wire.AppendVarint(nil, 1, 1), 2, wire.AppendVarint(nil, 1, 300))
history = wire.AppendBytes(history, 2, wire.AppendBytes(wire.AppendVarint(nil, 1, 1), 2, turn))
a.call("/BattleRecordSave", wire.AppendVarint(wire.AppendBytes(append([]byte(nil), stage...), 4, history), 5, 900))
created := a.call("/BattleRecordCodeCreate", stage)
code, _, _ := wire.Bytes(created, 1)
if len(code) == 0 || !bytes.Equal(recordBytes(a.call("/BattleRecordCodeCreate", stage), 1), code) {
t.Fatalf("record code create %x was not stable", created)
}
info := a.call("/BattleRecordInfo", stage)
if !bytes.Equal(recordBytes(info, 5), code) || len(appRows(info, 6)) != 1 || appValue(info, 100) != 0 {
t.Fatalf("own record did not list its code: %x", info)
}
lookup := wire.AppendString(append([]byte(nil), stage...), 4, string(code))
if found := b.call("/BattleRecordCodeInfo", lookup); len(recordBytes(found, 4)) != 0 {
t.Fatal("code resolved before its publication was delivered")
}
for _, event := range recordCodeEvents(t, a) {
if err = shared.Consume(context.Background(), event); err != nil {
t.Fatal(err)
}
}
found := b.call("/BattleRecordCodeInfo", lookup)
if !bytes.Equal(recordBytes(found, 3), code) || !bytes.Equal(recordBytes(found, 4), history) || appValue(found, 5) != 900 {
t.Fatalf("other player could not load the shared record: %x", found)
}
elsewhere := wire.AppendString(wire.AppendVarint(wire.AppendVarint(nil, 2, 23), 3, 97000), 4, string(code))
if len(recordBytes(b.call("/BattleRecordCodeInfo", elsewhere), 4)) != 0 {
t.Fatal("code resolved for another stage")
}
a.call("/BattleRecordSave", wire.AppendVarint(wire.AppendBytes(append([]byte(nil), stage...), 4, history), 5, 800))
if info = a.call("/BattleRecordInfo", stage); len(recordBytes(info, 5)) != 0 || len(appRows(info, 6)) != 1 {
t.Fatalf("new save kept the previous record's code: %x", info)
}
a.call("/BattleRecordCodeHistoryDelete", lookup)
if info = a.call("/BattleRecordInfo", stage); len(appRows(info, 6)) != 0 {
t.Fatal("deleted code stayed in history")
}
for _, event := range recordCodeEvents(t, a) {
if err = shared.Consume(context.Background(), event); err != nil {
t.Fatal(err)
}
}
if len(recordBytes(b.call("/BattleRecordCodeInfo", lookup), 4)) != 0 {
t.Fatal("deleted code still resolves")
}
}
@@ -70,13 +70,15 @@ func TestCafeteriaLoginRestoresAMissingDatingTicketOnce(t *testing.T) {
if got := g.itemCount(25, 26); got != 0 {
t.Fatalf("login restoration regranted the introduction box: decoration %d", got)
}
// Spend the restored ticket: the restoration identity must not grant again.
// A permanent credential is restored with the original instance, not a new grant.
var restoredIndex uint64
s = &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
items, err := p.ownedItems.SelectMutable(ctx, 19, ticket, 1)
if err != nil {
t.Fatal(err)
}
restoredIndex = items[0].InvenIndex
if err := p.ownedItems.Consume(ctx, items); err != nil {
t.Fatal(err)
}
@@ -84,9 +86,17 @@ func TestCafeteriaLoginRestoresAMissingDatingTicketOnce(t *testing.T) {
g.reopen()
g.call("/LoginUser", nil)
g.call("/CafeteriaIntroductionStoryReward", nil)
if got, deco := g.itemCount(19, ticket), g.itemCount(25, 26); got != 0 || deco != 0 {
t.Fatalf("restoration repeated or regranted the box: ticket %d decoration %d", got, deco)
if got, deco := g.itemCount(19, ticket), g.itemCount(25, 26); got != 1 || deco != 0 {
t.Fatalf("permanent ticket was lost or introduction box repeated: ticket %d decoration %d", got, deco)
}
s = &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
for _, item := range p.ownedItems.All(ctx) {
if item.Type == 19 && item.ID == ticket && item.InvenIndex != restoredIndex {
t.Fatal("permanent credential restoration changed its inventory instance")
}
}
})
}
// MissionTable 301/3012 is guide STEP McPackQuestIdClear for pack1 quest3
@@ -15,7 +15,8 @@ import (
// Current official PackageUI148.prefab uses BundleGroupPackageUI, whose
// per-product buttons only check availability and that product's own limit.
// Its contentsGroup91 sort3 product236 can be bought before sort2 product235.
// PackageUI132 uses BundleGroupRelayPackageUI and does enforce stage order.
// BundleGroupRelayPackageUI does enforce stage order; 2.38.11 GameData sells no
// relay package, so the same contents group is laid out as one to check it.
func TestIndependentCashPackageCanBeBoughtBeforeEarlierDisplayItems(t *testing.T) {
g := profileGameplay(t)
profileGrant(g, gamedata.Reward{Type: 2, Count: 1000000})
@@ -53,17 +54,23 @@ func TestIndependentCashPackageCanBeBoughtBeforeEarlierDisplayItems(t *testing.T
assertPurchase()
g.reopen()
assertPurchase()
// A real relay's later stage remains unavailable; no quote or debit is
// A relay's later stage remains unavailable; no quote or debit is
// attempted until its predecessor is owned.
relayed := append([]gamedata.CashPackageDesign(nil), g.factory.design.cashDesign.Packages...)
var relay gamedata.CashPackageDesign
for _, pack := range g.factory.design.cashDesign.Packages {
if pack.ResourceName == "PackageUI132" && pack.ContentsSortID == 2 {
relay = pack
break
for i := range relayed {
if relayed[i].ResourceName == "PackageUI148" {
relayed[i].Sequential = true
if relayed[i].ContentsSortID == 2 {
relay = relayed[i]
}
}
}
if relay.ID == 0 {
t.Fatal("official relay fixture absent")
t.Fatal("contents group 91 sort 2 absent")
}
if err := g.owner.assembly.cashService.AttachPackageRules(relayed); err != nil {
t.Fatal(err)
}
relayLine := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, relay.ID), 2, relay.SaleGroup), 3, 1)
failure := g.execute(g.request("/CashShopBuy", wire.AppendBytes(wire.AppendVarint(nil, 3, relay.GroupID), 4, relayLine)), true)
+1 -1
View File
@@ -36,7 +36,7 @@ func openConsole(c *configuration, design *designCatalog, seeds *seedCatalog, au
if err != nil {
return nil, err
}
return []admin.Player{{AccountID: "local-owner", UID: strconv.FormatUint(owner, 10), Name: "本地玩家", Active: true}}, nil
return []admin.Player{{AccountID: "local-owner", UID: strconv.FormatUint(owner, 10), NameKey: "console.players.local", Active: true}}, nil
}
profiles, err := authStore.Players(ctx)
if err != nil {
@@ -0,0 +1,106 @@
//go:build integration
package app
import (
"bytes"
"encoding/json"
"fmt"
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
)
func TestContentOpenKeepsNativePrerequisitesReplayAndCompletionIntegrity(t *testing.T) {
g := profileGameplay(t)
rules := g.owner.assembly.design.contentOpeningDesign
request := appScalar(2, 1)
g.execute(g.request("/ContentOpen", request), true)
if g.itemCount(19, rules.Completion.TicketID) != 0 {
t.Fatal("missing prerequisite still issued the completion credential")
}
profileGrant(g, gamedata.Reward{Type: 19, ID: rules.Prerequisite.TicketID, Count: 1})
claim := g.request("/ContentOpen", request)
response := g.execute(claim, false)
var returned uint64
for _, bundle := range appRows(response, 1) {
for _, item := range appRows(bundle, 1) {
if appValue(item, 3) == 19 && appValue(item, 2) == rules.Completion.TicketID {
returned += appValue(item, 4)
}
}
}
if returned != 1 || g.itemCount(19, rules.Completion.TicketID) != 1 {
t.Fatal("native ContentOpen response did not deliver exactly one completion credential")
}
g.reopen()
if replay := g.execute(claim, false); !bytes.Equal(replay, response) || g.itemCount(19, rules.Completion.TicketID) != 1 {
t.Fatal("ContentOpen retry changed its receipt or duplicated the ticket")
}
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
items, err := p.ownedItems.SelectMutable(ctx, 19, rules.Completion.TicketID, 1)
if err != nil {
t.Fatal(err)
}
if err := p.ownedItems.Consume(ctx, items); err != nil {
t.Fatal(err)
}
if _, err := p.ownedItems.GrantOnce(ctx, "invalid-completion-fixture", []gamedata.BattleReward{{Type: 19, ID: rules.Completion.TicketID, Count: 2}}); err != nil {
t.Fatal(err)
}
})
g.execute(g.request("/ContentOpen", request), true)
if g.itemCount(19, rules.Completion.TicketID) != 2 {
t.Fatal("invalid completion credential was rewritten during rejection")
}
}
func TestContentOpenCredentialAndReceiptRollBackWithAccountBatch(t *testing.T) {
g := profileGameplay(t)
rules := g.owner.assembly.design.contentOpeningDesign
profileGrant(g, gamedata.Reward{Type: 19, ID: rules.Prerequisite.TicketID, Count: 1})
claim := g.request("/ContentOpen", appScalar(2, 1))
invalid := g.request("/ItemDump", appMessage(2, inventoryItem(999999999, 1, 8, 1)))
batch := claim
batch.Requests = append(batch.Requests, invalid.Requests...)
if failed := g.execute(batch, true); !bytes.Contains(failed, []byte("/ItemDump")) {
t.Fatalf("batch did not reach the failing operation after ContentOpen: %s", failed)
}
g.reopen()
if g.itemCount(19, rules.Completion.TicketID) != 0 {
t.Fatal("failed account batch retained its completion credential")
}
s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
identity := fmt.Sprintf("content-ticket:%d", rules.Completion.TicketID)
if p.ownedItems.WasGranted(identity) {
t.Fatal("failed batch retained an in-memory credential grant marker after reopen")
}
for _, bucket := range []string{"granted", "grant_items", "grant_rewards"} {
if _, found, err := ctx.State.LoadEntry("items", bucket, identity); err != nil || found {
t.Fatalf("failed batch retained credential %s entry: found=%t err=%v", bucket, found, err)
}
}
raw, err := p.gameplayStore.Load(ctx.State, "content_open")
if err != nil {
t.Fatal(err)
}
if raw != nil {
var state struct {
Receipts map[string]json.RawMessage `json:"receipts"`
}
if err := json.Unmarshal(raw, &state); err != nil || len(state.Receipts) != 0 {
t.Fatalf("failed batch retained a ContentOpen receipt: %s %v", raw, err)
}
}
})
response := g.execute(claim, false)
if g.itemCount(19, rules.Completion.TicketID) != 1 {
t.Fatal("original request did not issue one credential after rollback")
}
g.reopen()
if replay := g.execute(claim, false); !bytes.Equal(replay, response) || g.itemCount(19, rules.Completion.TicketID) != 1 {
t.Fatal("successful retry lost its receipt or duplicated the credential")
}
}
@@ -0,0 +1,83 @@
//go:build integration
package app
import (
"bytes"
"encoding/json"
"testing"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/fishing"
)
func TestFishingShopSaleDoesNotReaddSoldFishToNativeInventory(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
g := newSquareGameplay(t, factory, accounts[0])
g.call("/FishingItemInfo", nil)
var sold, retained uint64
inventorySetup(t, g, func(ctx command.Context, _ *playerAssembly) {
raw, found, err := ctx.State.LoadEntry("fishing", "state", "core")
if err != nil || !found {
t.Fatal("missing fishing inventory", err)
}
var saved map[string]json.RawMessage
if err := json.Unmarshal(raw, &saved); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(saved["Next"], &sold); err != nil {
t.Fatal(err)
}
retained = sold + 1
items := []fishing.Item{
{Index: sold, ID: 1, Count: 1, Size: 250},
{Index: retained, ID: 1, Count: 1, Size: 750, Locked: true},
}
saved["Fish"], err = json.Marshal(items)
if err != nil {
t.Fatal(err)
}
saved["Next"], err = json.Marshal(retained + 1)
if err != nil {
t.Fatal(err)
}
raw, err = json.Marshal(saved)
if err != nil {
t.Fatal(err)
}
if err := ctx.State.PutEntry("fishing", "state", "core", raw); err != nil {
t.Fatal(err)
}
})
g.reopen()
before := squareBalance(t, g, 54, 0)
saleItem := appScalar(1, sold)
saleItem = append(saleItem, appScalar(2, 1)...)
saleItem = append(saleItem, appScalar(3, 1)...)
saleItem = append(saleItem, appScalar(4, 1)...)
sale := g.request("/FishingShopSell", appMessage(2, saleItem))
body := g.execute(sale, false)
bundles := appRows(body, 1)
if len(bundles) != 1 {
t.Fatalf("sale reward bundles=%d, want 1", len(bundles))
}
// The native sale callback removes requested indices, then adds FishInfo as rewards.
if fish := appRows(bundles[0], 11); len(fish) != 0 {
t.Fatalf("sale re-added %d fish through RewardInfoBundle.FishInfo", len(fish))
}
// Current FishingSellItemTable 1/1 pays 30 coins; size 250 has a 2x premium.
if got := squareBalance(t, g, 54, 0); got != before+60 {
t.Fatalf("fishing coins=%d, want %d", got, before+60)
}
g.reopen()
if replay := g.execute(sale, false); !bytes.Equal(replay, body) {
t.Fatal("reopened sale replay changed")
}
if got := squareBalance(t, g, 54, 0); got != before+60 {
t.Fatalf("sale replay credited coins again: %d", got)
}
fish := appRows(g.call("/FishingItemInfo", nil), 1)
if len(fish) != 1 || appValue(fish[0], 1) != retained {
t.Fatalf("sale did not preserve exactly the unsold locked fish: %x", fish)
}
}
@@ -10,6 +10,7 @@ import (
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
)
// LocalText38037 sells every pending fish when auto-sale is selected. The
@@ -152,3 +153,120 @@ func TestFishingChargeScheduleIsIncludedBeforeOpeningHarbor(t *testing.T) {
g.call("/FishingItemInfo", nil)
g.call("/FishingInfo", nil)
}
// FishingDefaultTable supplies the unlock level and ticket; ContentOpenTable
// 20/1 checks that ticket independently of TrapRewardReceiptTime.
func TestFishingBoatUpgradeDeliversTrapUnlockAtDesignLevel(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
g := newSquareGameplay(t, factory, accounts[0])
d, err := factory.design.eventPlay.Row("FishingDefaultTable", 25, 0)
if err != nil {
t.Fatal(err)
}
level, _, err := wire.Varint(d, 20)
if err != nil {
t.Fatal(err)
}
ticket, _, err := wire.Varint(d, 21)
if err != nil {
t.Fatal(err)
}
if level <= 1 || ticket == 0 {
t.Fatal("missing boat trap unlock design")
}
g.call("/LoginUser", nil)
if g.itemCount(19, ticket) != 0 {
t.Fatal("starter boat unlocked the trap")
}
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
if _, err := p.eventEconomy.Apply(ctx, "trap-unlock-budget", nil, []gamedata.Reward{{Type: 54, Count: 1000000}}); err != nil {
t.Fatal(err)
}
})
var last []byte
for g.owner.assembly.fishingService.Profile().BoatLevel < level {
if g.itemCount(19, ticket) != 0 {
t.Fatalf("boat level %d unlocked the trap before required level %d", g.owner.assembly.fishingService.Profile().BoatLevel, level)
}
last = g.call("/FishingBoatUpgrade", nil)
if current := g.owner.assembly.fishingService.Profile().BoatLevel; current < level && (g.itemCount(19, ticket) != 0 || appValue(last, 2) != 0) {
t.Fatalf("upgrade to boat level %d activated the trap before required level %d", current, level)
}
}
if appValue(last, 2) == 0 || g.itemCount(19, ticket) != 1 {
t.Fatal("unlocked boat did not activate the trap and permanent ticket")
}
var delivered uint64
for _, bundle := range appRows(last, 3) {
for _, item := range appRows(bundle, 1) {
if appValue(item, 3) == 19 && appValue(item, 2) == ticket {
delivered += appValue(item, 4)
}
}
}
if delivered != 1 {
t.Fatalf("native upgrade reward delivered %d trap tickets, want 1", delivered)
}
g.reopen()
g.call("/LoginUser", nil)
g.call("/FishingBoatUpgrade", nil)
g.call("/LoginUser", nil)
if g.itemCount(19, ticket) != 1 {
t.Fatal("upgrade or login duplicated the permanent unlock ticket")
}
}
func TestFishingLoginReconcilesEligibleBoatWithoutTrapTicket(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
g := newSquareGameplay(t, factory, accounts[0])
d, err := factory.design.eventPlay.Row("FishingDefaultTable", 25, 0)
if err != nil {
t.Fatal(err)
}
ticket, _, err := wire.Varint(d, 21)
if err != nil {
t.Fatal(err)
}
if ticket == 0 {
t.Fatal("missing trap ticket design")
}
g.call("/FishingInfo", nil)
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
raw, found, err := ctx.State.LoadEntry("fishing", "state", "core")
if err != nil || !found {
t.Fatal("missing fishing core", err)
}
var saved map[string]json.RawMessage
if err := json.Unmarshal(raw, &saved); err != nil {
t.Fatal(err)
}
var maxLevel uint64
for _, boat := range p.design.eventPlay.Tables["FishingBoatTable"] {
maxLevel = max(maxLevel, appValue(boat, 8))
}
saved["Boat"], err = json.Marshal(maxLevel)
if err != nil {
t.Fatal(err)
}
raw, err = json.Marshal(saved)
if err != nil {
t.Fatal(err)
}
if err := ctx.State.PutEntry("fishing", "state", "core", raw); err != nil {
t.Fatal(err)
}
})
g.reopen()
if g.itemCount(19, ticket) != 0 {
t.Fatal("test account already owns trap ticket")
}
g.call("/LoginUser", nil)
if g.itemCount(19, ticket) != 1 || appValue(g.call("/FishingTrapInfo", nil), 1) == 0 {
t.Fatal("login did not restore the eligible boat's native trap access")
}
g.reopen()
g.call("/LoginUser", nil)
if g.itemCount(19, ticket) != 1 {
t.Fatal("repeated login duplicated the restored trap ticket")
}
}
@@ -4,11 +4,101 @@ package app
import (
"encoding/json"
"strconv"
"strings"
"testing"
"bd2server/internal/server/domain/command"
)
// GameData 20261021182514: day-one group301 has eight ordinary tasks and
// aggregate3018 (condition1001, day1, target8, Params[0]); LocalText5501104
// says to complete all day-one missions. Emulate an old account with seven
// received rewards and one completed-but-unclaimed task, then use native APIs.
func TestGuidePassDailyAggregateBackfillsClaimsAndPaysOnce(t *testing.T) {
g := newMissionGameplay(t)
g.call("/EventMissionInfo", nil)
s := &trapPlayerScenario{factory: g.factory, owner: g.owner, account: g.account}
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
raw, err := p.gameplayStore.Load(ctx.State, "eventtasks")
if err != nil {
t.Fatal(err)
}
var state map[string]json.RawMessage
if err := json.Unmarshal(raw, &state); err != nil {
t.Fatal(err)
}
var progress map[string]struct {
Value uint64
Claimed bool
Period string
}
if err := json.Unmarshal(state["Missions"], &progress); err != nil {
t.Fatal(err)
}
for key, value := range progress {
for _, task := range g.factory.design.eventTasksDesign.Missions {
if task.Group != 301 || !strings.HasSuffix(key, "/"+strconv.FormatUint(task.ID, 10)) {
continue
}
value.Value = task.Target
value.Claimed = task.ID != 3018 && task.ID != 3019
if task.ID == 3018 {
value.Value = 0
}
progress[key] = value
}
}
state["Missions"], err = json.Marshal(progress)
if err != nil {
t.Fatal(err)
}
raw, err = json.Marshal(state)
if err != nil {
t.Fatal(err)
}
if err := p.gameplayStore.Save(ctx.State, "eventtasks", raw); err != nil {
t.Fatal(err)
}
})
g.reopen()
assertAggregate := func(want uint64, claimed bool) {
t.Helper()
for _, row := range appRows(g.call("/EventMissionInfo", nil), 1) {
if appValue(row, 1) == 7001 && appValue(row, 3) == 3018 {
if appValue(row, 4) != want || (appValue(row, 5) == 1) != claimed {
t.Fatalf("guide aggregate value=%d claimed=%v, want %d/%v", appValue(row, 4), appValue(row, 5) == 1, want, claimed)
}
return
}
}
t.Fatal("guide aggregate missing")
}
claim := func(task uint64) []byte {
body := append(appScalar(3, 2), appScalar(4, 301)...)
body = append(body, appScalar(5, task)...)
return append(body, appScalar(6, 7001)...)
}
assertAggregate(7, false)
if _, err := g.execute("/MissionClear", claim(3018)); err == nil {
t.Fatal("unclaimed eighth task counted as an aggregate receipt")
}
g.call("/MissionClear", claim(3019))
assertAggregate(8, false)
before := g.itemCount(8, 14)
g.reopen()
assertAggregate(8, false)
g.call("/MissionClear", claim(3018))
if g.itemCount(8, 14) != before+4 {
t.Fatal("completed aggregate did not grant its four materials")
}
g.reopen()
assertAggregate(8, true)
if _, err := g.execute("/MissionClear", claim(3018)); err == nil || g.itemCount(8, 14) != before+4 {
t.Fatal("aggregate reward paid twice after reopen")
}
}
// PassInfo.GetPassTableList includes schedule-free newbie passes. Current
// GameData pass76/step1 starts at level1 with box510031, which opens costume3303;
// level2 requires65 EXP. Homescreen mission3038 contributes10 EXP when claimed.
@@ -97,25 +97,29 @@ func TestUnlimitedItemStacksMergeAndSplitBackForTheirAccountOnly(t *testing.T) {
// refreshed runs one ordinary request and reports whether its reply asks
// the LocalIdentity plugin to reload the inventory.
refreshed := func(g *puzzleGameplay) bool {
refreshed := func(g *puzzleGameplay, policy uint64) bool {
t.Helper()
reply, err := g.owner.Execute(context.Background(), g.request("/ItemInfo", nil))
if err != nil || len(reply.Responses) != 1 {
t.Fatalf("/ItemInfo: responses=%d error=%v", len(reply.Responses), err)
}
actual, present, err := wire.Varint(reply.Responses[0].Notification, ItemStackPolicyNotifyField)
if err != nil || !present || actual != policy {
t.Fatalf("account %s stack policy=%d present=%t err=%v, want %d", g.account, actual, present, err, policy)
}
flag, present, err := wire.Varint(reply.Responses[0].Notification, ItemStackRefreshNotifyField)
return err == nil && present && flag == itemStackRefreshItems
}
// Switching on merges them into one stack on the very next request, without a new login.
writeSettings(true)
if !refreshed(a) {
if !refreshed(a, 2) {
t.Fatal("enabling did not ask the client to reload its inventory")
}
if total, _, count := stacks(a); total != scattered || count != 1 {
t.Fatalf("enabled A: total=%d stacks=%d, want %d in one stack", total, count, scattered)
}
if refreshed(a) || refreshed(b) {
if refreshed(a, 2) || refreshed(b, 1) {
t.Fatal("an unchanged inventory asked for another reload")
}
grant(a, "stack-a", limit)
@@ -135,7 +139,7 @@ func TestUnlimitedItemStacksMergeAndSplitBackForTheirAccountOnly(t *testing.T) {
// Switching off splits the stack back to the limit on the next request;
// nothing is lost while slots remain.
writeSettings(false)
if !refreshed(a) {
if !refreshed(a, 1) {
t.Fatal("disabling did not ask the client to reload its inventory")
}
total, largest, count := stacks(a)
@@ -0,0 +1,61 @@
//go:build integration
package app
import (
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/notice"
"bd2server/internal/server/protocol/wire"
)
// The session's LoggedIn callback runs after player execution. Rollover during
// LoginUser must therefore use the incoming language before that callback.
func TestMissionCompensationUsesIncomingLoginLanguage(t *testing.T) {
g := newMissionGameplay(t)
g.factory.options.notices = notice.NewBoard(nil)
g.call("/LoginUser", appScalar(7, 2))
var mission gamedata.MissionKey
found := false
for key, rewards := range g.owner.assembly.design.missionDesign.Missions {
if key.GroupType != 0 || len(rewards) == 0 {
continue
}
if _, limited := g.owner.assembly.design.missionDesign.Windows[[2]uint64{key.GroupID, key.ID}]; limited {
continue
}
goldOnly := true
for _, reward := range rewards {
goldOnly = goldOnly && reward.Type == 4
}
if goldOnly {
mission, found = key, true
break
}
}
if !found {
t.Fatal("current GameData has no permanent daily gold mission fixture")
}
g.completeFixtures([]gamedata.MissionKey{mission})
g.now = g.now.AddDate(0, 0, 1)
g.factory.options.notices.SetLanguage(g.account, "ko_kr")
g.call("/LoginUser", appScalar(7, 3))
want := "デイリーミッション未受取報酬の配布"
assertTitle := func() {
t.Helper()
for _, row := range appRows(g.call("/MailInfo", nil), 1) {
title, _, err := wire.Bytes(row, 5)
if err != nil {
t.Fatal(err)
}
if string(title) == want {
return
}
}
t.Fatal("login rollover did not issue compensation in the incoming Japanese language")
}
assertTitle()
g.reopen()
assertTitle()
}
+3
View File
@@ -117,6 +117,9 @@ func (p *playerAssembly) assets(ctx command.Context) error {
if err != nil {
return fmt.Errorf("load mission state: %w", err)
}
if p.options.notices != nil {
p.missionService.SetLanguage(p.options.notices.Language(ctx.AccountID))
}
if err := p.missionService.AttachWallet(ctx, p.wallet); err != nil {
return fmt.Errorf("attach mission wallet: %w", err)
}
+1
View File
@@ -16,6 +16,7 @@ func (p *playerAssembly) avatar(ctx command.Context) error {
if err != nil {
return fmt.Errorf("open avatar profile: %w", err)
}
p.avatarService.AttachContentTickets(p.contentCredentials)
return p.login.AttachAvatarSelection(p.avatarService)
}
func (p *playerAssembly) AvatarItems(ctx command.Context) []assets.Item { return p.ownedItems.All(ctx) }
+4
View File
@@ -65,6 +65,7 @@ func (p *playerAssembly) events(ctx command.Context) error {
return fmt.Errorf("load fishing state: %w", err)
}
p.fishingService.AttachProgress(p.recordMission)
p.fishingService.AttachContentTickets(p.contentCredentials)
if err := p.login.AttachFishing(func() loginprotocol.FishingState {
state := p.fishingService.Profile()
return loginprotocol.FishingState{AP: state.MultiAP, FishSlots: state.FishSlots, RodSlots: state.RodSlots, ItemSlots: state.ItemSlots}
@@ -82,6 +83,9 @@ func (p *playerAssembly) events(ctx command.Context) error {
return fmt.Errorf("attach event field packs: %w", err)
}
p.battleService.AttachEventBattle(p.eventPlayService)
if p.shared != nil {
p.battleService.AttachRecordCodes(p.shared.recordCode)
}
p.eventActionsService, err = eventactions.Open(ctx, p.gameplayStore, p.design.eventActionsDesign, p.eventRegistry, p.eventEconomy)
if err != nil {
return fmt.Errorf("load event action state: %w", err)
+22 -2
View File
@@ -1,6 +1,7 @@
package app
import (
"bd2server/internal/common/i18n"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/protocol/wire"
@@ -189,9 +190,16 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
}
for index, item := range request.Requests {
var response player.Response
stage := "dispatch"
if isLogin {
stage = "login"
started := time.Now()
err = assembly.beginLogin(identity)
language, _, languageErr := wire.Varint(item.Body, 7)
err = languageErr
if err == nil {
assembly.missionService.SetLanguage(i18n.FromGameLanguage(language))
err = assembly.beginLogin(identity)
}
if err == nil {
response.Body, err = assembly.login.Login(identity, item.Body, request.LoginSessionKey)
response.PacketCode = 3
@@ -203,6 +211,7 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
assembly.achievementObserver.BeginLogin(identity)
}
for _, observer := range assembly.observers {
stage = "before_dispatch"
if err = observer.BeforeDispatch(identity, item.Path, item.Body); err != nil {
break
}
@@ -210,6 +219,7 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
reply.Timing.Observer += time.Since(started)
if err == nil {
started = time.Now()
stage = "dispatch"
if friendResponse, found := friendResponses[index]; found {
response = friendResponse
} else if plan := socialPlans[index]; plan != nil {
@@ -227,6 +237,7 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
if err == nil {
started = time.Now()
for _, observer := range assembly.observers {
stage = "after_dispatch"
var notify []byte
notify, err = observer.AfterDispatch(identity, item.Path, item.Body, response.Body)
@@ -240,7 +251,7 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
}
if err != nil {
sequence, _, _ := wire.Varint(item.Body, 1)
return reply, failCommand(&command.RequestError{Path: item.Path, Sequence: sequence, Cause: err})
return reply, failCommand(&command.RequestError{Path: item.Path, Sequence: sequence, Stage: stage, Cause: err})
}
reply.Responses = append(reply.Responses, response)
@@ -357,6 +368,15 @@ func (p *playerAssembly) beginLogin(ctx command.Context) error {
if err := p.cafeteriaService.ReconcileIntroduction(ctx); err != nil {
return err
}
if err := p.fishingService.ReconcileTrapUnlock(ctx); err != nil {
return err
}
if _, err := p.avatarService.ReconcileUnlockTickets(ctx); err != nil {
return err
}
if err := p.worldService.ReconcileContentTickets(ctx); err != nil {
return err
}
if err := p.worldService.ClaimOpenFieldPacks(ctx); err != nil {
return err
}
+1
View File
@@ -115,6 +115,7 @@ type playerAssembly struct {
battleService *battle.Service
gameplayStore stateio.EntrySnapshotStore
contentOpenService *assets.ContentOpenService
contentCredentials *assets.ContentTickets
huntingService *hunting.Service
eventRegistry *events.Registry
eventEconomy *events.Economy
@@ -47,6 +47,11 @@ func (p *playerAssembly) gameplay(ctx command.Context) error {
if err := p.worldService.AttachFieldBuffRuntime(p.design.fieldBuffs); err != nil {
return fmt.Errorf("attach field monster damage: %w", err)
}
p.contentCredentials, err = assets.NewContentTickets(p.ownedItems, p.design.contentOpeningDesign.TicketTypes)
if err != nil {
return err
}
p.worldService.AttachContentTickets(p.contentCredentials)
p.contentOpenService, err = assets.NewContentOpenService(ctx, p.design.contentOpeningDesign, p.ownedItems, p.gameplayStore, func() (uint64, error) {
experience, err := p.missionService.AchievementExperience()
if err != nil {
+17 -5
View File
@@ -9,6 +9,9 @@ import (
// LocalIdentity plugin reloads the inventories its value names.
const ItemStackRefreshNotifyField = 1000
// ItemStackPolicyNotifyField carries 1 for design limits and 2 for unlimited stacks.
const ItemStackPolicyNotifyField = 1001
// Bits of ItemStackRefreshNotifyField.
const (
itemStackRefreshItems = 1 << 0 // ordinary inventory and item storage
@@ -21,9 +24,18 @@ const (
type itemStackObserver struct {
player *playerAssembly
changed uint64
policy uint64
}
func (o *itemStackObserver) BeforeDispatch(ctx command.Context, path string, _ []byte) error {
unlimited, err := o.player.unlimitedStacks(ctx)
if err != nil {
return err
}
o.policy = 1
if unlimited {
o.policy = 2
}
changed, err := o.player.normalizeItemStacks(ctx)
// The login reply is followed by the client's own full inventory requests.
if path != "/LoginUser" {
@@ -33,12 +45,12 @@ func (o *itemStackObserver) BeforeDispatch(ctx command.Context, path string, _ [
}
func (o *itemStackObserver) AfterDispatch(command.Context, string, []byte, []byte) ([]byte, error) {
if o.changed == 0 {
return nil, nil
notify := wire.AppendVarint(nil, ItemStackPolicyNotifyField, o.policy)
if o.changed != 0 {
notify = wire.AppendVarint(notify, ItemStackRefreshNotifyField, o.changed)
o.changed = 0
}
changed := o.changed
o.changed = 0
return wire.AppendVarint(nil, ItemStackRefreshNotifyField, changed), nil
return notify, nil
}
// normalizeItemStacks reshapes inventory and life item stacks to the account's
@@ -43,14 +43,7 @@ func (p *playerAssembly) optionalGameplay(ctx command.Context) error {
}
p.datingService.SetResetSeconds(p.design.eventAPReset.ResetSeconds)
p.cafeteriaService.SetResetSeconds(p.design.eventAPReset.ResetSeconds)
p.cafeteriaService.AttachDatingTicket(p.design.contentOpeningDesign.Dating.TicketID, func(ctx command.Context, ticket uint64) bool {
for _, item := range p.ownedItems.All(ctx) {
if item.Type == 19 && item.ID == ticket && item.Count > 0 {
return true
}
}
return false
})
p.cafeteriaService.AttachDatingTicket(p.design.contentOpeningDesign.Dating.TicketID, p.contentCredentials)
p.cafeteriaService.AttachOwnedCostumes(func() []uint64 {
var ids []uint64
for _, costume := range p.collection.Costumes() {
@@ -191,7 +191,7 @@ func TestNewPlayerCanPersistGameDataDefaultPortraitWithoutOwningCostume(t *testi
if profileVarint(t, login, 14) != 0 {
t.Fatal("fresh player must start without a selected portrait")
}
// UserDBInfo.SetPortraitCostumeId sends GameDefaultTable field29 when the login portrait is zero.
// UserDBInfo.SetPortraitCostumeId sends GameDefaultTable defaultCostumeId when the login portrait is zero.
defaultPortrait := g.factory.design.profileDesign.DefaultPortraitCostumeID
if defaultPortrait == 0 {
t.Fatal("GameData default portrait is missing")
+2 -4
View File
@@ -78,7 +78,7 @@ func Serve(args []string) (serveErr error) {
if err := lockServerState(c.stateDirectory, c.gameRules.Story.StartPackID); err != nil {
return err
}
c.gameFile.Lock(commonconfig.Lock{Path: "story.start_pack_id", Value: c.gameRules.Story.StartPackID, Reason: "首次初始化后已永久保存于服务器状态,不能再更改"})
c.gameFile.Lock(commonconfig.Lock{Path: "story.start_pack_id", Value: c.gameRules.Story.StartPackID, Reason: "config.game.lock.story.start_pack_id"})
shared, err := openSharedRuntime(context.Background(), c, design)
if err != nil {
return err
@@ -179,13 +179,11 @@ func Serve(args []string) (serveErr error) {
ClientAllowed: compatibility.allowed,
UpdateFingerprint: func() []byte { return compatibility.envelope },
Compatibility: func() any {
minimum := c.versions.MinimumPlugins.ByID()
delete(minimum, "capture_environment")
return map[string]any{
"server_version": c.versions.ServerVersion, "game_version": c.versions.GameVersion,
"bundle_version": c.versions.BundleVersion, "game_data_version": c.versions.GameDataVersion,
"fingerprint": compatibility.summary(), "fingerprint_url": "/client/update-fingerprint",
"minimum_plugins": minimum, "maintenance_at": updater.MaintenanceStart(), "logins_closed": loginsClosed(0) != "",
"minimum_plugins": c.versions.MinimumPlugins.ByID(), "maintenance_at": updater.MaintenanceStart(), "logins_closed": loginsClosed(0) != "",
}
},
}.Handler()
@@ -734,11 +734,26 @@ func TestNativePVPGameplayUsesOwnedSnapshotsAndTickets(t *testing.T) {
t.Fatal("arena free tickets do not match current season charge rule")
}
match := attacker.pvpCall("/ColosseumBattleMatching", nil)
enemies := appRows(match, 3)
if len(enemies) == 0 || appValue(enemies[0], 1) != uint64(opponent.OwnerIndex) {
t.Fatal("arena did not match published opponent")
matchType, err := factory.design.pvp.Design.ColosseumRule(season, 3)
if err != nil || len(matchType) != 1 {
t.Fatalf("arena matching rule: %v", err)
}
var selected []byte
if matchType[0] == 0 {
if len(appRows(match, 3)) != 0 {
t.Fatal("direct matching leaked opponent information before battle start")
}
} else {
enemies := appRows(match, 3)
if len(enemies) == 0 || appValue(enemies[0], 1) != uint64(opponent.OwnerIndex) {
t.Fatal("arena did not match published opponent")
}
selected = appScalar(2, uint64(opponent.OwnerIndex))
}
start := attacker.pvpCall("/ColosseumBattleStart", selected)
if enemy := appRows(start, 3); len(enemy) != 1 || appValue(enemy[0], 1) != uint64(opponent.OwnerIndex) {
t.Fatal("arena start did not reveal the matched defender")
}
attacker.pvpCall("/ColosseumBattleStart", appScalar(2, uint64(opponent.OwnerIndex)))
attacker.pvpCall("/ColosseumBattleEnd", appScalar(2, 1))
attacker.drainPVP()
history = attacker.pvpCall("/ColosseumBattleHistory", nil)
@@ -825,8 +840,11 @@ func TestColosseumNoOpponentReturnsNativeErrorWithoutSpendingTicket(t *testing.T
defender.send("/ColosseumDeckSave", appMessage(2, decks[1]), 476, 0)
drainFriendPublications(t, registry, state, accounts[1])
matched := attacker.send("/ColosseumBattleMatching", nil, 483, 0)
enemies := appRows(matched, 3)
if len(enemies) != 1 || appValue(enemies[0], 1) != defender.owner {
if len(appRows(matched, 3)) != 0 {
t.Fatal("direct matching leaked opponent information")
}
start := attacker.send("/ColosseumBattleStart", nil, 484, 0)
if enemies := appRows(start, 3); len(enemies) != 1 || appValue(enemies[0], 1) != defender.owner {
t.Fatal("matching did not recover when a real opponent published a team")
}
attacker = friendHTTPLogin(t, registry, accounts[0])
@@ -0,0 +1,74 @@
package app
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"bd2server/internal/server/domain/battle"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/storage/outbox"
"bd2server/internal/server/storage/shared"
)
// sharedRecordCode is a published battle record code and its owner account.
type sharedRecordCode struct {
Source string
Record battle.RecordCodePublication
}
func (s *sharedRuntime) consumeRecordCode(ctx context.Context, event outbox.Pending) error {
var update battle.RecordCodePublication
if json.Unmarshal(event.Envelope.Event.Payload, &update) != nil || update.Code == "" || len(update.Code) > 15 || !update.Revoke && len(update.Record) == 0 {
return fmt.Errorf("invalid battle record code publication")
}
return s.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
raw, found, err := tx.Get("battle_record_codes", update.Code)
if err != nil {
return err
}
if found {
var current sharedRecordCode
if json.Unmarshal(raw, &current) != nil {
return fmt.Errorf("invalid shared battle record code")
}
if current.Source != envelope.Source {
// Random codes collide with negligible probability; the
// first owner keeps the code.
slog.Warn("battle record code already owned", "code", update.Code, "account_id", envelope.Source)
return nil
}
}
if update.Revoke {
_, err = tx.Delete("battle_record_codes", update.Code)
return err
}
raw, err = json.Marshal(sharedRecordCode{Source: envelope.Source, Record: update})
if err != nil {
return err
}
return tx.Put("battle_record_codes", update.Code, raw)
})
}
func (s *sharedRuntime) recordCode(ctx command.Context, code string) (battle.RecordCodePublication, bool, error) {
cancel := ctx.Cancellation
if cancel == nil {
cancel = context.Background()
}
var out sharedRecordCode
var found bool
err := s.store.View(cancel, func(tx *shared.Tx) error {
raw, ok, err := tx.Get("battle_record_codes", code)
if err != nil || !ok {
return err
}
if json.Unmarshal(raw, &out) != nil {
return fmt.Errorf("invalid shared battle record code")
}
found = true
return nil
})
return out.Record, found, err
}
+4
View File
@@ -12,6 +12,7 @@ import (
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/battle"
"bd2server/internal/server/domain/battle/pvp"
"bd2server/internal/server/domain/ranking"
"bd2server/internal/server/domain/social"
@@ -118,6 +119,9 @@ func (s *sharedRuntime) Consume(ctx context.Context, event outbox.Pending) error
if event.Envelope.Event.Topic == "fishing.projection" {
return s.rooms.updateFishing(ctx, event)
}
if event.Envelope.Event.Topic == battle.RecordCodeTopic {
return s.consumeRecordCode(ctx, event)
}
if event.Envelope.Event.Topic == "player.directory" {
return s.directory.consume(ctx, event)
}
@@ -0,0 +1,77 @@
//go:build integration
package app
import (
"encoding/binary"
"slices"
"testing"
"bd2server/internal/server/protocol/wire"
)
func shopFavorites(t *testing.T, body []byte, field int) map[uint64][]uint64 {
t.Helper()
out := map[uint64][]uint64{}
for _, info := range appRows(body, field) {
shop := appValue(info, 1)
if err := wire.Walk(info, func(f wire.Field) error {
if f.Number == 2 {
id, _ := binary.Uvarint(f.Value)
out[shop] = append(out[shop], id)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
return out
}
// 2.38.11 keeps NPC shop favorites on the server. ShopInfo asks the client to
// upload its former local favorites once; removed products are dropped, a
// second upload changes nothing and later saves persist across sessions.
func TestShopFavoritesMigrateOnceAndPersist(t *testing.T) {
g := profileGameplay(t)
var shop, first, second uint64
shops := make([]uint64, 0, len(g.factory.design.npcShopDesign.Products))
for id, products := range g.factory.design.npcShopDesign.Products {
if len(products) >= 2 {
shops = append(shops, id)
}
}
slices.Sort(shops)
if len(shops) == 0 {
t.Fatal("GameData has no shop with two products")
}
shop = shops[0]
var products []uint64
for id := range g.factory.design.npcShopDesign.Products[shop] {
products = append(products, id)
}
slices.Sort(products)
first, second = products[0], products[1]
if appValue(g.call("/ShopInfo", nil), 4) != 1 {
t.Fatal("new account was not asked to migrate local favorites")
}
packed := binary.AppendUvarint(binary.AppendUvarint(nil, first), 2147483647)
upload := wire.AppendBytes(nil, 2, wire.AppendBytes(wire.AppendVarint(nil, 1, shop), 2, packed))
if got := shopFavorites(t, g.call("/ShopFavoriteMigration", upload), 1); !slices.Equal(got[shop], []uint64{first}) || len(got) != 1 {
t.Fatalf("migration kept %v", got)
}
again := wire.AppendBytes(nil, 2, wire.AppendBytes(wire.AppendVarint(nil, 1, shop), 2, binary.AppendUvarint(nil, second)))
if got := shopFavorites(t, g.call("/ShopFavoriteMigration", again), 1); !slices.Equal(got[shop], []uint64{first}) {
t.Fatalf("second migration changed favorites: %v", got)
}
g.call("/ShopFavoriteSave", wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 2, shop), 3, second), 4, 1))
g.call("/ShopFavoriteSave", wire.AppendVarint(wire.AppendVarint(nil, 2, shop), 3, first))
g.execute(g.request("/ShopFavoriteSave", wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 2, shop), 3, 2147483647), 4, 1)), true)
g.reopen()
info := g.call("/ShopInfo", nil)
if appValue(info, 4) != 0 {
t.Fatal("migrated account was asked to migrate again")
}
if got := shopFavorites(t, info, 3); !slices.Equal(got[shop], []uint64{second}) || len(got) != 1 {
t.Fatalf("favorites after reopen %v", got)
}
}
@@ -4,6 +4,7 @@ package app
import (
"context"
"encoding/json"
"fmt"
"testing"
@@ -17,6 +18,44 @@ func avatarChoiceRequest(shop uint64) []byte {
return wire.AppendBytes(nil, 2, wire.AppendBytes(wire.AppendVarint(nil, 1, shop), 2, price))
}
func TestAvatarLoginRestoresCompletedSetupCredentialsWithoutRegrantingCharacter(t *testing.T) {
g := profileGameplay(t)
tickets := g.owner.assembly.design.avatarProfile.InitialUnlockTickets
if len(tickets) == 0 {
t.Fatal("missing SquareDefault setup ticket design")
}
g.call("/LoginUser", nil)
for _, ticket := range tickets {
if g.itemCount(19, ticket) != 0 {
t.Fatal("login unlocked content before avatar setup")
}
}
profileGrant(g, gamedata.Reward{Type: 61, ID: 1, Count: 1})
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
// An earlier client completed its first choice but received no setup tickets.
raw, err := json.Marshal(map[string]any{"use": map[string]any{"UseCharID": 1}, "wishlist": []uint64{}, "first_chosen": true})
if err != nil {
t.Fatal(err)
}
if err := p.gameplayStore.Save(ctx.State, "profile_avatar", raw); err != nil {
t.Fatal(err)
}
})
g.reopen()
before := g.wordCurrency()
g.call("/LoginUser", nil)
g.reopen()
g.call("/LoginUser", nil)
for _, ticket := range tickets {
if g.itemCount(19, ticket) != 1 {
t.Fatalf("completed setup did not retain one credential %d", ticket)
}
}
if g.itemCount(61, 1) != 1 || g.wordCurrency() != before {
t.Fatal("credential reconciliation repeated avatar or currency rewards")
}
}
// AvatarSelectUI -> SendFirstBuyAvatarCharRequest submits shop1's nominal
// price without a funds check. AvatarPacket first clamps the local debit to
// zero, then adds the response bundle. First choice is free by server policy.
@@ -24,11 +24,13 @@ func TestStarterGiftCurrentSourcesExcludeDefaultsAndAchievements(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var external, linked []gamedata.Reward
var external, linked, collaboration []gamedata.Reward
for _, gift := range gifts {
switch gift.Identity {
case startergift.LimitedAvatars:
external = gift.Rewards
case startergift.CollaborationAvatars:
collaboration = gift.Rewards
case "starter:prestige-avatar:65193:v1":
linked = gift.Rewards
}
@@ -44,7 +46,24 @@ func TestStarterGiftCurrentSourcesExcludeDefaultsAndAchievements(t *testing.T) {
if !slices.Equal(linked, want) {
t.Fatalf("owned prestige attachment=%v want %v", linked, want)
}
// AvatarCharTable 18/19/20 supplies the three bodies and nine matching parts.
if len(collaboration) != 12 {
t.Fatalf("collaboration attachments=%v, want three bodies and nine parts", collaboration)
}
for typ, ids := range map[uint64][]uint64{
61: {18, 19, 20},
49: {10030, 20038, 40055, 10031, 40056, 10033, 20040, 40061, 50025},
} {
for _, id := range ids {
if !slices.Contains(collaboration, gamedata.Reward{Type: typ, ID: id, Count: 1}) {
t.Fatalf("collaboration gift omitted %d:%d", typ, id)
}
}
}
for _, gift := range gifts {
if gift.Identity == startergift.CollaborationAvatars {
continue
}
if startergift.IsAvatarGift(gift.Identity) && gift.Identity != startergift.LimitedAvatars && gift.Identity != "starter:prestige-avatar:65193:v1" {
t.Fatalf("unowned prestige skin received an outfit: %s", gift.Identity)
}
@@ -65,6 +84,7 @@ func TestStarterGiftUpgradePreservesIssuedMailAndFiltersOwnedAccessories(t *test
}
for i := range legacy.Gifts {
legacy.Gifts[i].Parts = nil
legacy.Gifts[i].Characters = nil
}
factory.seeds.starterGifts = *legacy
owner, err := factory.open(accounts[0])
@@ -107,7 +127,7 @@ func TestStarterGiftUpgradePreservesIssuedMailAndFiltersOwnedAccessories(t *test
return ids, records
}
ids, _ := readMail()
if ids[startergift.LimitedCostumes] == 0 || ids[startergift.PrestigeSkins] == 0 || ids[startergift.LimitedAvatars] != 0 {
if ids[startergift.LimitedCostumes] == 0 || ids[startergift.PrestigeSkins] == 0 || ids[startergift.LimitedAvatars] != 0 || ids[startergift.CollaborationAvatars] != 0 {
t.Fatal("old account fixture must have only the two historical gifts")
}
// Leave the limited costume gift unclaimed and claim the prestige gift.
@@ -161,6 +181,38 @@ func TestStarterGiftUpgradePreservesIssuedMailAndFiltersOwnedAccessories(t *test
t.Fatalf("new claim request duplicated external accessory %d", id)
}
}
collaborationMail := ids[startergift.CollaborationAvatars]
if collaborationMail == 0 {
t.Fatal("existing account did not receive the collaboration avatar gift")
}
scenario.run(t, true, func(ctx command.Context, p *playerAssembly) {
if _, err := p.eventEconomy.Apply(ctx, "other-collaboration-source", nil, []gamedata.Reward{
{Type: 61, ID: 18, Count: 1}, {Type: 49, ID: 10030, Count: 1},
}); err != nil {
t.Fatal(err)
}
})
collaborationRequest := g.request("/MailOpen", appScalar(2, collaborationMail))
collaborationClaim := g.execute(collaborationRequest, false)
if retry := g.execute(collaborationRequest, false); !bytes.Equal(retry, collaborationClaim) {
t.Fatal("collaboration claim retry changed its reward bundle")
}
var acquired int
for _, bundle := range appRows(collaborationClaim, 1) {
for _, row := range appRows(bundle, 1) {
typ, id := appValue(row, 3), appValue(row, 2)
if typ == 61 && id == 18 || typ == 49 && id == 10030 {
t.Fatal("collaboration gift returned an already-owned body or part as newly acquired")
}
if typ == 49 || typ == 61 {
acquired++
}
}
}
if acquired != 10 {
t.Fatalf("new collaboration attachments=%d, want 10 after two owned items", acquired)
}
g.call("/MailOpen", appScalar(2, collaborationMail))
_, stable := readMail()
g.reopen()
g.call("/MailInfo", nil)
@@ -178,6 +230,16 @@ func TestStarterGiftUpgradePreservesIssuedMailAndFiltersOwnedAccessories(t *test
t.Fatalf("relogin duplicated or lost external accessory %d", id)
}
}
for typ, expected := range map[uint64][]uint64{
61: {18, 19, 20},
49: {10030, 20038, 40055, 10031, 40056, 10033, 20040, 40061, 50025},
} {
for _, id := range expected {
if got := g.itemCount(typ, id); got != 1 {
t.Fatalf("reopened collaboration %d:%d count=%d, want 1", typ, id, got)
}
}
}
}
func TestNewlyOwnedPrestigeCreatesLinkedGiftOnMailInfoWithoutDuplicatingSharedPieces(t *testing.T) {
+66 -66
View File
@@ -13,85 +13,85 @@ var realtimeEnabled = &commonconfig.Condition{Path: "realtime.enabled", In: []an
var providerActive = &commonconfig.Condition{Path: "text_moderation.provider.type", In: []any{"off"}, Not: true}
var schema = commonconfig.Schema{
Title: "游戏规则",
Summary: "服务端统一的玩法规则。修改后重启服务端生效。",
Title: "config.game.title",
Summary: "config.game.summary",
Sections: []commonconfig.Section{
{ID: "spine_recording", Title: "互动录制", Help: "保存玩家的互动立绘操作记录,并供原生客户端回放。修改后重启服务端生效。", Fields: []commonconfig.Field{
{Path: "spine_recording.download_base_url", Kind: commonconfig.KindString, Label: "录制下载基础 URL", Format: "url", Placeholder: "https://game.example.com/client/spine-recordings",
Help: "留空使用本服地址。自定义地址须反向代理到本服的 /client/spine-recordings/;系统会在其后追加录制路径和访问凭据。公网须使用 HTTPS。"},
{ID: "spine_recording", Title: "config.game.section.spine_recording.title", Help: "config.game.section.spine_recording.help", Fields: []commonconfig.Field{
{Path: "spine_recording.download_base_url", Kind: commonconfig.KindString, Label: "config.game.field.spine_recording.download_base_url.label", Format: "url", Placeholder: "https://game.example.com/client/spine-recordings",
Help: "config.game.field.spine_recording.download_base_url.help"},
}},
{ID: "story", Title: "开局章节", Help: "首次成功初始化后永久保存在服务器状态中,之后不能更改;不能通过删除数据库切换开局。", Fields: []commonconfig.Field{
{Path: "story.start_pack_id", Kind: commonconfig.KindInteger, Label: "起始章节", Options: []commonconfig.Option{
{Value: 21, Label: "店长篇", Help: "当前客户端默认的开局,使用该篇的任务和教学流程。"},
{Value: 1, Label: "旧主线第一章", Help: "使用当前 GameData 中该章的开场剧情、初始任务及购卡奖励。"},
{ID: "story", Title: "config.game.section.story.title", Help: "config.game.section.story.help", Fields: []commonconfig.Field{
{Path: "story.start_pack_id", Kind: commonconfig.KindInteger, Label: "config.game.field.story.start_pack_id.label", Options: []commonconfig.Option{
{Value: 21, Label: "config.game.field.story.start_pack_id.option.21.label", Help: "config.game.field.story.start_pack_id.option.21.help"},
{Value: 1, Label: "config.game.field.story.start_pack_id.option.1.label", Help: "config.game.field.story.start_pack_id.option.1.help"},
}},
}},
{ID: "gacha", Title: "抽卡", Fields: []commonconfig.Field{
{Path: "gacha.include_collaboration_ur_weapons", Kind: commonconfig.KindBool, Label: "UR 必得装备券加入联动专武",
Help: "在原池中加入 14 种联动角色 UR 专武(装备 943200–943213),沿用同星级单件权重;只改变券池候选,不直接发放装备。"},
{ID: "gacha", Title: "config.game.section.gacha.title", Fields: []commonconfig.Field{
{Path: "gacha.include_collaboration_ur_weapons", Kind: commonconfig.KindBool, Label: "config.game.field.gacha.include_collaboration_ur_weapons.label",
Help: "config.game.field.gacha.include_collaboration_ur_weapons.help"},
}},
{ID: "purchases", Title: "付费钻石充值", Help: "普通现金商品固定消耗付费钻石,价格由 GameData 换算;这里只设置付费钻石充值本身的兑换方式。", Fields: []commonconfig.Field{
{Path: "purchases.diamond_recharge.currency", Kind: commonconfig.KindString, Label: "充值方式", Options: []commonconfig.Option{
{Value: "free", Label: "免费", Help: "不扣货币,直接发放所选充值商品的原始奖励。"},
{Value: "gold", Label: "金币兑换", Help: "每单位常规付费钻石消耗设定数量的金币。"},
{Value: "diamonds", Label: "普通钻石兑换", Help: "每单位常规付费钻石消耗设定数量的普通钻石。"},
{Value: "ban", Label: "禁止充值", Help: "禁止购买付费钻石充值商品,不影响玩家已有付费钻石。"},
{Value: "", Label: "禁止充值(空字符串)", Help: "与 ban 相同的旧写法。"},
{ID: "purchases", Title: "config.game.section.purchases.title", Help: "config.game.section.purchases.help", Fields: []commonconfig.Field{
{Path: "purchases.diamond_recharge.currency", Kind: commonconfig.KindString, Label: "config.game.field.purchases.diamond_recharge.currency.label", Options: []commonconfig.Option{
{Value: "free", Label: "config.game.field.purchases.diamond_recharge.currency.option.free.label", Help: "config.game.field.purchases.diamond_recharge.currency.option.free.help"},
{Value: "gold", Label: "config.game.field.purchases.diamond_recharge.currency.option.gold.label", Help: "config.game.field.purchases.diamond_recharge.currency.option.gold.help"},
{Value: "diamonds", Label: "config.game.field.purchases.diamond_recharge.currency.option.diamonds.label", Help: "config.game.field.purchases.diamond_recharge.currency.option.diamonds.help"},
{Value: "ban", Label: "config.game.field.purchases.diamond_recharge.currency.option.ban.label", Help: "config.game.field.purchases.diamond_recharge.currency.option.ban.help"},
{Value: "", Label: "config.game.field.purchases.diamond_recharge.currency.option..label", Help: "config.game.field.purchases.diamond_recharge.currency.option..help"},
}},
{Path: "purchases.diamond_recharge.gold_per_paid_diamond", Kind: commonconfig.KindInteger, Label: "金币 / 付费钻石", Min: rateMin, Max: rateMax,
Help: "金币兑换时每单位常规付费钻石的费用。即使未选用也必须合法。"},
{Path: "purchases.diamond_recharge.diamonds_per_paid_diamond", Kind: commonconfig.KindInteger, Label: "普通钻石 / 付费钻石", Min: rateMin, Max: rateMax,
Help: "普通钻石兑换时每单位常规付费钻石的费用。即使未选用也必须合法。"},
{Path: "purchases.diamond_recharge.gold_per_paid_diamond", Kind: commonconfig.KindInteger, Label: "config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.label", Min: rateMin, Max: rateMax,
Help: "config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.help"},
{Path: "purchases.diamond_recharge.diamonds_per_paid_diamond", Kind: commonconfig.KindInteger, Label: "config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.label", Min: rateMin, Max: rateMax,
Help: "config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.help"},
}},
{ID: "realtime", Title: "实时联机", Help: "动作小游戏、联机钓鱼与随机防御使用的原生 TCP/UDP 连接。关闭时不监听实时端口,会影响玩家体验。", Fields: []commonconfig.Field{
{Path: "realtime.enabled", Kind: commonconfig.KindBool, Label: "启用实时联机"},
{Path: "realtime.public_host", Kind: commonconfig.KindString, Label: "公开主机名", Format: "host", Placeholder: "game.example.com", When: realtimeEnabled,
Help: "玩家能够访问的主机名,不带协议、路径或端口。"},
{Path: "realtime.tcp_port", Kind: commonconfig.KindInteger, Label: "公开 TCP 端口", Min: portMin, Max: portMax, When: realtimeEnabled},
{Path: "realtime.udp_port", Kind: commonconfig.KindInteger, Label: "公开 UDP 端口", Min: portMin, Max: portMax, When: realtimeEnabled},
{Path: "realtime.tcp_listen", Kind: commonconfig.KindString, Label: "TCP 监听地址", Format: "listen", Placeholder: "0.0.0.0:8444", When: realtimeEnabled,
Help: "公开端口可以与监听端口不同,适用于端口映射。"},
{Path: "realtime.udp_listen", Kind: commonconfig.KindString, Label: "UDP 监听地址", Format: "listen", Placeholder: "0.0.0.0:8444", When: realtimeEnabled},
{Path: "realtime.tls_cert_file", Kind: commonconfig.KindString, Label: "TLS 证书", Format: "path", When: realtimeEnabled,
Help: "与公开主机名匹配且受客户端信任的证书。相对路径以 game.json 所在目录为基准;更新后新握手自动载入。"},
{Path: "realtime.tls_key_file", Kind: commonconfig.KindString, Label: "TLS 私钥", Format: "path", When: realtimeEnabled,
Help: "私钥只留在服务端,须允许服务进程读取。"},
{Path: "realtime.development_plain_loopback", Kind: commonconfig.KindBool, Label: "本机开发明文模式", Advanced: true, When: realtimeEnabled,
Help: "仅限本机开发:监听地址和公开地址都必须是回环 IP,此时不需要证书。"},
{ID: "realtime", Title: "config.game.section.realtime.title", Help: "config.game.section.realtime.help", Fields: []commonconfig.Field{
{Path: "realtime.enabled", Kind: commonconfig.KindBool, Label: "config.game.field.realtime.enabled.label"},
{Path: "realtime.public_host", Kind: commonconfig.KindString, Label: "config.game.field.realtime.public_host.label", Format: "host", Placeholder: "game.example.com", When: realtimeEnabled,
Help: "config.game.field.realtime.public_host.help"},
{Path: "realtime.tcp_port", Kind: commonconfig.KindInteger, Label: "config.game.field.realtime.tcp_port.label", Min: portMin, Max: portMax, When: realtimeEnabled},
{Path: "realtime.udp_port", Kind: commonconfig.KindInteger, Label: "config.game.field.realtime.udp_port.label", Min: portMin, Max: portMax, When: realtimeEnabled},
{Path: "realtime.tcp_listen", Kind: commonconfig.KindString, Label: "config.game.field.realtime.tcp_listen.label", Format: "listen", Placeholder: "0.0.0.0:8444", When: realtimeEnabled,
Help: "config.game.field.realtime.tcp_listen.help"},
{Path: "realtime.udp_listen", Kind: commonconfig.KindString, Label: "config.game.field.realtime.udp_listen.label", Format: "listen", Placeholder: "0.0.0.0:8444", When: realtimeEnabled},
{Path: "realtime.tls_cert_file", Kind: commonconfig.KindString, Label: "config.game.field.realtime.tls_cert_file.label", Format: "path", When: realtimeEnabled,
Help: "config.game.field.realtime.tls_cert_file.help"},
{Path: "realtime.tls_key_file", Kind: commonconfig.KindString, Label: "config.game.field.realtime.tls_key_file.label", Format: "path", When: realtimeEnabled,
Help: "config.game.field.realtime.tls_key_file.help"},
{Path: "realtime.development_plain_loopback", Kind: commonconfig.KindBool, Label: "config.game.field.realtime.development_plain_loopback.label", Advanced: true, When: realtimeEnabled,
Help: "config.game.field.realtime.development_plain_loopback.help"},
}},
{ID: "text_moderation", Title: "文本审核", Help: "本地规则先执行,通过后才调用第三方。已有昵称和简介不会在登录时重新审核。", Fields: []commonconfig.Field{
{Path: "text_moderation.rule_files", Kind: commonconfig.KindList, Label: "本地词库文件", Format: "path",
Help: "UTF-8 的 .txt(每行一个词,子串匹配)或 .json(逐条指定匹配方式与范围),单文件最多 4 MiB。相对路径以 game.json 所在目录为基准。"},
{Path: "text_moderation.provider.type", Kind: commonconfig.KindString, Label: "第三方审核", Options: []commonconfig.Option{
{Value: "off", Label: "关闭"},
{Value: "http_json", Label: "通用 HTTP JSON", Help: "接入自建审核服务或第三方适配网关。"},
{Value: "azure_content_safety", Label: "Azure AI Content Safety"},
{ID: "text_moderation", Title: "config.game.section.text_moderation.title", Help: "config.game.section.text_moderation.help", Fields: []commonconfig.Field{
{Path: "text_moderation.rule_files", Kind: commonconfig.KindList, Label: "config.game.field.text_moderation.rule_files.label", Format: "path",
Help: "config.game.field.text_moderation.rule_files.help"},
{Path: "text_moderation.provider.type", Kind: commonconfig.KindString, Label: "config.game.field.text_moderation.provider.type.label", Options: []commonconfig.Option{
{Value: "off", Label: "config.game.field.text_moderation.provider.type.option.off.label"},
{Value: "http_json", Label: "config.game.field.text_moderation.provider.type.option.http_json.label", Help: "config.game.field.text_moderation.provider.type.option.http_json.help"},
{Value: "azure_content_safety", Label: "config.game.field.text_moderation.provider.type.option.azure_content_safety.label"},
}},
{Path: "text_moderation.provider.endpoint", Kind: commonconfig.KindString, Label: "审核地址", Format: "url", When: providerActive,
Help: "使用 HTTPS,只有回环地址允许 HTTP,不跟随重定向。Azure 填资源根地址。"},
{Path: "text_moderation.provider.api_key_env", Kind: commonconfig.KindString, Label: "密钥环境变量", Format: "env", When: providerActive,
Help: "服务端从这个环境变量读取密钥,配置文件里不保存密钥本身。"},
{Path: "text_moderation.provider.api_key_header", Kind: commonconfig.KindString, Label: "密钥请求头", Advanced: true,
{Path: "text_moderation.provider.endpoint", Kind: commonconfig.KindString, Label: "config.game.field.text_moderation.provider.endpoint.label", Format: "url", When: providerActive,
Help: "config.game.field.text_moderation.provider.endpoint.help"},
{Path: "text_moderation.provider.api_key_env", Kind: commonconfig.KindString, Label: "config.game.field.text_moderation.provider.api_key_env.label", Format: "env", When: providerActive,
Help: "config.game.field.text_moderation.provider.api_key_env.help"},
{Path: "text_moderation.provider.api_key_header", Kind: commonconfig.KindString, Label: "config.game.field.text_moderation.provider.api_key_header.label", Advanced: true,
When: &commonconfig.Condition{Path: "text_moderation.provider.type", In: []any{"http_json"}},
Help: "Authorization 头会发送 Bearer <密钥>,其他头名原样传递密钥。"},
{Path: "text_moderation.provider.scopes", Kind: commonconfig.KindList, Label: "审核范围", Unique: true, OpenOptions: true,
Help: "第三方只审核明确列出的输入入口。", Options: []commonconfig.Option{
{Value: "nickname", Label: "玩家昵称"}, {Value: "greeting", Label: "个人简介"}, {Value: "master_title", Label: "主角称呼"},
{Value: "preset_name", Label: "配队预设名"}, {Value: "equipment_preset_name", Label: "装备预设名"}, {Value: "equipment_mark", Label: "装备标记"},
{Value: "monster_hunt_preset_name", Label: "魔兽追踪者预设名"}, {Value: "guild_raid_preset_name", Label: "公会战预设名"},
{Value: "colosseum_preset_name", Label: "斗兽场预设名"}, {Value: "guild_name", Label: "公会名称"}, {Value: "guild_message", Label: "公会介绍"},
{Value: "guild_notice", Label: "公会公告"}, {Value: "room_name", Label: "房间名称"}, {Value: "chat", Label: "联机聊天"},
Help: "config.game.field.text_moderation.provider.api_key_header.help"},
{Path: "text_moderation.provider.scopes", Kind: commonconfig.KindList, Label: "config.game.field.text_moderation.provider.scopes.label", Unique: true, OpenOptions: true,
Help: "config.game.field.text_moderation.provider.scopes.help", Options: []commonconfig.Option{
{Value: "nickname", Label: "config.game.field.text_moderation.provider.scopes.option.nickname.label"}, {Value: "greeting", Label: "config.game.field.text_moderation.provider.scopes.option.greeting.label"}, {Value: "master_title", Label: "config.game.field.text_moderation.provider.scopes.option.master_title.label"},
{Value: "preset_name", Label: "config.game.field.text_moderation.provider.scopes.option.preset_name.label"}, {Value: "equipment_preset_name", Label: "config.game.field.text_moderation.provider.scopes.option.equipment_preset_name.label"}, {Value: "equipment_mark", Label: "config.game.field.text_moderation.provider.scopes.option.equipment_mark.label"},
{Value: "monster_hunt_preset_name", Label: "config.game.field.text_moderation.provider.scopes.option.monster_hunt_preset_name.label"}, {Value: "guild_raid_preset_name", Label: "config.game.field.text_moderation.provider.scopes.option.guild_raid_preset_name.label"},
{Value: "colosseum_preset_name", Label: "config.game.field.text_moderation.provider.scopes.option.colosseum_preset_name.label"}, {Value: "guild_name", Label: "config.game.field.text_moderation.provider.scopes.option.guild_name.label"}, {Value: "guild_message", Label: "config.game.field.text_moderation.provider.scopes.option.guild_message.label"},
{Value: "guild_notice", Label: "config.game.field.text_moderation.provider.scopes.option.guild_notice.label"}, {Value: "room_name", Label: "config.game.field.text_moderation.provider.scopes.option.room_name.label"}, {Value: "chat", Label: "config.game.field.text_moderation.provider.scopes.option.chat.label"},
}},
{Path: "text_moderation.provider.timeout_ms", Kind: commonconfig.KindInteger, Label: "超时(毫秒)", Min: timeoutMin, Max: timeoutMax, Advanced: true},
{Path: "text_moderation.provider.failure_policy", Kind: commonconfig.KindString, Label: "接口故障时", Advanced: true, Options: []commonconfig.Option{
{Value: "deny", Label: "暂不接受修改", Help: "客户端提示审核暂时不可用。"},
{Value: "allow", Label: "放行", Help: "放行已通过本地规则的文本;明确拒绝的结果不会被放行。"},
{Path: "text_moderation.provider.timeout_ms", Kind: commonconfig.KindInteger, Label: "config.game.field.text_moderation.provider.timeout_ms.label", Min: timeoutMin, Max: timeoutMax, Advanced: true},
{Path: "text_moderation.provider.failure_policy", Kind: commonconfig.KindString, Label: "config.game.field.text_moderation.provider.failure_policy.label", Advanced: true, Options: []commonconfig.Option{
{Value: "deny", Label: "config.game.field.text_moderation.provider.failure_policy.option.deny.label", Help: "config.game.field.text_moderation.provider.failure_policy.option.deny.help"},
{Value: "allow", Label: "config.game.field.text_moderation.provider.failure_policy.option.allow.label", Help: "config.game.field.text_moderation.provider.failure_policy.option.allow.help"},
}},
{Path: "text_moderation.provider.severity_threshold", Kind: commonconfig.KindInteger, Label: "Azure 拒绝阈值", Min: severityMin, Max: severityMax, Advanced: true,
Help: "任一类别达到该严重程度即拒绝;0 表示连严重程度 0 的结果也拒绝。"},
{Path: "text_moderation.provider.severity_threshold", Kind: commonconfig.KindInteger, Label: "config.game.field.text_moderation.provider.severity_threshold.label", Min: severityMin, Max: severityMax, Advanced: true,
Help: "config.game.field.text_moderation.provider.severity_threshold.help"},
}},
{ID: "format", Title: "格式", Fields: []commonconfig.Field{
{Path: "schema_version", Kind: commonconfig.KindInteger, Label: "格式版本", Advanced: true, Options: []commonconfig.Option{{Value: 1, Label: "1"}}},
{ID: "format", Title: "config.game.section.format.title", Fields: []commonconfig.Field{
{Path: "schema_version", Kind: commonconfig.KindInteger, Label: "config.game.field.schema_version.label", Advanced: true, Options: []commonconfig.Option{{Value: 1, Label: "1"}}},
}},
},
}
@@ -12,6 +12,8 @@ import (
// introduction; ticket identities and level requirements remain version data.
type ContentOpeningDesign struct {
Prerequisite, Completion, Dating ContentOpenRule
TicketTypes map[uint64]uint64
Rules map[[2]uint64]ContentOpenRule
}
func LoadContentOpeningDesign(root, version string) (*ContentOpeningDesign, error) {
@@ -65,7 +67,7 @@ func loadContentOpeningDesign(db *sql.DB) (*ContentOpeningDesign, error) {
return nil, err
}
defer func() { _ = rows.Close() }()
d := &ContentOpeningDesign{}
d := &ContentOpeningDesign{TicketTypes: tickets, Rules: map[[2]uint64]ContentOpenRule{}}
seen := map[[2]uint64]bool{}
for rows.Next() {
var group, id, ticket uint64
@@ -86,6 +88,7 @@ func loadContentOpeningDesign(db *sql.DB) (*ContentOpeningDesign, error) {
}
seen[key] = true
rule := ContentOpenRule{TutorialID: values[3], SquadLevel: values[4], TicketID: ticket}
d.Rules[key] = rule
if key == [2]uint64{19, 1} {
if tickets[ticket] != 1 {
return nil, fmt.Errorf("gamedata: dating opening requires permanent content ticket")
@@ -199,7 +199,7 @@ func loadEquipmentSmeltingDesign(db *sql.DB) (*EquipmentSmeltingDesign, error) {
if err := db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&defaults); err != nil {
return nil, fmt.Errorf("gamedata: equipment smelting limit: %w", err)
}
maxStreak, _ := packedInts(defaults, 5)
maxStreak, _ := packedInts(defaults, GameDefaultMaxEquipmentRefineStreak)
if len(maxStreak) != 1 || maxStreak[0] == 0 {
return nil, fmt.Errorf("gamedata: invalid maximum smelting streak")
}
@@ -15,7 +15,7 @@ func LoadEventAPDesign(root, version string) (map[uint64]uint64, HuntingAPDesign
return nil, d, e
}
caps := map[uint64]uint64{}
for typ, field := range map[uint64]int{30: 43, 32: 113, 35: 102} {
for typ, field := range map[uint64]int{30: GameDefaultEventAPMax, 32: GameDefaultTorchLightAPMax, 35: GameDefaultRoguelikeAPMax} {
n, e := optionalScalar(raw, field)
if e != nil {
return nil, d, e
@@ -23,7 +23,7 @@ func LoadFieldResetSchedule(root, version string) (FieldResetSchedule, error) {
if err = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&raw); err != nil {
return FieldResetSchedule{}, err
}
times, found, err := wire.Bytes(raw, 23)
times, found, err := wire.Bytes(raw, GameDefaultDailyResetTime)
if err != nil || !found {
return FieldResetSchedule{}, fmt.Errorf("gamedata: missing field daily reset time")
}
@@ -38,7 +38,7 @@ func LoadFieldResetSchedule(root, version string) (FieldResetSchedule, error) {
return FieldResetSchedule{}, fmt.Errorf("gamedata: invalid daily reset time")
}
}
day, _, err := wire.Varint(raw, 97)
day, _, err := wire.Varint(raw, GameDefaultResetDayOfWeek)
if err != nil || day > 6 {
return FieldResetSchedule{}, fmt.Errorf("gamedata: invalid weekly reset day")
}
@@ -18,7 +18,7 @@ func LoadFieldSettingsDesign(root, version string) (*FieldSettingsDesign, error)
if e = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&raw); e != nil {
return nil, e
}
n, e := optionalScalar(raw, 109)
n, e := optionalScalar(raw, GameDefaultTalentSkillPinMaxCount)
if e != nil || n == 0 || n > 2147483647 {
return nil, fmt.Errorf("gamedata: invalid talent slot capacity")
}
@@ -101,7 +101,7 @@ func loadFirstGacha(db *sql.DB) (*FirstGachaDesign, error) {
if err != nil {
return nil, err
}
first, err := packedInts(defaults, 46)
first, err := packedInts(defaults, GameDefaultFirstLimitGachaID)
if err != nil || len(first) != 1 || first[0] == 0 {
return nil, errors.New("gamedata: missing FirstLimitGachaId")
}
+30 -10
View File
@@ -39,6 +39,7 @@ type InfiniteGachaDesign struct {
type CharacterDesign struct {
ID uint64
Element uint64
GrowthCharacterIDs []uint64 // Permanent CharTable IDs sharing this costume's UniqueCharId.
HP uint64
CostumeMaxLevel uint64
@@ -67,6 +68,7 @@ type RegularGacha struct {
RewardGroup *CostumeRewardGroup
FixedCostumeID uint64
TicketIDs []uint64
TicketOnly bool
}
type GachaGroupDesign struct {
@@ -219,7 +221,7 @@ func NewRegularGachaCatalog(gachas map[uint64]RegularGacha, characters map[uint6
}
maps.Copy(catalog.characters, characters)
for id, gacha := range gachas {
if id == 0 || gacha.ID != id || gacha.Count <= 0 || (gacha.PriceType != 2 && gacha.PriceType != 3 && gacha.PriceType != 19) || gacha.Price == 0 {
if id == 0 || gacha.ID != id || gacha.Count <= 0 || (!gacha.TicketOnly && ((gacha.PriceType != 2 && gacha.PriceType != 3 && gacha.PriceType != 19) || gacha.Price == 0)) || (gacha.TicketOnly && (gacha.PriceType != 0 || gacha.Price != 0 || len(gacha.TicketIDs) == 0)) {
return nil, errors.New("gamedata: invalid regular gacha definition")
}
if gacha.RewardGroup == nil {
@@ -243,7 +245,7 @@ func NewRegularGachaCatalog(gachas map[uint64]RegularGacha, characters map[uint6
// AddGroupDesign supports small, schema-accurate fixtures. Production uses
// loadGroupsAndFixed to read the same fields from the live GameData tables.
func (c *RegularGachaCatalog) AddGroupDesign(group GachaGroupDesign, fixed GachaFixedDesign) error {
if c == nil || group.ID == 0 || group.PointCount == 0 {
if c == nil || group.ID == 0 || (group.PointCount == 0 && group.GachaSubType != 2) {
return errors.New("gamedata: invalid gacha group")
}
if group.OneTimeGachaID != 0 {
@@ -869,9 +871,9 @@ func LoadActiveGachaForSchedules(root, version string, scheduleGroupIDs, stepUpG
return LoadActiveGacha(root, version, costume, equipment, stepUpGroupIDs)
}
// permanentGachaGroupIDs returns static selection and ordinary equipment groups. ScheduleType=0
// permanentGachaGroupIDs returns static selection, element, and ordinary equipment groups. ScheduleType=0
// groups are deliberately absent from the dynamic schedule response; the
// selection or shared pity/point metadata distinguishes these banners from
// subtype or shared pity/point metadata distinguishes these banners from
// content-ticket banners handled by other flows.
func permanentGachaGroupIDs(root, version string) ([]uint64, error) {
db, closeDB, err := openStatDatabase(root, version)
@@ -896,6 +898,8 @@ func permanentGachaGroupIDs(root, version string) ([]uint64, error) {
types, _ := packedInts(raw, 17)
if len(types) == 1 && types[0] == 1 && len(subTypes) == 1 && subTypes[0] == 1 && len(selectCounts) == 1 && selectCounts[0] != 0 {
result = append(result, id)
} else if len(types) == 1 && types[0] == 1 && len(subTypes) == 1 && subTypes[0] == 2 {
result = append(result, id)
} else if isPermanentEquipmentGachaGroup(raw) {
result = append(result, id)
}
@@ -982,7 +986,7 @@ func LoadRegularCostumeGachaGroups(root, version string, groupIDs, stepUpGroupID
if err := db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&defaults); err != nil {
return nil, fmt.Errorf("gamedata: gacha defaults: %w", err)
}
bonusCounts, err := packedInts(defaults, 48)
bonusCounts, err := packedInts(defaults, GameDefaultGachaEventAddFreeCount)
if err != nil || len(bonusCounts) > 1 {
return nil, errors.New("gamedata: malformed GachaEventAddFreeCount")
}
@@ -991,12 +995,13 @@ func LoadRegularCostumeGachaGroups(root, version string, groupIDs, stepUpGroupID
return nil, err
}
}
paidBonus, err := optionalScalar(defaults, 47)
paidBonus, err := optionalScalar(defaults, GameDefaultGachaEventAddDailyPayGachaCount)
if err != nil || paidBonus > 256 {
return nil, errors.New("gamedata: malformed GachaEventAddDailyPayGachaCount")
}
catalog.gachaEventAddDailyPayCount = paidBonus
gachaIDs := make(map[uint64]struct{})
elementGachaIDs := make(map[uint64]bool)
for _, groupID := range groupIDs {
var raw []byte
if err := db.QueryRow("SELECT ProtoBuf FROM GachaGroupTable WHERE id=?", groupID).Scan(&raw); err != nil {
@@ -1013,6 +1018,11 @@ func LoadRegularCostumeGachaGroups(root, version string, groupIDs, stepUpGroupID
}
if len(ids) == 1 && ids[0] != 0 {
gachaIDs[ids[0]] = struct{}{}
subType, err := optionalScalar(raw, 16)
if err != nil {
return nil, err
}
elementGachaIDs[ids[0]] = subType == 2
}
}
}
@@ -1049,8 +1059,9 @@ func LoadRegularCostumeGachaGroups(root, version string, groupIDs, stepUpGroupID
priceIDs, _ := packedInts(proto, 11)
priceTypes, _ := packedInts(proto, 12)
ticketIDs, _ := packedInts(proto, 8)
if len(counts) != 1 || len(groups) != 1 || len(prices) != 1 || len(priceTypes) != 1 ||
(priceTypes[0] != 2 && priceTypes[0] != 3 && priceTypes[0] != 19) {
ticketOnly := elementGachaIDs[id] && len(prices) == 0 && len(priceIDs) == 0 && len(priceTypes) == 0 && len(ticketIDs) != 0
if len(counts) != 1 || counts[0] == 0 || counts[0] > 256 || len(groups) != 1 || (!ticketOnly && (len(prices) != 1 || len(priceTypes) != 1 ||
(priceTypes[0] != 2 && priceTypes[0] != 3 && priceTypes[0] != 19))) {
return nil, fmt.Errorf("gamedata: malformed regular gacha %d", id)
}
var priceID uint64
@@ -1064,7 +1075,7 @@ func LoadRegularCostumeGachaGroups(root, version string, groupIDs, stepUpGroupID
return nil, fmt.Errorf("gamedata: regular gacha %d: %w", id, err)
}
rewardCount, err := costumeRewardCount(reward)
if err != nil || rewardCount != counts[0] {
if err != nil || (rewardCount != counts[0] && (!ticketOnly || rewardCount != 1 || reward.DropType != 0)) {
return nil, fmt.Errorf("gamedata: regular gacha %d reward count=%d want=%d: %w", id, rewardCount, counts[0], err)
}
pool, _ := costumeRewardPool(reward)
@@ -1116,7 +1127,11 @@ func LoadRegularCostumeGachaGroups(root, version string, groupIDs, stepUpGroupID
if (dailyPayCount == 0) != (dailyPayPrice == 0) {
return nil, fmt.Errorf("gamedata: regular gacha %d has incomplete daily paid design", id)
}
catalog.Gachas[id] = RegularGacha{Grades: catalog.grades, ID: id, Count: int(counts[0]), DailyPayGachaCount: dailyPayCount, DailyPayGachaPriceCount: dailyPayPrice, FreeCountDay: freeCount, PriceType: priceTypes[0], PriceID: priceID, Price: prices[0], Pool: pool, RewardGroup: program, FixedCostumeID: fixedCostumeID, TicketIDs: ticketIDs}
var priceType, price uint64
if !ticketOnly {
priceType, price = priceTypes[0], prices[0]
}
catalog.Gachas[id] = RegularGacha{TicketOnly: ticketOnly, Grades: catalog.grades, ID: id, Count: int(counts[0]), DailyPayGachaCount: dailyPayCount, DailyPayGachaPriceCount: dailyPayPrice, FreeCountDay: freeCount, PriceType: priceType, PriceID: priceID, Price: price, Pool: pool, RewardGroup: program, FixedCostumeID: fixedCostumeID, TicketIDs: ticketIDs}
catalog.recordPoolGrades(catalog.Gachas[id])
}
if err := catalog.loadGroupsAndFixed(db); err != nil {
@@ -1474,6 +1489,11 @@ func loadGachaCharacterDesign(db *sql.DB, costumeID uint64) (CharacterDesign, er
if err != nil {
return CharacterDesign{}, err
}
element, err := optionalScalar(character, 6)
if err != nil || element > 5 {
return CharacterDesign{}, fmt.Errorf("gamedata: character %d invalid element", characterID)
}
costume.Element = element
costume.ID = characterID
costume.GrowthCharacterIDs = family
costume.HP = uint64(hp)
@@ -0,0 +1,28 @@
package gamedata
import "fmt"
// ElementGacha restricts the authoritative reward pool using the character
// element, as GachaEachRateScrollItem does for subtype 2. Water is enum zero.
func (c *RegularGachaCatalog) ElementGacha(id, element uint64) (RegularGacha, error) {
gacha, ok := c.Gacha(id)
group, grouped := c.GroupForGacha(id)
if !ok || !grouped || group.GachaSubType != 2 || !gacha.TicketOnly || element > 4 || gacha.RewardGroup != nil {
return RegularGacha{}, fmt.Errorf("gamedata: invalid element gacha %d element=%d", id, element)
}
var err error
gacha.Pool, err = gacha.conditionedPool(func(id uint64) (bool, error) {
character, exists := c.characters[id]
if !exists {
return false, fmt.Errorf("gamedata: costume %d lacks character", id)
}
return character.Element == element, nil
})
if err != nil {
return RegularGacha{}, err
}
if len(gacha.Pool) == 0 {
return RegularGacha{}, fmt.Errorf("gamedata: empty element gacha %d element=%d", id, element)
}
return gacha, nil
}
@@ -0,0 +1,55 @@
//go:build integration
package gamedata
import (
"testing"
"bd2server/internal/common/versionconfig"
)
// Independently queried 20261104152727: group1008 has subtype2, no point or
// fixed ID, gachas40/41 have counts1/10 and ticket1106, reward70011 has one
// weighted draw with 131 grade-five costumes. CharTable element counts below
// come from CostumeTable.UseUniqueCharId, including protobuf-default water0.
func TestCurrentGameDataElementGachaLoadsAndRepeatsOneRewardProgram(t *testing.T) {
versions, err := versionconfig.Find()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := CloseDatabaseCache(); err != nil {
t.Error(err)
}
})
c, _, err := LoadActiveGachaForSchedules(versions.Resolve("data/resources/GameData"), versions.GameDataVersion, nil, nil)
if err != nil {
t.Fatal(err)
}
group, ok := c.Group(1008)
if !ok || group.FixedID != 0 || group.PointCount != 0 || group.GachaSubType != 2 {
t.Fatalf("element group=%+v", group)
}
for element, size := range []int{24, 30, 24, 30, 23} {
for id, count := range map[uint64]int{40: 1, 41: 10} {
g, err := c.ElementGacha(id, uint64(element))
if err != nil {
t.Fatal(err)
}
if !g.TicketOnly || g.PriceType != 0 || g.Price != 0 || len(g.TicketIDs) != 1 || g.TicketIDs[0] != 1106 || g.Count != count || len(g.Pool) != size {
t.Fatalf("element%d gacha%d=%+v", element, id, g)
}
for _, entry := range g.Pool {
ch, ok := c.Character(entry.ID)
grade, graded := c.CostumeGrade(entry.ID)
if !ok || ch.Element != uint64(element) || !graded || grade != 5 || entry.Weight != 1 {
t.Fatalf("unexpected element pool entry=%+v character=%+v grade=%d", entry, ch, grade)
}
}
roll, err := g.Roll()
if err != nil || len(roll) != count {
t.Fatalf("gacha%d produced %d results err=%v", id, len(roll), err)
}
}
}
}
@@ -0,0 +1,53 @@
package gamedata
import (
"reflect"
"testing"
)
func TestElementGachaConditionsNestedWeightsAndDoesNotMutateCatalog(t *testing.T) {
// Before filtering: costume 1 has mass 1/4 and costume 3 has mass 1/2.
// Conditioning on water must produce a 1:2 ratio, although both surviving
// parent branches originally had equal weights.
pool := []WeightedCostume{
{Weight: 1, Children: []WeightedCostume{{ID: 1, Weight: 1}, {ID: 2, Weight: 1}}},
{Weight: 1, Children: []WeightedCostume{{ID: 3, Weight: 1}}},
}
c, err := NewRegularGachaCatalog(map[uint64]RegularGacha{1: {ID: 1, Count: 1, TicketOnly: true, TicketIDs: []uint64{9}, Pool: pool}}, map[uint64]CharacterDesign{1: {ID: 1, Element: 0}, 2: {ID: 2, Element: 1}, 3: {ID: 3, Element: 0}})
if err != nil {
t.Fatal(err)
}
if err = c.AddGroupDesign(GachaGroupDesign{ID: 2, GachaSubType: 2, OneTimeGachaID: 1}, GachaFixedDesign{}); err != nil {
t.Fatal(err)
}
g, err := c.ElementGacha(1, 0)
if err != nil {
t.Fatal(err)
}
var choices []uint64
for n := range uint64(3) {
id, err := rollCostumeChoiceWith(g.Pool, func(total uint64) (uint64, error) {
if total != 3 {
t.Fatalf("conditioned total=%d, want 3", total)
}
return n, nil
})
if err != nil {
t.Fatal(err)
}
choices = append(choices, id)
}
if !reflect.DeepEqual(choices, []uint64{1, 3, 3}) {
t.Fatalf("conditioned choices=%v", choices)
}
wantPool := []WeightedCostume{
{Weight: 1, Children: []WeightedCostume{{ID: 1, Weight: 1}, {ID: 2, Weight: 1}}},
{Weight: 1, Children: []WeightedCostume{{ID: 3, Weight: 1}}},
}
if !reflect.DeepEqual(c.Gachas[1].Pool, wantPool) {
t.Fatal("element selection mutated shared catalog")
}
if _, err = c.ElementGacha(1, 2); err == nil {
t.Fatal("empty eligible element accepted")
}
}
@@ -8,6 +8,16 @@ import (
// gradePool conditions the actual nested weighted distribution on one grade.
// Exact rational path weights preserve branches with different child totals.
func (g RegularGacha) gradePool(grade uint64) ([]WeightedCostume, error) {
return g.conditionedPool(func(id uint64) (bool, error) {
actual, ok := g.Grades[id]
if !ok || actual < 3 || actual > 5 {
return false, errors.New("gamedata: costume grade unavailable")
}
return actual == grade, nil
})
}
func (g RegularGacha) conditionedPool(include func(uint64) (bool, error)) ([]WeightedCostume, error) {
weights := map[uint64]*big.Rat{}
var walk func([]WeightedCostume, *big.Rat) error
walk = func(pool []WeightedCostume, path *big.Rat) error {
@@ -29,11 +39,11 @@ func (g RegularGacha) gradePool(grade uint64) ([]WeightedCostume, error) {
}
continue
}
actual, ok := g.Grades[item.ID]
if !ok || actual < 3 || actual > 5 {
return errors.New("gamedata: costume grade unavailable")
matched, err := include(item.ID)
if err != nil {
return err
}
if actual == grade {
if matched {
if weights[item.ID] == nil {
weights[item.ID] = new(big.Rat)
}
@@ -0,0 +1,65 @@
package gamedata
// GameDefaultTable field numbers from common.db GameDefaultTable.proto. The
// generator numbers the fields alphabetically, so a client update that adds a
// field renumbers every field after it; keep every reader on these names.
const (
GameDefaultMaxEquipmentRefineStreak = 5
GameDefaultAddEquipInvenPriceCount = 9
GameDefaultAddEquipInvenPriceType = 10
GameDefaultAddEquipStoragePriceCount = 11
GameDefaultAddEquipStoragePriceType = 12
GameDefaultAddInvenPriceCount = 13
GameDefaultAddInvenPriceType = 14
GameDefaultAddStoragePriceCount = 15
GameDefaultAddStoragePriceType = 16
GameDefaultColosseumPresetBaseCount = 21
GameDefaultColosseumPresetMaxCount = 22
GameDefaultDailyResetTime = 24
GameDefaultDefaultCostumeID = 30
GameDefaultDefaultEquipInvenSlotCount = 31
GameDefaultDefaultEquipStorageSlotCount = 32
GameDefaultDefaultFishInvenSlotCount = 33
GameDefaultDefaultFishingItemInvenSlotCount = 34
GameDefaultDefaultInvenSlotCount = 35
GameDefaultDefaultRodInvenSlotCount = 36
GameDefaultDefaultStorageSlotCount = 38
GameDefaultEventAPMax = 44
GameDefaultFirstLimitGachaID = 47
GameDefaultGachaEventAddDailyPayGachaCount = 48
GameDefaultGachaEventAddFreeCount = 49
GameDefaultHuntingAPMax = 57
GameDefaultID = 58
GameDefaultLoseLikabilityPoint = 66
GameDefaultMaxEquipInvenSlotCount = 74
GameDefaultMaxEquipStorageSlotCount = 75
GameDefaultMaxFishInvenSlotCount = 76
GameDefaultMaxFreePvpTicket = 78
GameDefaultMaxInvenCost = 80
GameDefaultMaxInvenSlotCount = 81
GameDefaultMaxStorageSlotCount = 84
GameDefaultMHPresetBaseCount = 85
GameDefaultMHPresetMaxCount = 86
GameDefaultPartnerLikabilityMax = 88
GameDefaultPresetBaseCount = 92
GameDefaultPresetBuyCount = 93
GameDefaultPresetBuyID = 94
GameDefaultPresetBuyType = 95
GameDefaultPresetMaxCount = 96
GameDefaultPVPDefPresetBaseCount = 97
GameDefaultPVPDefPresetMaxCount = 98
GameDefaultPVPOffPresetBaseCount = 99
GameDefaultPVPOffPresetMaxCount = 100
GameDefaultResetDayOfWeek = 102
GameDefaultRoguelikeAPMax = 107
GameDefaultTalentSkillPinMaxCount = 114
GameDefaultTodayQuestAchievementScore = 115
GameDefaultTodayQuestLimitCount = 116
GameDefaultTodayQuestPackPostCount = 117
GameDefaultTorchLightAPMax = 118
GameDefaultTWPresetBaseCount = 119
GameDefaultTWPresetMaxCount = 120
GameDefaultUseBossHuntingAP = 126
GameDefaultUseNormalHuntingAP = 127
GameDefaultWinLikabilityPoint = 128
)
@@ -33,11 +33,11 @@ func LoadHuntingPack(root, version string, pack int) (*HuntingPack, error) {
if err := common.QueryRow("SELECT ProtoBuf FROM GameDefaultTable").Scan(&defaults); err != nil {
return nil, err
}
d.BossAP, err = optionalScalar(defaults, 121)
d.BossAP, err = optionalScalar(defaults, GameDefaultUseBossHuntingAP)
if err != nil {
return nil, err
}
d.NormalAP, err = optionalScalar(defaults, 122)
d.NormalAP, err = optionalScalar(defaults, GameDefaultUseNormalHuntingAP)
if err != nil {
return nil, err
}
@@ -22,11 +22,11 @@ func LoadHuntingAPDesign(root, version string) (HuntingAPDesign, error) {
if e = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&raw); e != nil {
return HuntingAPDesign{}, e
}
max, e := optionalScalar(raw, 56)
max, e := optionalScalar(raw, GameDefaultHuntingAPMax)
if e != nil {
return HuntingAPDesign{}, e
}
text, _, e := wire.Bytes(raw, 23)
text, _, e := wire.Bytes(raw, GameDefaultDailyResetTime)
if e != nil {
return HuntingAPDesign{}, e
}
@@ -46,7 +46,7 @@ func loadInventorySlotDesign(db *sql.DB) (*InventorySlotDesign, error) {
}
return values[0], nil
}
maxPrice, err := read(79)
maxPrice, err := read(GameDefaultMaxInvenCost)
if err != nil {
return nil, err
}
@@ -74,16 +74,16 @@ func loadInventorySlotDesign(db *sql.DB) (*InventorySlotDesign, error) {
return rule, nil
}
design := &InventorySlotDesign{}
if design.Items, err = makeRule(34, 80, 14, 13); err != nil {
if design.Items, err = makeRule(GameDefaultDefaultInvenSlotCount, GameDefaultMaxInvenSlotCount, GameDefaultAddInvenPriceType, GameDefaultAddInvenPriceCount); err != nil {
return nil, err
}
if design.Storage, err = makeRule(37, 83, 16, 15); err != nil {
if design.Storage, err = makeRule(GameDefaultDefaultStorageSlotCount, GameDefaultMaxStorageSlotCount, GameDefaultAddStoragePriceType, GameDefaultAddStoragePriceCount); err != nil {
return nil, err
}
if design.Equipment, err = makeRule(30, 73, 10, 9); err != nil {
if design.Equipment, err = makeRule(GameDefaultDefaultEquipInvenSlotCount, GameDefaultMaxEquipInvenSlotCount, GameDefaultAddEquipInvenPriceType, GameDefaultAddEquipInvenPriceCount); err != nil {
return nil, err
}
if design.EquipmentStorage, err = makeRule(31, 74, 12, 11); err != nil {
if design.EquipmentStorage, err = makeRule(GameDefaultDefaultEquipStorageSlotCount, GameDefaultMaxEquipStorageSlotCount, GameDefaultAddEquipStoragePriceType, GameDefaultAddEquipStoragePriceCount); err != nil {
return nil, err
}
return design, nil
@@ -306,11 +306,11 @@ func LoadMonsterHuntPresetDesign(root, version string) (*PresetDesign, error) {
if err = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&raw); err != nil {
return nil, err
}
d.BaseCount, err = optionalScalar(raw, 84)
d.BaseCount, err = optionalScalar(raw, GameDefaultMHPresetBaseCount)
if err != nil {
return nil, err
}
d.Maximum, err = optionalScalar(raw, 85)
d.Maximum, err = optionalScalar(raw, GameDefaultMHPresetMaxCount)
if err != nil {
return nil, err
}
+13 -1
View File
@@ -23,6 +23,18 @@ func (d PresetDesign) Validate() error {
return nil
}
// priceLikeInventory applies the client's ExpandPopupUI price for Total War
// and Colosseum preset slots: the inventory expansion price, not presetBuy*.
func (d *PresetDesign) priceLikeInventory(defaults []byte) error {
var err error
if d.PriceType, err = optionalScalar(defaults, GameDefaultAddInvenPriceType); err != nil {
return err
}
d.PriceID = 0
d.Price, err = optionalScalar(defaults, GameDefaultAddInvenPriceCount)
return err
}
func LoadPresetDesign(root, version string) (*PresetDesign, error) {
db, release, err := OpenDatabase(root, version, "common")
if err != nil {
@@ -38,7 +50,7 @@ func loadPresetDesign(db *sql.DB) (*PresetDesign, error) {
return nil, err
}
d := &PresetDesign{}
for field, target := range map[int]*uint64{91: &d.BaseCount, 92: &d.Price, 93: &d.PriceID, 94: &d.PriceType, 95: &d.Maximum} {
for field, target := range map[int]*uint64{GameDefaultPresetBaseCount: &d.BaseCount, GameDefaultPresetBuyCount: &d.Price, GameDefaultPresetBuyID: &d.PriceID, GameDefaultPresetBuyType: &d.PriceType, GameDefaultPresetMaxCount: &d.Maximum} {
v, err := optionalScalar(raw, field)
if err != nil {
return nil, err
@@ -44,7 +44,7 @@ func LoadProfileDesign(root, version string) (*ProfileDesign, error) {
if err = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&raw); err != nil {
return nil, err
}
d.DefaultPortraitCostumeID, err = optionalScalar(raw, 29)
d.DefaultPortraitCostumeID, err = optionalScalar(raw, GameDefaultDefaultCostumeID)
if err != nil {
return nil, err
}
+21 -3
View File
@@ -66,6 +66,9 @@ type PvpDesign struct {
ColosseumRules map[uint64]map[uint64][]uint64
Blesses map[uint64]ColosseumBless
Presets *PresetDesign
// MirrorPresets are the attack (index 0) and defense (index 1) preset
// slots, priced like normal party presets.
MirrorPresets [2]*PresetDesign
}
func pvpTableRows(db *sql.DB, table string, visit func([]byte) error) (err error) {
@@ -123,21 +126,36 @@ func LoadPvpDesign(root, version string) (*PvpDesign, error) {
if err = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&defaults); err != nil {
return nil, err
}
if err = pvpScalars(defaults, map[int]*uint64{20: &presets.BaseCount, 21: &presets.Maximum}); err != nil {
if err = pvpScalars(defaults, map[int]*uint64{GameDefaultColosseumPresetBaseCount: &presets.BaseCount, GameDefaultColosseumPresetMaxCount: &presets.Maximum}); err != nil {
return nil, err
}
if err = presets.priceLikeInventory(defaults); err != nil {
return nil, err
}
if err = presets.Validate(); err != nil {
return nil, err
}
var mirror [2]*PresetDesign
for side, fields := range [2][2]int{{GameDefaultPVPOffPresetBaseCount, GameDefaultPVPOffPresetMaxCount}, {GameDefaultPVPDefPresetBaseCount, GameDefaultPVPDefPresetMaxCount}} {
if mirror[side], err = loadPresetDesign(db); err != nil {
return nil, err
}
if err = pvpScalars(defaults, map[int]*uint64{fields[0]: &mirror[side].BaseCount, fields[1]: &mirror[side].Maximum}); err != nil {
return nil, err
}
if err = mirror[side].Validate(); err != nil {
return nil, err
}
}
reset, err := LoadHuntingAPDesign(root, version)
if err != nil {
return nil, err
}
var freeTickets uint64
if err = pvpScalars(defaults, map[int]*uint64{77: &freeTickets}); err != nil {
if err = pvpScalars(defaults, map[int]*uint64{GameDefaultMaxFreePvpTicket: &freeTickets}); err != nil {
return nil, err
}
d := &PvpDesign{DailyResetSeconds: reset.ResetSeconds, FreeMirrorTickets: freeTickets, Version: version, Presets: presets, MirrorRanks: map[uint64][]PvpRank{}, MirrorSeasons: map[uint64]uint64{}, ColosseumSeasons: map[uint64]uint64{}, ColosseumRankGroups: map[uint64]uint64{}, ColosseumRanks: map[uint64][]ColosseumRank{}, ColosseumRules: map[uint64]map[uint64][]uint64{}, Blesses: map[uint64]ColosseumBless{}}
d := &PvpDesign{DailyResetSeconds: reset.ResetSeconds, FreeMirrorTickets: freeTickets, Version: version, Presets: presets, MirrorPresets: mirror, MirrorRanks: map[uint64][]PvpRank{}, MirrorSeasons: map[uint64]uint64{}, ColosseumSeasons: map[uint64]uint64{}, ColosseumRankGroups: map[uint64]uint64{}, ColosseumRanks: map[uint64][]ColosseumRank{}, ColosseumRules: map[uint64]map[uint64][]uint64{}, Blesses: map[uint64]ColosseumBless{}}
loaders := []struct {
table string
visit func([]byte) error
@@ -41,12 +41,12 @@ func LoadRosterProgressDesign(root, version string) (*RosterProgressDesign, erro
if err = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&raw); err != nil {
return nil, err
}
d.PartnerMaximum, err = optionalScalar(raw, 87)
d.PartnerMaximum, err = optionalScalar(raw, GameDefaultPartnerLikabilityMax)
if err != nil || d.PartnerMaximum == 0 {
return nil, fmt.Errorf("gamedata: invalid partner maximum")
}
d.WinPoint, _ = optionalScalar(raw, 123)
d.LosePoint, _ = optionalScalar(raw, 65)
d.WinPoint, _ = optionalScalar(raw, GameDefaultWinLikabilityPoint)
d.LosePoint, _ = optionalScalar(raw, GameDefaultLoseLikabilityPoint)
read := func(table string, visit func([]byte) error) error { return readCashMetadata(db, table, visit) }
rewards := func(raw []byte, count, id, typ int) ([]Reward, error) {
a, e := packedInts(raw, count)
@@ -32,7 +32,7 @@ func LoadTodayQuests(root, version string) (*TodayQuestCatalog, error) {
if err = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&defaults); err != nil {
return nil, err
}
for field, dst := range map[int]*int{110: &c.AchievementScore, 111: &c.Limit, 112: &c.PostCount} {
for field, dst := range map[int]*int{GameDefaultTodayQuestAchievementScore: &c.AchievementScore, GameDefaultTodayQuestLimitCount: &c.Limit, GameDefaultTodayQuestPackPostCount: &c.PostCount} {
v, e := optionalScalar(defaults, field)
if e != nil || v == 0 || v > 2147483647 {
return nil, fmt.Errorf("gamedata: invalid today defaults %d", field)
@@ -16,10 +16,13 @@ func loadTotalWarPresetDesign(root, version string) (*PresetDesign, error) {
if err = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&raw); err != nil {
return nil, err
}
if d.BaseCount, err = optionalScalar(raw, 114); err != nil {
if d.BaseCount, err = optionalScalar(raw, GameDefaultTWPresetBaseCount); err != nil {
return nil, err
}
if d.Maximum, err = optionalScalar(raw, 115); err != nil {
if d.Maximum, err = optionalScalar(raw, GameDefaultTWPresetMaxCount); err != nil {
return nil, err
}
if err = d.priceLikeInventory(raw); err != nil {
return nil, err
}
if err = d.Validate(); err != nil {
@@ -37,6 +37,7 @@ type Service struct {
consumeFieldBuff func(ctx command.Context, _ string) error
externalResume func(command.Context, uint64, string) ([]byte, error)
abandonment func(command.Context, string) error
recordCodes RecordCodeLookup
}
type FieldMonsterRuntime interface {
BeginFieldMonsterBattle(ctx command.Context, _ int, _ uint64, _ uint64) (string, bool, error)
@@ -53,11 +53,12 @@ func (s *Service) handle(ctx command.Context, path string, request []byte) (int,
next := state.Phases[state.Phase+1]
response := wire.AppendVarint(nil, 1, next.GroupID)
response = wire.AppendVarint(response, 2, next.ID)
// The client starts the next phase at TurnCount + 1.
response = wire.AppendVarint(response, 6, state.Round)
response = wire.AppendVarint(response, 8, next.DeckID)
// The local engine does not simulate combat. With verification disabled
// and no battle_result the client explicitly preserves its blue team;
// fabricating a verified result would overwrite HP, SP and action state.
// Dynamic official turn/SP values are not available in this request.
state.Phase++
state.Index, state.Deck, state.PhaseStarted = next.DeckID, next.DeckID, false
state.PhaseSeq, state.PhaseReply = seq, append([]byte(nil), response...)
@@ -1,6 +1,7 @@
package pvp
import (
"bd2server/internal/common/util"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
@@ -15,6 +16,13 @@ func (s *Service) matching(ctx command.Context, mode Mode, request []byte) ([]by
if e != nil {
return nil, e
}
direct := false
if mode == Colosseum {
direct, e = s.directMatching(season.ID)
if e != nil {
return nil, e
}
}
m := s.state.Modes[mode]
if err := s.reconcile(); err != nil {
return nil, err
@@ -23,6 +31,9 @@ func (s *Service) matching(ctx command.Context, mode Mode, request []byte) ([]by
return nil, fmt.Errorf("pvp: pending settlements must be projected before another match")
}
if m.Active != nil && m.Active.Season == season.ID {
if mode == Colosseum {
return colosseumMatching(m.Active, direct), nil
}
return append([]byte(nil), m.Active.MatchReply...), nil
}
if len(m.Attack.Deck) == 0 {
@@ -63,6 +74,9 @@ func (s *Service) matching(ctx command.Context, mode Mode, request []byte) ([]by
if count == 0 || count > 100 {
return nil, fmt.Errorf("pvp: unsupported matching count")
}
if direct {
count = 1
}
firstAttack := uint64(1)
if mode == Colosseum {
values, e := s.rules.Design.ColosseumRule(season.ID, 13)
@@ -110,10 +124,14 @@ func (s *Service) matching(ctx command.Context, mode Mode, request []byte) ([]by
if mode == Mirror {
c.Selected = accepted[0].Profile.OwnerIndex
c.Started = false
} else if firstAttack == 0 {
c.FirstAttack = 1 + seed%2
} else {
c.FirstAttack = firstAttack
c.FirstAttack, e = firstAttackTeam(firstAttack, util.RandomUint64N)
if e != nil {
return nil, e
}
if direct {
c.Selected = accepted[0].Profile.OwnerIndex
}
}
if e = s.spendTickets(ctx, mode, season.ID, "pvp:challenge:"+c.ID, multiplier); e != nil {
return nil, e
@@ -121,7 +139,7 @@ func (s *Service) matching(ctx command.Context, mode Mode, request []byte) ([]by
if mode == Mirror {
c.MatchReply = mirrorMatching(c)
} else {
c.MatchReply = colosseumMatching(c)
c.MatchReply = colosseumMatching(c, direct)
}
if s.preparation != nil {
if err := s.preparation(ctx, mode, c.ID, cloneSnapshot(c.Attacker), append([]byte(nil), request...)); err != nil {
@@ -157,10 +175,20 @@ func (s *Service) start(ctx command.Context, mode Mode, request []byte) ([]byte,
}
return wire.AppendVarint(nil, 1, seed), nil
}
direct, e := s.directMatching(season.ID)
if e != nil {
return nil, e
}
owner, e := scalar(request, 2)
if e != nil || owner == 0 {
if e != nil || direct && owner != 0 || !direct && owner == 0 {
return nil, fmt.Errorf("pvp: invalid selected opponent")
}
if direct {
if len(c.Candidates) == 0 {
return nil, fmt.Errorf("pvp: direct challenge has no matched opponent")
}
owner = c.Candidates[0].Profile.OwnerIndex
}
if c.Started && c.Selected != owner {
return nil, fmt.Errorf("pvp: challenge opponent already selected")
}
@@ -384,3 +412,25 @@ func (s *Service) claim(ctx command.Context, mode Mode) ([]byte, error) {
}
return nil, fmt.Errorf("pvp: no unclaimed season entitlement")
}
func (s *Service) directMatching(season uint64) (bool, error) {
values, err := s.rules.Design.ColosseumRule(season, 3)
if err != nil || len(values) != 1 || values[0] > 1 {
return false, fmt.Errorf("pvp: invalid matching type")
}
return values[0] == 0, nil
}
func firstAttackTeam(rule uint64, draw func(uint64) (uint64, error)) (uint64, error) {
if rule == 0 {
value, err := draw(2)
if err != nil {
return 0, err
}
return 1 + value, nil
}
if rule > 2 {
return 0, fmt.Errorf("pvp: invalid first attack rule")
}
return rule, nil
}
@@ -0,0 +1,155 @@
package pvp
import (
"bytes"
"encoding/json"
"errors"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/stateio"
)
// The turn draw is independent of challenge IDs and battle replay seeds.
func TestFirstAttackTeamUsesBothOutcomesAndPreservesAuthoredRules(t *testing.T) {
for _, draw := range []uint64{0, 1} {
team, err := firstAttackTeam(0, func(limit uint64) (uint64, error) {
if limit != 2 {
t.Fatalf("turn draw upper bound=%d, want 2", limit)
}
return draw, nil
})
if err != nil || team != draw+1 {
t.Fatalf("draw %d: team=%d err=%v", draw, team, err)
}
}
for _, rule := range []uint64{1, 2} {
team, err := firstAttackTeam(rule, func(uint64) (uint64, error) {
t.Fatal("fixed turn rule unexpectedly drew randomness")
return 0, nil
})
if err != nil || team != rule {
t.Fatalf("fixed rule %d: team=%d err=%v", rule, team, err)
}
}
failure := errors.New("entropy unavailable")
if _, err := firstAttackTeam(0, func(uint64) (uint64, error) { return 0, failure }); !errors.Is(err, failure) {
t.Fatalf("entropy error was not propagated: %v", err)
}
}
type challengeSource struct {
Source
candidates []PublishedSnapshot
calls int
}
func (s *challengeSource) Candidates(CandidateQuery) ([]PublishedSnapshot, error) {
s.calls++
return s.candidates, nil
}
func (s *challengeSource) Personal(ProgressQuery) (PersonalProgress, error) {
return PersonalProgress{Found: true, VP: 1200}, nil
}
func (s *challengeSource) Ranking(RankQuery) ([]RankEntry, error) { return nil, nil }
// CmDirect sends no enemy before commitment, then starts with owner_index=0.
// CmChoice retains its native explicit selection flow for authored seasons.
func TestColosseumMatchingKeepsOpponentTurnSeedAndTicketAcrossReload(t *testing.T) {
for _, matchType := range []uint64{0, 1} {
t.Run(map[uint64]string{0: "direct", 1: "choice"}[matchType], func(t *testing.T) {
ctx := command.Context{Identity: command.Identity{AccountID: "alice", SessionID: "s"}, State: stateio.NewMemory()}
entry := func(index uint64) []byte {
return wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, index), 3, 1), 4, 100+index)
}
deck := entry(1)
enemy := PublishedSnapshot{Profile: Profile{OwnerID: "bob", OwnerIndex: 2, Name: "Bob"}, Mode: Colosseum, Season: 1, Version: 1, VP: 1300,
Snapshot: FullSnapshot{FullDeck: wire.AppendBytes(nil, 1, entry(2))}}
other := PublishedSnapshot{Profile: Profile{OwnerID: "cara", OwnerIndex: 3, Name: "Cara"}, Mode: Colosseum, Season: 1, Version: 1, VP: 1400,
Snapshot: FullSnapshot{FullDeck: wire.AppendBytes(nil, 1, entry(3))}}
source := &challengeSource{candidates: []PublishedSnapshot{enemy, other}}
spends := 0
service := &Service{profile: Profile{OwnerID: "alice", OwnerIndex: 1}, source: source, now: func() time.Time { return time.UnixMilli(100) },
rules: &Rules{Seasons: []Season{{Mode: Colosseum, ID: 1, Start: 1, End: 1000}}, Design: &gamedata.PvpDesign{
ColosseumSeasons: map[uint64]uint64{1: 1}, ColosseumRules: map[uint64]map[uint64][]uint64{1: {1: {5, 5}, 2: {7}, 3: {matchType}, 4: {2}, 9: {3}, 13: {0}}}}},
state: state{Version: 1, Modes: map[Mode]*modeState{Colosseum: {Attack: formation{Version: 1, Deck: [][]byte{deck}, Snapshot: FullSnapshot{FullDeck: wire.AppendBytes(nil, 1, deck)}}, Progress: map[string]progress{}, Pending: map[string]pendingResult{}}}},
balance: func(command.Context, uint64) (uint64, error) { return 3, nil },
spend: func(_ command.Context, _ string, costs []gamedata.BattleReward) error {
if len(costs) != 1 || costs[0].Type != 52 || costs[0].Count != 1 {
t.Fatalf("matching ticket costs=%+v", costs)
}
spends++
return nil
},
}
matched, err := service.matching(ctx, Colosseum, nil)
if err != nil {
t.Fatal(err)
}
enemies, err := messages(matched, 3)
if err != nil || matchType == 0 && len(enemies) != 0 || matchType == 1 && len(enemies) != 2 {
t.Fatalf("matching type %d enemy disclosure=%x err=%v", matchType, enemies, err)
}
wantCandidates := 1
if matchType == 1 {
wantCandidates = 2
}
if got := len(service.state.Modes[Colosseum].Active.Candidates); got != wantCandidates {
t.Fatalf("persisted %d candidates for matching type %d, want %d", got, matchType, wantCandidates)
}
turn, _ := scalar(matched, 4)
if turn != 1 && turn != 2 {
t.Fatalf("invalid first attack team %d", turn)
}
seed := service.state.Modes[Colosseum].Active.Seed
source.candidates = nil
// Reopen the saved state, then request IsReload=true with a new sequence.
raw, _, err := ctx.State.LoadEntry("pvp", "state", "core")
if err != nil || json.Unmarshal(raw, &service.state) != nil {
t.Fatalf("cannot reopen issued challenge: %v", err)
}
repeated, err := service.matching(ctx, Colosseum, wire.AppendVarint(nil, 2, 1))
if err != nil || !bytes.Equal(matched, repeated) || source.calls != 1 || spends != 1 {
t.Fatalf("reload rematched or charged again: calls=%d spends=%d err=%v", source.calls, spends, err)
}
if _, err := service.start(ctx, Colosseum, wire.AppendVarint(nil, 2, 99)); err == nil {
t.Fatal("caller replaced the committed opponent")
}
var selection []byte
wantOwner, wantVP := uint64(2), uint64(1300)
if matchType == 1 {
if _, err := service.start(ctx, Colosseum, nil); err == nil {
t.Fatal("choice matching accepted a missing selected owner")
}
selection = wire.AppendVarint(nil, 2, 3)
wantOwner, wantVP = 3, 1400
}
started, err := service.start(ctx, Colosseum, selection)
if err != nil {
t.Fatal(err)
}
selected, err := messages(started, 3)
if err != nil || len(selected) != 1 {
t.Fatalf("start enemy=%x err=%v", selected, err)
}
owner, _ := scalar(selected[0], 1)
vp, _ := scalar(selected[0], 4)
battleSeed, _ := scalar(selected[0], 15)
active := service.state.Modes[Colosseum].Active
if owner != wantOwner || vp != wantVP || battleSeed != seed || active.FirstAttack != turn || !active.Started || active.Selected != wantOwner {
t.Fatal("start changed the matched opponent, turn, score or replay seed")
}
if matchType == 1 {
if _, err := service.start(ctx, Colosseum, wire.AppendVarint(nil, 2, 2)); err == nil {
t.Fatal("started choice challenge switched to another matched candidate")
}
}
if replay, err := service.start(ctx, Colosseum, selection); err != nil || !bytes.Equal(started, replay) || spends != 1 {
t.Fatalf("start retry changed its result or charged again: %v", err)
}
})
}
}
+115 -44
View File
@@ -8,12 +8,37 @@ import (
"math"
"sort"
"strconv"
"strings"
"unicode/utf8"
)
func (s *Service) validatePreset(ctx command.Context, raw []byte) error {
// presetBook is one independently sized list of stored formations. Colosseum
// has one; PvP has an attack and a defense list selected by the request's
// Define_CommonBattleDeckType, which shifts every later request field by one.
type presetBook struct {
mode Mode
side uint64
bucket string
slots *uint64
design *gamedata.PresetDesign
// offset is added to the Colosseum request field numbers.
offset int
}
func (s *Service) colosseumPresets() presetBook {
return presetBook{mode: Colosseum, bucket: "presets", slots: &s.state.PresetSlots, design: s.rules.Design.Presets}
}
func (s *Service) mirrorPresets(side uint64) (presetBook, error) {
if side > 1 {
return presetBook{}, fmt.Errorf("pvp: invalid preset deck type")
}
return presetBook{mode: Mirror, side: side, bucket: [2]string{"mirror_attack_presets", "mirror_defense_presets"}[side], slots: &s.state.MirrorPresetSlots[side], design: s.rules.Design.MirrorPresets[side], offset: 1}, nil
}
func (s *Service) validatePreset(ctx command.Context, book presetBook, raw []byte) error {
slot, e := scalar(raw, 4)
if e != nil || slot >= s.state.PresetSlots {
if e != nil || slot >= *book.slots {
return fmt.Errorf("pvp: preset slot unavailable")
}
name, _, e := wire.Bytes(raw, 1)
@@ -21,7 +46,7 @@ func (s *Service) validatePreset(ctx command.Context, raw []byte) error {
return fmt.Errorf("pvp: invalid preset name")
}
icon, e := scalar(raw, 2)
if e != nil || icon != 0 && !s.rules.Design.Presets.Icons[icon] {
if e != nil || icon != 0 && !book.design.Icons[icon] {
return fmt.Errorf("pvp: invalid preset icon")
}
color, e := scalar(raw, 3)
@@ -46,7 +71,21 @@ func (s *Service) validatePreset(ctx command.Context, raw []byte) error {
if e != nil {
return e
}
deck = append(deck, wire.AppendVarint(append([]byte(nil), base...), 4, costume))
member := wire.AppendVarint(append([]byte(nil), base...), 4, costume)
if book.mode == Mirror {
// PvpPresetDeckDBInfo costume_seq 4 and priority_skill 5 are the
// formation's PvpBattleUserDeckInfo fields 5 and 6.
for from, to := range map[int]int{4: 5, 5: 6} {
skills, e := messages(entry, from)
if e != nil {
return e
}
for _, skill := range skills {
member = wire.AppendBytes(member, to, skill)
}
}
}
deck = append(deck, member)
refs, e := messages(entry, 3)
if e != nil {
return e
@@ -65,79 +104,108 @@ func (s *Service) validatePreset(ctx command.Context, raw []byte) error {
}
contents = append(contents, item)
}
season, e := s.current(Colosseum)
season, e := s.current(book.mode)
if e != nil {
return e
}
if e = s.validateDeck(Colosseum, season.ID, deck); e != nil {
if e = s.validateDeck(book.mode, season.ID, deck); e != nil {
return e
}
// Preset storage never changes the live formation or publishes a defense.
_, e = s.builder.Freeze(ctx, FreezeRequest{Mode: Colosseum, Season: season.ID, Deck: deck, Contents: contents, Renew: false})
_, e = s.builder.Freeze(ctx, FreezeRequest{Mode: book.mode, Season: season.ID, Deck: deck, Contents: contents, Renew: false})
return e
}
func (s *Service) listPresets(ctx command.Context, book presetBook) ([][]byte, error) {
entries, e := ctx.State.ListEntries("pvp", book.bucket)
if e != nil {
return nil, e
}
slots := make([]int, 0, len(entries))
for key := range entries {
slot, e := strconv.Atoi(key)
if e != nil || slot < 0 || uint64(slot) >= *book.slots {
return nil, fmt.Errorf("pvp: corrupt preset slot")
}
slots = append(slots, slot)
}
sort.Ints(slots)
out := make([][]byte, 0, len(slots))
for _, slot := range slots {
out = append(out, entries[strconv.Itoa(slot)])
}
return out, nil
}
func (s *Service) preset(ctx command.Context, path string, request []byte) ([]byte, error) {
if path == "/PvpPresetInfo" {
var out []byte
for side := range uint64(2) {
book, _ := s.mirrorPresets(side)
presets, e := s.listPresets(ctx, book)
if e != nil {
return nil, e
}
out = addMessages(out, int(side)+1, presets)
}
out = wire.AppendVarint(out, 3, s.state.MirrorPresetSlots[0])
return wire.AppendVarint(out, 4, s.state.MirrorPresetSlots[1]), nil
}
book := s.colosseumPresets()
if path == "/ColosseumPresetInfo" {
entries, e := ctx.State.ListEntries("pvp", "presets")
presets, e := s.listPresets(ctx, book)
return addMessages(nil, 1, presets), e
}
if strings.HasPrefix(path, "/PvpPreset") {
side, e := scalar(request, 2)
if e != nil {
return nil, e
}
slots := make([]int, 0, len(entries))
for key := range entries {
slot, e := strconv.Atoi(key)
if e != nil || slot < 0 || uint64(slot) >= s.state.PresetSlots {
return nil, fmt.Errorf("pvp: corrupt preset slot")
}
slots = append(slots, slot)
if book, e = s.mirrorPresets(side); e != nil {
return nil, e
}
sort.Ints(slots)
var out []byte
for _, slot := range slots {
out = wire.AppendBytes(out, 1, entries[strconv.Itoa(slot)])
}
return out, nil
}
field := func(n int) int { return n + book.offset }
switch path {
case "/ColosseumPresetSave":
raw, exists, e := wire.Bytes(request, 2)
case "/ColosseumPresetSave", "/PvpPresetSave":
raw, exists, e := wire.Bytes(request, field(2))
if e != nil || !exists {
return nil, fmt.Errorf("pvp: missing preset")
}
if e = s.validatePreset(ctx, raw); e != nil {
if e = s.validatePreset(ctx, book, raw); e != nil {
return nil, e
}
slot, _ := scalar(raw, 4)
return nil, ctx.State.PutEntry("pvp", "presets", strconv.FormatUint(slot, 10), raw)
case "/ColosseumPresetDelete":
slots, e := ints(request, 2)
return nil, ctx.State.PutEntry("pvp", book.bucket, strconv.FormatUint(slot, 10), raw)
case "/ColosseumPresetDelete", "/PvpPresetDelete":
slots, e := ints(request, field(2))
if e != nil {
return nil, e
}
for _, slot := range slots {
if slot >= s.state.PresetSlots {
if slot >= *book.slots {
return nil, fmt.Errorf("pvp: invalid delete slot")
}
}
for _, slot := range slots {
if _, e = ctx.State.DeleteEntry("pvp", "presets", strconv.FormatUint(slot, 10)); e != nil {
if _, e = ctx.State.DeleteEntry("pvp", book.bucket, strconv.FormatUint(slot, 10)); e != nil {
return nil, e
}
}
return nil, nil
case "/ColosseumPresetInfoChange":
slot, e := scalar(request, 5)
if e != nil || slot >= s.state.PresetSlots {
case "/ColosseumPresetInfoChange", "/PvpPresetInfoChange":
slot, e := scalar(request, field(5))
if e != nil || slot >= *book.slots {
return nil, fmt.Errorf("pvp: unavailable preset slot")
}
raw, exists, e := ctx.State.LoadEntry("pvp", "presets", strconv.FormatUint(slot, 10))
raw, exists, e := ctx.State.LoadEntry("pvp", book.bucket, strconv.FormatUint(slot, 10))
if e != nil {
return nil, e
}
if !exists {
raw = wire.AppendVarint(nil, 4, slot)
}
name, _, e := wire.Bytes(request, 2)
name, _, e := wire.Bytes(request, field(2))
if e != nil {
return nil, e
}
@@ -148,32 +216,35 @@ func (s *Service) preset(ctx command.Context, path string, request []byte) ([]by
if !exists {
raw = wire.AppendBytes(raw, 1, name)
}
for field := 2; field <= 3; field++ {
value, e := scalar(request, field+1)
for target := 2; target <= 3; target++ {
value, e := scalar(request, field(target+1))
if e != nil {
return nil, e
}
raw, _, e = wire.ReplaceVarint(raw, field, value)
raw, _, e = wire.ReplaceVarint(raw, target, value)
if e != nil {
return nil, e
}
}
if e = s.validatePreset(ctx, raw); e != nil {
if e = s.validatePreset(ctx, book, raw); e != nil {
return nil, e
}
return nil, ctx.State.PutEntry("pvp", "presets", strconv.FormatUint(slot, 10), raw)
case "/ColosseumPresetSlotAdd":
count, e := scalar(request, 2)
d := s.rules.Design.Presets
if e != nil || count == 0 || count > d.Maximum || s.state.PresetSlots > d.Maximum-count || count > math.MaxUint64/d.Price {
return nil, ctx.State.PutEntry("pvp", book.bucket, strconv.FormatUint(slot, 10), raw)
case "/ColosseumPresetSlotAdd", "/PvpPresetSlotAdd":
count, e := scalar(request, field(2))
d := book.design
if e != nil || count == 0 || count > d.Maximum || *book.slots > d.Maximum-count || count > math.MaxUint64/d.Price {
return nil, fmt.Errorf("pvp: invalid preset slot purchase")
}
seq, _ := scalar(request, 1)
id := fmt.Sprintf("pvp:preset:%s:%s:%d", s.profile.OwnerID, ctx.SessionID, seq)
if book.mode == Mirror {
id = fmt.Sprintf("pvp:mirror-preset:%d:%s:%s:%d", book.side, s.profile.OwnerID, ctx.SessionID, seq)
}
if e = s.spend(ctx, id, []gamedata.BattleReward{{Type: d.PriceType, ID: d.PriceID, Count: d.Price * count}}); e != nil {
return nil, e
}
s.state.PresetSlots += count
*book.slots += count
return nil, s.save(ctx)
}
return nil, fmt.Errorf("pvp: unknown preset operation")
@@ -0,0 +1,114 @@
package pvp
import (
"math"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/stateio"
)
type presetBuilder struct{ requests []FreezeRequest }
func (b *presetBuilder) Freeze(_ command.Context, r FreezeRequest) (FullSnapshot, error) {
b.requests = append(b.requests, r)
return FullSnapshot{}, nil
}
func presetValue(raw []byte, field int) uint64 { v, _ := scalar(raw, field); return v }
func mirrorPreset(slot uint64, name string) []byte {
base := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, 1), 2, 2), 3, 1)
skill := wire.AppendVarint(wire.AppendVarint(nil, 1, 101), 2, 1)
deck := wire.AppendBytes(nil, 1, base)
deck = wire.AppendVarint(deck, 2, 101)
deck = wire.AppendBytes(deck, 4, skill)
deck = wire.AppendBytes(deck, 5, skill)
raw := wire.AppendString(nil, 1, name)
raw = wire.AppendVarint(raw, 2, 7)
raw = wire.AppendVarint(raw, 3, 1)
raw = wire.AppendVarint(raw, 4, slot)
return wire.AppendBytes(raw, 5, deck)
}
// 2.38.11 PvP presets keep separate attack and defense lists, each with its
// own GameData slot count, priced like normal presets, and are validated as
// mirror formations including costume skill order and priority skills.
func TestMirrorPresetsKeepAttackAndDefenseListsApart(t *testing.T) {
design := func() *gamedata.PresetDesign {
return &gamedata.PresetDesign{BaseCount: 5, Maximum: 10, PriceType: 4, Price: 2000, Icons: map[uint64]bool{7: true}}
}
builder := &presetBuilder{}
var spent []gamedata.BattleReward
s := &Service{
rules: &Rules{Seasons: []Season{{Mode: Mirror, ID: 1, Start: 0, End: math.MaxInt64}}, Design: &gamedata.PvpDesign{Presets: design(), MirrorPresets: [2]*gamedata.PresetDesign{design(), design()}}},
profile: Profile{OwnerID: "alice"},
source: &progressSource{},
builder: builder,
spend: func(_ command.Context, _ string, costs []gamedata.BattleReward) error {
spent = append(spent, costs...)
return nil
},
now: func() time.Time { return time.UnixMilli(100) },
state: state{Version: 1, Modes: map[Mode]*modeState{Mirror: {Progress: map[string]progress{}, Pending: map[string]pendingResult{}}, Colosseum: {Progress: map[string]progress{}, Pending: map[string]pendingResult{}}}, PresetSlots: 5, MirrorPresetSlots: [2]uint64{5, 5}},
}
ctx := command.Context{Identity: command.Identity{AccountID: "alice", SessionID: "s"}, State: stateio.NewMemory()}
call := func(path string, fields []byte) ([]byte, error) {
return s.preset(ctx, path, append(wire.AppendVarint(nil, 1, 1), fields...))
}
if _, err := call("/PvpPresetSave", wire.AppendBytes(wire.AppendVarint(nil, 2, 0), 3, mirrorPreset(0, "A"))); err != nil {
t.Fatal(err)
}
if len(builder.requests) != 1 || builder.requests[0].Mode != Mirror || len(builder.requests[0].Deck) != 1 {
t.Fatalf("attack preset was not validated as a mirror formation: %+v", builder.requests)
}
if seq, _ := messages(builder.requests[0].Deck[0], 5); len(seq) != 1 {
t.Fatal("costume skill order did not reach formation validation")
}
if priority, _ := messages(builder.requests[0].Deck[0], 6); len(priority) != 1 {
t.Fatal("priority skills did not reach formation validation")
}
if _, err := call("/PvpPresetSave", wire.AppendBytes(wire.AppendVarint(nil, 2, 1), 3, mirrorPreset(4, "B"))); err != nil {
t.Fatal(err)
}
info, err := call("/PvpPresetInfo", nil)
if err != nil {
t.Fatal(err)
}
attack, _ := messages(info, 1)
defense, _ := messages(info, 2)
if len(attack) != 1 || len(defense) != 1 || presetValue(info, 3) != 5 || presetValue(info, 4) != 5 || presetValue(defense[0], 4) != 4 {
t.Fatalf("preset info %x", info)
}
rename := wire.AppendVarint(nil, 2, 1)
rename = wire.AppendString(rename, 3, "D")
rename = wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(rename, 4, 7), 5, 2), 6, 4)
if _, err = call("/PvpPresetInfoChange", rename); err != nil {
t.Fatal(err)
}
if _, err = call("/PvpPresetDelete", wire.AppendBytes(wire.AppendVarint(nil, 2, 0), 3, []byte{0})); err != nil {
t.Fatal(err)
}
if _, err = call("/PvpPresetSlotAdd", wire.AppendVarint(wire.AppendVarint(nil, 2, 1), 3, 2)); err != nil {
t.Fatal(err)
}
if len(spent) != 1 || spent[0].Type != 4 || spent[0].Count != 4000 || s.state.MirrorPresetSlots != [2]uint64{5, 7} {
t.Fatalf("slot purchase spent %+v, slots %v", spent, s.state.MirrorPresetSlots)
}
info, _ = call("/PvpPresetInfo", nil)
attack, _ = messages(info, 1)
defense, _ = messages(info, 2)
name, _, _ := wire.Bytes(defense[0], 1)
if len(attack) != 0 || len(defense) != 1 || string(name) != "D" || presetValue(defense[0], 3) != 2 || presetValue(info, 4) != 7 {
t.Fatalf("preset info after edits %x", info)
}
if _, err = call("/PvpPresetSave", wire.AppendBytes(wire.AppendVarint(nil, 2, 0), 3, mirrorPreset(5, "C"))); err == nil {
t.Fatal("attack preset saved beyond its slots")
}
if _, err = call("/PvpPresetSave", wire.AppendBytes(wire.AppendVarint(nil, 2, 2), 3, mirrorPreset(0, "C"))); err == nil {
t.Fatal("unknown deck type accepted")
}
}
@@ -17,10 +17,11 @@ import (
var codes = map[string]int{
"/ColosseumPromotionRewardInfo": 0,
"/PvpBattleReplayInfo": 0, "/PvpBattleReset": 0,
"/PvpBattleReplayInfo": 0, "/PvpBattleReset": 0,
"/PvpBattleUserInfo": 86, "/PvpBattleDeckInfo": 87, "/PvpBattleDeckSave": 88, "/PvpBattleMatching": 89, "/PvpBattleStart": 90, "/PvpBattleEnd": 91, "/PvpBattleReward": 92, "/PvpBattleRanking": 93, "/PvpBattleRankUserDetail": 94, "/PvpBattleHistory": 97, "/PvpBattleHistoryDeckInfo": 98, "/PvpSeasonReward": 136, "/PvpBattleOnceRewardInfo": 277, "/PvpContentsItemRenew": 401,
"/ColosseumUserInfo": 473, "/ColosseumSeasonReward": 474, "/ColosseumDeckInfo": 475, "/ColosseumDeckSave": 476, "/ColosseumContentsItemRenew": 478, "/ColosseumRanking": 479, "/ColosseumRankDetail": 480, "/ColosseumBattleHistory": 481, "/ColosseumBattleReplayInfo": 482, "/ColosseumBattleMatching": 483, "/ColosseumBattleStart": 484, "/ColosseumBattleEnd": 485, "/ColosseumBlessInfo": 486, "/ColosseumBlessSave": 487, "/ColosseumBattleCountReset": 488, "/ColosseumApBuy": 489,
"/ColosseumPresetInfo": 493, "/ColosseumPresetSave": 494, "/ColosseumPresetDelete": 495, "/ColosseumPresetSlotAdd": 496, "/ColosseumPresetInfoChange": 497,
"/PvpPresetInfo": 655, "/PvpPresetSave": 656, "/PvpPresetDelete": 657, "/PvpPresetInfoChange": 658, "/PvpPresetSlotAdd": 659,
}
type receipt struct{ Request, Response []byte }
@@ -82,7 +83,7 @@ func mutates(path string) bool {
}
func (s *Service) handle(ctx command.Context, mode Mode, path string, request []byte) ([]byte, error) {
if strings.HasPrefix(path, "/ColosseumPreset") {
if strings.HasPrefix(path, "/ColosseumPreset") || strings.HasPrefix(path, "/PvpPreset") {
return s.preset(ctx, path, request)
}
m := s.state.Modes[mode]
@@ -329,11 +330,13 @@ func colosseumEnemy(enemy PublishedSnapshot, seed uint64) []byte {
out = wire.AppendVarint(out, 15, seed)
return appendDouble(out, 16, enemy.TopPercent)
}
func colosseumMatching(c *challenge) []byte {
func colosseumMatching(c *challenge, direct bool) []byte {
out := wire.AppendVarint(nil, 1, c.Attacker.VP)
out = wire.AppendVarint(out, 2, c.Attacker.Rank)
for _, enemy := range c.Candidates {
out = wire.AppendBytes(out, 3, colosseumEnemy(enemy, c.Seed))
if !direct {
for _, enemy := range c.Candidates {
out = wire.AppendBytes(out, 3, colosseumEnemy(enemy, c.Seed))
}
}
return wire.AppendVarint(out, 4, c.FirstAttack)
}
@@ -1,11 +1,11 @@
package pvp
import (
"bd2server/internal/common/util"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
party "bd2server/internal/server/domain/roster/formation"
"bd2server/internal/server/protocol/wire"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
@@ -24,7 +24,7 @@ type Rules struct {
}
func NewRules(d *gamedata.PvpDesign, seasons []Season, policy ScorePolicy) (*Rules, error) {
if d == nil || d.Presets == nil || policy == nil || len(seasons) == 0 {
if d == nil || d.Presets == nil || d.MirrorPresets[0] == nil || d.MirrorPresets[1] == nil || policy == nil || len(seasons) == 0 {
return nil, fmt.Errorf("pvp: incomplete rules")
}
seen := map[string]bool{}
@@ -40,7 +40,7 @@ func NewRules(d *gamedata.PvpDesign, seasons []Season, policy ScorePolicy) (*Rul
return nil, err
}
case Colosseum:
for _, kind := range []uint64{1, 2, 4, 9, 11, 13, 14, 15, 26, 30, 31} {
for _, kind := range []uint64{1, 2, 3, 4, 9, 11, 13, 14, 15, 26, 30, 31} {
values, err := d.ColosseumRule(s.ID, kind)
if err != nil || len(values) == 0 && kind != 30 && kind != 31 {
return nil, fmt.Errorf("pvp: incomplete colosseum season %d rule %d", s.ID, kind)
@@ -102,6 +102,8 @@ type state struct {
Version int
Modes map[Mode]*modeState
PresetSlots uint64
// MirrorPresetSlots are the PvP attack and defense preset slot counts.
MirrorPresetSlots [2]uint64
}
type Service struct {
preparation func(command.Context, Mode, string, PublishedSnapshot, []byte) error
@@ -132,6 +134,12 @@ func Open(ctx command.Context, rules *Rules, profile Profile, source Source, bui
return nil, fmt.Errorf("pvp: invalid player state")
}
}
for side, d := range rules.Design.MirrorPresets {
// States saved before 2.38.11 start with the design's free slots.
if s.state.MirrorPresetSlots[side] == 0 {
s.state.MirrorPresetSlots[side] = d.BaseCount
}
}
for _, mode := range []Mode{Mirror, Colosseum} {
if s.state.Modes[mode] == nil {
s.state.Modes[mode] = &modeState{Progress: map[string]progress{}, Pending: map[string]pendingResult{}}
@@ -278,11 +286,11 @@ func publish(ctx command.Context, id, topic string, payload any) error {
return ctx.Publish(command.Event{ID: id, Topic: topic, Payload: raw})
}
func randomID() (uint64, error) {
var b [8]byte
if _, e := rand.Read(b[:]); e != nil {
return 0, e
value, err := util.RandomUint64N(math.MaxInt64)
if err != nil {
return 0, err
}
return binary.LittleEndian.Uint64(b[:])&math.MaxInt64 | 1, nil
return value + 1, nil
}
func cloneSnapshot(p PublishedSnapshot) PublishedSnapshot {
p.Snapshot.FullDeck = append([]byte(nil), p.Snapshot.FullDeck...)
Loaded 100 of 250 files, more files were not shown because too many files have changed in this diff. Show more