Compare commits

...
Author SHA1 Message Date
Flechazo 045f7ac193 chore(all): release client 0.2.19 and server 0.2.6 for game 2.38.11
release notes / releases (push) Successful in 2s
2026-11-12 17:40:20 +08:00
Flechazo bae82a859b feat(client): register plugins dynamically and add BetterExperience with audio and inventory fixes 2026-11-12 17:40:19 +08:00
Flechazo 7da29e7bee refactor(all): localize source comparison and release messages 2026-11-12 17:39:25 +08:00
Flechazo 7d3b670896 build(server): separate dev and beta snapshot deployments 2026-11-12 17:39:25 +08:00
Flechazo dec353c3a2 feat(server): complete draws, presets, rewards and unlocks with localized diagnostics 2026-11-12 17:39:20 +08:00
Flechazo 7af41dcd73 chore(all): release client 0.2.18 and server 0.2.5
release notes / releases (push) Successful in 2s
2026-10-26 00:11:08 +08:00
Flechazo 38c568cba4 fix(plugin): isolate arena actions and match ordinary presets with borrowed supporters 2026-10-26 00:11:08 +08:00
Flechazo d2d92d3961 fix(server): share mode-specific formation validation, preserve partial saves and resolve airship talents 2026-10-26 00:11:08 +08:00
Flechazo a89fd2171a chore(all): release client 0.2.17 and server 0.2.4
release notes / releases (push) Successful in 3s
2026-10-25 23:18:07 +08:00
Flechazo 09214fc0be fix(plugin): keep AI translation settings above their opening panel 2026-10-25 23:18:07 +08:00
Flechazo bf6c24a236 feat(all): match PvP opponents using contextual skill ratings and battle reports 2026-10-25 23:18:07 +08:00
Flechazo d1711697c1 fix(server): include fishing ticket schedules in charge information 2026-10-25 23:04:58 +08:00
Flechazo 08cd490861 fix(server): return native no-opponent errors from PvP matching 2026-10-25 22:23:53 +08:00
Flechazo ac6c5526c2 fix(server): accept signed furniture rotation and interaction in room saves 2026-10-25 21:48:06 +08:00
Flechazo 8123ddf321 fix(server): keep live game sessions active during long battles 2026-10-25 20:59:35 +08:00
Flechazo 03b2471106 fix(plugin): preserve loaded plugin reporting after Unity scene teardown 2026-10-25 20:01:51 +08:00
Flechazo 2b98e0225a chore(client): release client 0.2.16 with managed plugin reporting and update fixes
release notes / releases (push) Successful in 3s
Publish preset first-turn actions and the room wallpaper fix with compatible launcher and plugin metadata. Bump plugins using the shared runtime settings and include five-language release notes.
2026-10-25 19:45:42 +08:00
Flechazo 339b2dcaee fix(client): derive loaded plugin reporting from the managed registry
Pass managed plugin IDs and DLL names through launcher runtime settings. Report real versions only from loaded managed assemblies, excluding third-party and failed plugins.
2026-10-25 19:20:52 +08:00
Flechazo e8f0ed8e7d fix(server): price room expansions by owned room count
Allow any valid unowned grid cell and use the next owned-room count for its price. Verify exact charges, retries, rejected purchases, and persistence.
2026-10-25 18:20:05 +08:00
Flechazo b62dc26a37 fix(client): validate dev launches against server compatibility requirements 2026-10-25 18:10:39 +08:00
Flechazo 3ca98d774d fix(client): support new plugin updates and prepare manual client 0.2.15
Validate plugin identifiers without a fixed list and accept installed versions above declared minima. Cover future launcher and plugin downloads and installation.

Withdraw the canceled 0.2.14 announcement, retain server 0.2.3, and sign manual client metadata without publishing a new update.
2026-10-25 18:05:54 +08:00
Flechazo 499001b8ea fix(client): keep optional battle actions compatible with existing updaters 2026-10-25 17:47:03 +08:00
Flechazo 1a3a3784a8 chore(client): release client 0.2.14 with preset actions and room fixes
release notes / releases (push) Successful in 2s
2026-10-25 17:42:24 +08:00
Flechazo 2b5a06a647 chore(server): remove unused puzzle test helpers 2026-10-25 17:42:23 +08:00
Flechazo ed2b24ef2c feat(all): save preset first-turn actions and apply them in battle 2026-10-25 17:42:23 +08:00
Flechazo e06d68aaaf fix(all): restore room placement, inventory counts and saved layouts 2026-10-25 17:42:22 +08:00
Flechazo 3b39718d76 fix(server): restore tower clear package eligibility 2026-10-25 17:42:22 +08:00
322 changed files with 13552 additions and 1506 deletions

No files matched your search

+297
View File
@@ -1,5 +1,302 @@
# 更新日志
## 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
### en_us: Preset battle actions with supporters and arena teams
- Keep ordinary preset first-turn actions working when the party includes a borrowed supporter; supporters continue using their own actions and are excluded from preset member matching.
- Exclude Golden Colosseum battles from ordinary preset action overrides, keeping each mode’s own team and action settings separate.
### zh_cn: 助战与竞技场预设动作修复
- 普通队伍带借用助战时仍可正确匹配预设并应用首轮动作;助战独立行动,不参与普通预设成员匹配。
- 黄金竞技场不再误用普通预设的首轮动作,保留各玩法自己的配队和行动设置。
### zh_tw: 助戰與競技場預設動作修正
- 普通隊伍包含借用助戰時,仍能正確比對預設並套用首輪動作;助戰獨立行動,不參與普通預設成員比對。
- 黃金競技場不再誤用普通預設的首輪動作,保留各玩法自己的配隊及行動設定。
### ja_jp: 助っ人と闘技場のプリセット動作修正
- 通常編成に借用した助っ人がいてもプリセットを正しく照合し、初手の行動を適用します。助っ人は照合対象から除外し、独自の行動を維持します。
- 黄金の闘技場では通常プリセットの初手設定を適用せず、各モードの編成と行動設定を維持します。
### ko_kr: 지원 캐릭터 및 투기장 프리셋 행동 수정
- 일반 편성에 빌린 지원 캐릭터가 있어도 프리셋을 올바르게 확인하고 첫 턴 행동을 적용합니다. 지원 캐릭터는 프리셋 구성원 비교에서 제외하고 자체 행동을 유지합니다.
- 황금 투기장에 일반 프리셋의 첫 턴 설정이 잘못 적용되지 않도록 하여 각 모드의 편성 및 행동 설정을 유지합니다.
## server 2.37.13+server.0.2.5 · 2026-10-26
> type: update
> migration: none
### en_us: Party presets and airship talents
- Share formation validation across ordinary parties, PvP, guild raids and Fiend Hunts while retaining each mode’s capacity and grid rules. Fix guild raid saves rejecting the seventh action slot and the last cells of the 5×5 grid, and reject duplicate action orders in Fiend Hunt teams.
- Preserve parties when saving only action settings in guild raids and Fiend Hunts. Merge settings by character, battle mode and monster so changes do not erase other saved actions.
- Resolve the airship lobby before its first position save, keeping dungeon and lobby maps correct when entering stages, returning or reconnecting. Fix valid talent requests being rejected because the current map was unknown.
### zh_cn: 配队预设与飞船天赋修复
- 普通配队、PvP、公会联合战和魔兽追踪共用编队校验,各玩法保留独立的人数与棋盘规则;修复公会第七行动位、5×5 棋盘后部位置无法保存的问题,并补上魔兽同队行动序号去重。
- 修复公会与魔兽仅保存技能设置时清空配队的问题;技能设置按角色、战斗模式和怪物分别合并,保留其他已保存设置。
- 补齐首次保存位置前的飞船大厅地图识别,进入关卡、返回大厅和重连时保持正确场景,修复合法天赋请求因地图未知而被拒绝的问题。
### zh_tw: 配隊預設與飛船天賦修正
- 普通配隊、PvP、公會聯合戰與魔獸追蹤共用編隊驗證,各玩法保留獨立的人數及棋盤規則;修正公會第七行動位、5×5 棋盤後段位置無法儲存的問題,並補上魔獸同隊行動順序去重。
- 修正公會與魔獸僅儲存技能設定時清空配隊的問題;技能設定依角色、戰鬥模式及怪物合併,保留其他已儲存設定。
- 補齊首次儲存位置前的飛船大廳地圖識別,進入關卡、返回大廳及重新連線時維持正確場景,修正合法天賦請求因地圖未知而遭拒絕的問題。
### ja_jp: 編成プリセットと飛行船の才能スキル修正
- 通常編成、PvP、ギルドレイド、魔獣追跡の編成検証を共通化し、各モードの人数と盤面ルールを維持しました。ギルドの7番目の行動順と5×5盤面の後方マスを保存できない問題を修正し、魔獣の同一チーム内の行動順重複を検出します。
- ギルドと魔獣でスキル設定だけを保存すると編成が消える問題を修正しました。設定はキャラクター、戦闘モード、モンスターごとに更新し、他の設定を保持します。
- 最初の位置保存前でも飛行船ロビーを識別し、ステージ進入、ロビーへの帰還、再接続時のマップを正しく扱います。現在地不明で有効な才能スキルが拒否される問題を修正しました。
### ko_kr: 편성 프리셋 및 비행선 재능 수정
- 일반 편성, PvP, 길드 레이드와 마수 추적의 편성 검증을 공통화하고 각 모드의 인원 및 전장 규칙을 유지했습니다. 길드의 일곱 번째 행동 순서와 5×5 전장 뒤쪽 칸을 저장하지 못하는 문제를 수정하고 마수 팀 내 행동 순서 중복을 검사합니다.
- 길드와 마수에서 스킬 설정만 저장할 때 편성이 지워지던 문제를 수정했습니다. 캐릭터, 전투 모드와 몬스터별로 설정을 병합하여 다른 설정을 보존합니다.
- 첫 위치 저장 전에도 비행선 로비를 식별하고 스테이지 진입, 로비 복귀 및 재접속 시 올바른 맵을 유지합니다. 현재 맵을 알 수 없어 유효한 재능 요청이 거부되던 문제를 수정했습니다.
## client 2.37.13+client.0.2.17 · 2026-10-25
> type: update
### en_us: AI translation settings and PvP battle reports
- Keep the main chat’s translation switch and AI configuration entry in Chat Settings, removing duplicate controls from the chat bar. Open AI settings above the window that launched it so its controls remain accessible.
- Add PvP battle reports with remaining team health, survivors and turn count for matchmaking analysis. Existing battle results continue to work when no report is available.
### zh_cn: AI 翻译设置与 PvP 战斗统计
- 主聊天的自动翻译开关和 AI 设置统一保留在聊天设置中,移除聊天栏的重复入口;AI 设置面板显示在打开它的窗口上方,避免被遮挡而无法操作。
- 补充 PvP 双方剩余生命、存活人数和回合数统计,为匹配分析提供数据;无法取得统计时仍正常提交原有战斗结果。
### zh_tw: AI 翻譯設定與 PvP 戰鬥統計
- 主聊天的自動翻譯開關與 AI 設定統一保留在聊天設定中,移除聊天列的重複入口;AI 設定面板顯示於開啟它的視窗上方,避免遭遮擋而無法操作。
- 補充 PvP 雙方剩餘生命、存活人數與回合數統計,提供配對分析資料;無法取得統計時仍正常提交原有戰鬥結果。
### ja_jp: AI翻訳設定とPvP戦闘統計
- メインチャットの自動翻訳スイッチとAI設定をチャット設定にまとめ、チャットバーの重複した入口を削除しました。AI設定は呼び出し元のウィンドウより手前に表示し、操作できるようにしました。
- PvPの両チームの残りHP、生存人数、ターン数をマッチング分析用に報告します。統計を取得できなくても通常の戦闘結果は送信します。
### ko_kr: AI 번역 설정 및 PvP 전투 통계
- 메인 채팅의 자동 번역 스위치와 AI 설정을 채팅 설정에 모으고 채팅 바의 중복 진입 버튼을 제거했습니다. AI 설정 창을 호출한 창보다 앞에 표시하여 가려지지 않고 조작할 수 있습니다.
- PvP 양 팀의 남은 체력, 생존 인원과 턴 수를 매칭 분석에 보고합니다. 통계를 얻지 못하더라도 기존 전투 결과는 정상 전송합니다.
## server 2.37.13+server.0.2.4 · 2026-10-25
> type: update
> migration: none
### en_us: PvP matchmaking and gameplay fixes
- Choose Mirror War and Golden Colosseum opponents using skill ratings and a learned win-probability model that accounts for available team power, account experience, team size and turn order. Matchmaking ratings persist across seasons; existing season scores and rewards keep their rules.
- When no opponent is available, show the game’s native message and end matching without retrying until a network timeout or consuming a challenge ticket.
- Keep active sessions alive during long battles so retrying a tower battle does not reconnect after an idle timeout.
- Accept native negative furniture rotation and interaction values when saving My Room layouts and presets.
- Initialize multiplayer fishing ticket recharge information when logging in, fixing the missing-schedule exception when opening fishing.
### zh_cn: PvP 匹配优化与玩法修复
- 镜中之战和黄金竞技场按隐藏实力评分与学习得到的胜率选择对手,结合可用的队伍战力、账号经验、队伍人数和先后手信息。匹配评分跨赛季保留,赛季积分和奖励仍遵循原有规则。
- 没有可匹配对手时使用游戏原生提示并结束匹配,不再重试到网络超时,也不消耗挑战门票。
- 长时间战斗期间正确维持活跃会话,修复塔内重来因闲置超时而重连的问题。
- 修复小屋布局和预设保存错误拒绝家具负数朝向、互动状态而断联的问题。
- 补齐登录时的多人钓鱼门票充能信息,修复打开钓鱼界面时缺少计时记录的异常。
### zh_tw: PvP 配對最佳化與玩法修正
- 鏡中之戰與黃金競技場依隱藏實力評分及學習得到的勝率選擇對手,結合可用的隊伍戰力、帳號經驗、隊伍人數與先後手資訊。配對評分跨賽季保留,賽季積分與獎勵仍遵循原有規則。
- 沒有可配對對手時顯示遊戲原生提示並結束配對,不再重試至網路逾時,也不消耗挑戰門票。
- 長時間戰鬥期間正確維持活躍連線,修正塔內重試因閒置逾時而重新連線的問題。
- 修正儲存小屋配置與預設時,錯誤拒絕家具負數朝向及互動狀態而斷線的問題。
- 補齊登入時的多人釣魚門票充能資訊,修正開啟釣魚介面時缺少計時記錄的異常。
### ja_jp: PvPマッチングの改善と不具合修正
- 鏡戦争と黄金の闘技場で、内部レーティングと学習した勝率を使って対戦相手を選択します。取得できる編成戦闘力、アカウント経験値、人数、先攻・後攻を考慮します。レーティングはシーズンをまたいで保持し、シーズン得点と報酬のルールは維持します。
- 対戦相手がいない場合はゲーム標準のメッセージを表示してマッチングを終了します。通信タイムアウトまで再試行せず、挑戦チケットも消費しません。
- 長時間の戦闘中もセッションを維持し、塔で再挑戦すると待機タイムアウトにより再接続する問題を修正しました。
- マイルームの配置やプリセット保存時に、家具の負数の向き・インタラクション値が拒否されて切断する問題を修正しました。
- ログイン時にマルチ釣りチケットの回復情報を初期化し、釣り画面を開くとスケジュール情報不足で例外が発生する問題を修正しました。
### ko_kr: PvP 매칭 개선 및 플레이 오류 수정
- 거울전쟁과 황금 투기장은 숨겨진 실력 평점과 학습된 승률로 상대를 선택하며, 사용 가능한 편성 전투력, 계정 경험치, 팀 인원과 선후공 정보를 반영합니다. 평점은 시즌이 바뀌어도 유지되고 시즌 점수와 보상 규칙은 그대로 적용됩니다.
- 매칭할 상대가 없으면 게임 기본 안내를 표시하고 매칭을 종료합니다. 네트워크 시간 초과까지 재시도하거나 도전권을 소모하지 않습니다.
- 장시간 전투 중에도 세션을 유지하여 탑에서 재도전할 때 유휴 시간 초과로 재접속되던 문제를 수정했습니다.
- 마이룸 배치와 프리셋 저장 시 가구의 음수 방향 및 상호작용 값이 잘못 거부되어 연결이 끊기는 문제를 수정했습니다.
- 로그인 시 멀티 낚시 도전권 충전 정보를 초기화하여 낚시 화면을 열 때 시간표 정보 누락으로 예외가 발생하는 문제를 수정했습니다.
## client 2.37.13+client.0.2.16 · 2026-10-25
> type: update
### en_us: Preset first-turn actions and client update fixes
- Configure each character's first-turn normal attack, knock-back or costume skill and burst level in the team preset's action editor. Choices are saved with the preset and restored after reconnecting; later turns follow the game's normal behavior.
- Fix a crash when placing the first wallpaper on an empty wall in My Room.
- Fix incorrect client-update prompts caused by missing plugin version reports. Report actual loaded managed plugins while keeping third-party plugins separate, and allow future plugin additions without blocking launcher updates.
- Fix development launches being rejected when release identifiers differ despite compatible versions and identical game resources.
### zh_cn: 预设首轮出手与客户端更新修复
- 在配队预设的“出手方式”中,为每名角色选择首轮普攻、击退或服装技能及爆发等级。配置随预设保存,重连后恢复,后续回合交给游戏处理。
- 修复小屋空墙面首次放置墙纸时崩溃的问题。
- 修复漏报插件版本导致的“需要更新客户端”误提示,按实际加载结果识别受管理插件,不混入第三方插件;后续新增插件也不会阻断启动器更新。
- 修复开发模式下版本和游戏资源均兼容,却因发布标识不同而无法启动的问题。
### zh_tw: 預設首輪行動與用戶端更新修正
- 在配隊預設的「出手方式」中,為每名角色選擇首輪普攻、擊退或服裝技能與爆發等級。設定隨預設儲存,重新連線後恢復,後續回合交給遊戲處理。
- 修正小屋空牆面首次放置壁紙時崩潰的問題。
- 修正漏報插件版本導致的「需要更新用戶端」誤提示,依實際載入結果識別受管理插件,不混入第三方插件;後續新增插件也不會阻擋啟動器更新。
- 修正開發模式下版本與遊戲資源均相容,卻因發布識別碼不同而無法啟動的問題。
### ja_jp: プリセットの初回行動とクライアント更新の修正
- 編成プリセットの行動エディターで、各キャラクターの初回の通常攻撃、ノックバック、コスチュームスキルとバーストレベルを選べます。設定はプリセットとともに保存され、再接続後も復元されます。以降のターンは通常のゲーム動作に従います。
- マイルームの空の壁に初めて壁紙を配置するとクラッシュする問題を修正しました。
- プラグインのバージョン報告漏れによる誤った更新要求を修正しました。管理対象のプラグインは実際の読み込み状態から判定し、第三者製プラグインは含めません。今後のプラグイン追加でもランチャーの更新を妨げません。
- 開発モードで、バージョンとゲームリソースが互換でもリリース識別子の違いにより起動できない問題を修正しました。
### ko_kr: 프리셋 첫 턴 행동 및 클라이언트 업데이트 수정
- 편성 프리셋의 행동 편집기에서 캐릭터별 첫 턴의 일반 공격, 넉백 또는 코스튬 스킬과 버스트 단계를 선택할 수 있습니다. 설정은 프리셋과 함께 저장되고 재접속 후 복원되며, 이후 턴은 게임의 기본 동작을 따릅니다.
- 마이룸의 빈 벽에 처음 벽지를 배치할 때 발생하는 충돌을 수정했습니다.
- 플러그인 버전 보고 누락으로 잘못 표시되던 업데이트 요구를 수정했습니다. 관리 대상 플러그인은 실제 로드 상태로 확인하고 타사 플러그인은 포함하지 않습니다. 이후 새 플러그인이 추가되어도 런처 업데이트를 차단하지 않습니다.
- 개발 모드에서 버전과 게임 리소스가 호환되어도 릴리스 식별자가 다르면 실행할 수 없던 문제를 수정했습니다.
## server 2.37.13+server.0.2.3 · 2026-10-25
> type: update
+1 -1
View File
@@ -1,4 +1,4 @@
{
"key_id": "6ba6c06138973875",
"signature": "xc2YjF6k//tU0tJZSQT9uL7W75mwy26ysMXcWneNHEXARyUTHRlYDqqZDxsa61CdVuzwsqUdJQWVvMqoAShMBw=="
"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.13","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
}},
+9 -13
View File
@@ -23,13 +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"`
}
// pluginVersions maps plugin version keys to versions.
type pluginVersions map[string]string
func readConfig(path string, config *Config) error {
raw, err := os.ReadFile(path)
@@ -53,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
@@ -105,18 +100,19 @@ 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}
// 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}$`)
if !semver.MatchString(c.GameVersion) {
return "", errors.New("game_version must be a numeric three-part version")
}
for _, key := range []string{"local_identity", "capture_environment", "login_ui", "cash_shop", "fchat"} {
if !semver.MatchString(plugins[key]) {
for key, value := range plugins {
if !semver.MatchString(value) {
return "", fmt.Errorf("plugins.%s must be a numeric three-part version", key)
}
}
+15 -2
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
})
}
@@ -341,7 +350,11 @@ func (s *Studio) Launch(input Request) (Response, error) {
launch := func() (Response, error) {
configured := input.settings()
if s.updates != nil {
configured.Runtime = s.updates.Runtime(input.GameDirectory)
runtime, err := s.updates.Runtime(input.GameDirectory)
if err != nil {
return Response{}, err
}
configured.Runtime = runtime
}
settings, err := clientsetup.SaveSettings(input.GameDirectory, configured)
if err != nil {
+7 -6
View File
@@ -37,12 +37,13 @@ type Settings struct {
}
type Runtime struct {
ClientVersion string `json:"client_version"`
UpdateFingerprint string `json:"update_fingerprint"`
ResourceFingerprint string `json:"resource_fingerprint"`
GameVersion string `json:"game_version"`
BundleVersion string `json:"bundle_version"`
GameDataVersion string `json:"game_data_version"`
PluginFiles map[string]string `json:"plugin_files,omitempty"`
ClientVersion string `json:"client_version"`
UpdateFingerprint string `json:"update_fingerprint"`
ResourceFingerprint string `json:"resource_fingerprint"`
GameVersion string `json:"game_version"`
BundleVersion string `json:"bundle_version"`
GameDataVersion string `json:"game_data_version"`
}
func Path(gameDir string) string {
+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 -31
View File
@@ -1,56 +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: "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
@@ -74,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
}
@@ -82,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))
}
@@ -94,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) {
@@ -111,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
@@ -140,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
+6 -2
View File
@@ -15,8 +15,12 @@ func (m *Manager) PrepareLocalDatabase(ctx context.Context, client *http.Client,
if client == nil {
client = m.options.Client
}
_, err := dbpatch.Run(ctx, dbpatch.Options{
GameDirectory: game, Origin: origin, GameVersion: m.Runtime(game).GameVersion,
runtime, err := m.Runtime(game)
if err != nil {
return err
}
_, err = dbpatch.Run(ctx, dbpatch.Options{
GameDirectory: game, Origin: origin, GameVersion: runtime.GameVersion,
Client: client, Logger: m.options.Logger, Running: func() (bool, error) { return m.localDatabaseRunning(game) },
})
return err
+45 -7
View File
@@ -14,6 +14,7 @@ import (
clientconfig "bd2server/internal/client/config"
"bd2server/internal/client/download"
"bd2server/internal/client/plugin"
"bd2server/internal/client/setup"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/release"
@@ -68,12 +69,34 @@ func (m *Manager) Versions(game string) versionconfig.Config {
return v
}
func (m *Manager) Runtime(game string) *clientconfig.Runtime {
func (m *Manager) Runtime(game string) (*clientconfig.Runtime, error) {
var runtime *clientconfig.Runtime
if m.options.Development {
return m.developmentRuntime()
runtime = m.developmentRuntime()
for _, artifact := range m.options.DevelopmentPlugins {
if artifact.ID != "" {
if runtime.PluginFiles == nil {
runtime.PluginFiles = map[string]string{}
}
runtime.PluginFiles[artifact.ID] = artifact.Name
}
}
return runtime, nil
}
v := m.Versions(game)
runtime := &clientconfig.Runtime{ClientVersion: v.ClientVersion, GameVersion: v.GameVersion, BundleVersion: v.BundleVersion, GameDataVersion: v.GameDataVersion}
runtime = &clientconfig.Runtime{ClientVersion: v.ClientVersion, GameVersion: v.GameVersion, BundleVersion: v.BundleVersion, GameDataVersion: v.GameDataVersion}
store, err := plugin.ReadStore(m.options.Directory)
if err != nil {
return nil, fmt.Errorf("read runtime plugin identities: %w", err)
}
for _, file := range store.Files {
if file.ID != "" {
if runtime.PluginFiles == nil {
runtime.PluginFiles = map[string]string{}
}
runtime.PluginFiles[file.ID] = file.Name
}
}
m.mu.Lock()
fp := m.fingerprint
m.mu.Unlock()
@@ -83,7 +106,7 @@ func (m *Manager) Runtime(game string) *clientconfig.Runtime {
runtime.ResourceFingerprint = receipt.ResourceFingerprint
}
}
return runtime
return runtime, nil
}
func (m *Manager) configureGame(game string) error {
@@ -91,7 +114,10 @@ func (m *Manager) configureGame(game string) error {
if err != nil {
return err
}
settings.Runtime = m.Runtime(game)
settings.Runtime, err = m.Runtime(game)
if err != nil {
return err
}
_, err = clientconfig.Save(game, settings)
return err
}
@@ -122,8 +148,20 @@ func (m *Manager) prepareDevelopmentGame(game string) error {
m.mu.Lock()
server := m.fingerprint
m.mu.Unlock()
if server != nil && (m.project == nil || server.ID != m.project.ID) {
return fmt.Errorf("server requires update %s for game %s; update the project's %s before launching", server.ID, gameVersion(server), release.FingerprintFileName)
if server != nil {
runtime := m.developmentRuntime()
identity := release.ClientIdentity{
Version: runtime.ClientVersion,
Plugins: v.Plugins.ByID(),
GameVersion: runtime.GameVersion,
BundleVersion: runtime.BundleVersion,
GameDataVersion: runtime.GameDataVersion,
Fingerprint: runtime.UpdateFingerprint,
ResourceFingerprint: runtime.ResourceFingerprint,
}
if !server.Accepts(identity) {
return fmt.Errorf("server requires update %s for game %s; update the project's %s before launching", server.ID, gameVersion(server), release.FingerprintFileName)
}
}
if _, err := setup.Inspect(game, v); err != nil {
return fmt.Errorf("development game does not match versions.json: %w", err)
+9 -4
View File
@@ -6,11 +6,13 @@ import (
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
clientconfig "bd2server/internal/client/config"
"bd2server/internal/client/plugin"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/release"
"bd2server/internal/common/versionconfig"
@@ -89,7 +91,7 @@ func TestServerOnlyFingerprintChangeReusesVerifiedGameResources(t *testing.T) {
func TestDevelopmentGameUsesProjectFingerprintAndNeverInstallsServerRequirement(t *testing.T) {
game := t.TempDir()
versions := versionconfig.Config{ServerVersion: "2.37.13+server.0.2.0", ClientVersion: "2.37.13+client.0.2.7", GameVersion: "2.37.13", BundleVersion: "20261022174708", GameDataVersion: "20261021182514"}
m := New(Options{Directory: t.TempDir(), Versions: versions, Development: true})
m := New(Options{Directory: t.TempDir(), Versions: versions, Development: true, DevelopmentPlugins: plugin.Set{{ID: "future_plugin", Name: "UnrelatedFileName.dll"}}})
m.project = &release.Fingerprint{ID: "project", ServerVersion: versions.ServerVersion, ClientVersion: versions.ClientVersion, GameFingerprint: "project-resources"}
m.fingerprint = &release.Fingerprint{ID: "server", RequireGameUpdate: true}
err := m.ensureGame(context.Background(), game)
@@ -99,9 +101,12 @@ func TestDevelopmentGameUsesProjectFingerprintAndNeverInstallsServerRequirement(
if entries, err := os.ReadDir(game); err != nil || len(entries) != 0 {
t.Fatalf("development preparation wrote into the game directory: %v %v", entries, err)
}
got := m.Runtime(game)
want := clientconfig.Runtime{ClientVersion: versions.ClientVersion, GameVersion: versions.GameVersion, BundleVersion: versions.BundleVersion, GameDataVersion: versions.GameDataVersion, UpdateFingerprint: "project", ResourceFingerprint: "project-resources"}
if *got != want {
got, err := m.Runtime(game)
if err != nil {
t.Fatal(err)
}
want := clientconfig.Runtime{ClientVersion: versions.ClientVersion, GameVersion: versions.GameVersion, BundleVersion: versions.BundleVersion, GameDataVersion: versions.GameDataVersion, UpdateFingerprint: "project", ResourceFingerprint: "project-resources", PluginFiles: map[string]string{"future_plugin": "UnrelatedFileName.dll"}}
if !reflect.DeepEqual(*got, want) {
t.Fatalf("development runtime = %+v, want project configuration %+v", *got, want)
}
}
+4 -1
View File
@@ -35,7 +35,7 @@ func releaseFile(name, content string) release.File {
return release.File{Name: name, Size: int64(len(content)), SHA256: hex.EncodeToString(digest[:]), URL: "/" + name}
}
func signedFixture(t *testing.T, launcher, plugins *release.Component) ([]byte, []release.TrustedKey) {
func signedFixture(t *testing.T, launcher, plugins *release.Component, fingerprints ...*release.Fingerprint) ([]byte, []release.TrustedKey) {
t.Helper()
public, private, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
@@ -43,6 +43,9 @@ func signedFixture(t *testing.T, launcher, plugins *release.Component) ([]byte,
}
key := release.TrustedKey{ID: release.KeyID(public), PublicKey: base64.StdEncoding.EncodeToString(public)}
manifest := release.Manifest{Schema: release.SchemaVersion, Channel: release.BuiltinChannel().Name, PublishedAt: time.Now().UTC(), Commit: strings.Repeat("a", 40), Launcher: launcher, Plugins: plugins}
if len(fingerprints) != 0 {
manifest.Fingerprint = fingerprints[0]
}
payload, err := json.Marshal(manifest)
if err != nil {
t.Fatal(err)
+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)
}
}
+3 -12
View File
@@ -154,7 +154,7 @@ func (f Fingerprint) Validate() error {
}
for id, version := range f.MinimumPlugins {
v, e := ParseVersion(version)
if e != nil || !knownPlayerPlugin(id) || v.HasGame {
if e != nil || !pluginIDPattern.MatchString(id) || v.HasGame {
return errors.New("release: invalid fingerprint plugin version")
}
}
@@ -182,15 +182,6 @@ func (f Fingerprint) Validate() error {
return nil
}
func knownPlayerPlugin(id string) bool {
switch id {
case "local_identity", "login_ui", "cash_shop", "fchat":
return true
default:
return false
}
}
func (f Fingerprint) digest() (string, error) {
raw, err := json.Marshal(f)
if err != nil {
@@ -231,8 +222,8 @@ func (f Fingerprint) MatchesVersions(v versionconfig.Config) error {
return errors.New("release: fingerprint does not match installed game resource versions")
}
for id, version := range f.MinimumPlugins {
if v.Plugins.ByID()[id] != version {
return fmt.Errorf("release: fingerprint plugin %s does not match installed version", id)
if !AtLeast(v.Plugins.ByID()[id], version) {
return fmt.Errorf("release: fingerprint plugin %s requires at least %s", id, version)
}
}
return nil
@@ -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": "修復"
}
+4 -3
View File
@@ -70,8 +70,9 @@ type Migration struct {
}
var (
digestPattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
commitPattern = regexp.MustCompile(`^[0-9a-f]{40}$`)
pluginIDPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
digestPattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
commitPattern = regexp.MustCompile(`^[0-9a-f]{40}$`)
)
func Platform() string { return runtime.GOOS + "-" + runtime.GOARCH }
@@ -149,7 +150,7 @@ func (c *Component) validate(name string) error {
return errors.New("release: server must declare its migration kind")
}
for id, minimum := range c.MinimumPlugins {
if _, err := ParseVersion(minimum); err != nil || id == "" {
if _, err := ParseVersion(minimum); err != nil || !pluginIDPattern.MatchString(id) {
return fmt.Errorf("release: invalid minimum plugin %s=%q", id, minimum)
}
}
+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 -29
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,13 +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"`
}
// 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.
@@ -73,19 +71,20 @@ 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)
}
}
@@ -112,18 +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 {
return map[string]string{"local_identity": p.LocalIdentity, "capture_environment": p.CaptureEnvironment, "login_ui": p.LoginUI, "cash_shop": p.CashShop, "fchat": p.FChat}
}
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)
@@ -3,9 +3,12 @@
package app
import (
"bytes"
"context"
"encoding/json"
"fmt"
"slices"
"strings"
"testing"
"time"
@@ -180,3 +183,109 @@ func TestClearPackageClaimsSurviveSessionAndDayChanges(t *testing.T) {
t.Fatalf("mail retries credited diamonds again: got %d, want %d", got, before+2100)
}
}
// GameData20261021182514 ClearEvilCastleTable: group11/gate2/floor10
// uses ticket12 for free rewards (mail733: 100 free diamonds) and
// ticket441001 for premium rewards (mail734: material1000 x10).
func TestTowerClearPackageClaimsUseSavedProgressAndDoNotRepeatMail(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
a := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
b := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
t.Cleanup(func() { closeNicknamePlayer(t, a.owner); closeNicknamePlayer(t, b.owner) })
seq := uint64(100)
claimRequest := func(ticket uint64) []byte {
seq++
row := append(appScalar(1, 11), appScalar(2, ticket)...)
row = append(row, appScalar(3, 2)...)
row = append(row, appScalar(4, 10)...)
request := append(appScalar(1, seq), appScalar(2, 1)...)
return append(request, appMessage(4, row)...)
}
assertRejected := func(s *trapPlayerScenario, ticket uint64, reason string) {
t.Helper()
if _, err := s.execute("/ClearPackageReward", claimRequest(ticket)); err == nil || !strings.Contains(err.Error(), reason) {
t.Fatalf("ticket%d: got %v, want %s", ticket, err, reason)
}
}
seedFloors := func(last uint64) {
t.Helper()
a.run(t, true, func(ctx command.Context, _ *playerAssembly) {
towers := map[string]map[string]uint64{}
for floor := uint64(1); floor <= last; floor++ {
towers[fmt.Sprintf("16:%d", floor)] = map[string]uint64{"ID": floor, "Mode": 16}
}
towers["19:10"] = map[string]uint64{"ID": 10, "Mode": 19}
raw, err := json.Marshal(map[string]any{"Towers": towers, "Floors": map[string]any{}})
if err != nil {
t.Fatal(err)
}
if err := ctx.State.PutEntry("missions", "castle_state", "progress", raw); err != nil {
t.Fatal(err)
}
})
a.reopen(t)
}
seedFloors(9)
assertRejected(a, 12, "progression incomplete")
seedFloors(10)
assertRejected(b, 12, "progression incomplete")
assertRejected(a, 441001, "premium ticket required")
free := a.protocol(t, "/ClearPackageReward", claimRequest(12))
a.run(t, true, func(ctx command.Context, p *playerAssembly) {
if _, err := p.ownedItems.GrantOnce(ctx, "tower-premium-ticket", []gamedata.BattleReward{{Type: 19, ID: 441001, Count: 1}}); err != nil {
t.Fatal(err)
}
})
premium := a.protocol(t, "/ClearPackageReward", claimRequest(441001))
mailRows := func() [][]byte {
t.Helper()
seq++
return appRows(a.protocol(t, "/CashMailInfo", append(appScalar(1, seq), appScalar(3, 100)...)), 1)
}
before := mailRows()
if len(before) != 2 {
t.Fatalf("got %d reward mails, want 2", len(before))
}
wantMail := map[uint64][3]uint64{733: {3, 0, 100}, 734: {8, 1000, 10}}
for _, row := range before {
template := appValue(row, 3)
want, ok := wantMail[template]
if !ok || !slices.Equal(appPacked(row, 8), []uint64{want[0]}) || !slices.Equal(appPacked(row, 9), []uint64{want[1]}) || !slices.Equal(appPacked(row, 10), []uint64{want[2]}) {
t.Fatalf("wrong tower reward mail: %x", row)
}
delete(wantMail, template)
}
a.reopen(t)
if got := a.protocol(t, "/ClearPackageReward", claimRequest(12)); !bytes.Equal(got, free) {
t.Fatal("free retry changed its receipt")
}
if got := a.protocol(t, "/ClearPackageReward", claimRequest(441001)); !bytes.Equal(got, premium) {
t.Fatal("premium retry changed its receipt")
}
after := mailRows()
if len(after) != len(before) {
t.Fatal("retry issued duplicate reward mails")
}
for i := range before {
if appValue(before[i], 1) != appValue(after[i], 1) {
t.Fatal("retry replaced an existing reward mail")
}
}
seq++
info := a.protocol(t, "/PackInfo", appScalar(1, seq))
claims := appRows(info, 4)
if len(appRows(info, 3)) != 0 || len(claims) != 2 {
t.Fatal("reopened PackInfo lost tower claims or mixed them with story claims")
}
var tickets []uint64
for _, row := range claims {
if appValue(row, 1) != 11 || appValue(row, 3) != 2 || appValue(row, 4) != 10 {
t.Fatalf("wrong claimed floor: %x", row)
}
tickets = append(tickets, appValue(row, 2))
}
slices.Sort(tickets)
if !slices.Equal(tickets, []uint64{12, 441001}) {
t.Fatalf("wrong claim tickets: %v", tickets)
}
}
+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
@@ -112,3 +113,160 @@ func TestFishingTrapAutoSaleUsesNativeCurrencyAndAtomicSettlement(t *testing.T)
t.Fatal("reopened fishing experience lost")
}
}
func TestFishingChargeScheduleIsIncludedBeforeOpeningHarbor(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
g := newSquareGameplay(t, factory, accounts[0])
login := g.call("/LoginUser", nil)
users := appRows(login, 1)
if len(users) != 1 {
t.Fatal("missing player")
}
// UserDBInfo.fishing_multi_ap=62; EElementType.FishingMultiTicket=55.
tickets := appValue(users[0], 62)
if tickets != 10 {
t.Fatalf("current FishingDefaultTable0 actionPointCount=%d want10", tickets)
}
charge := g.call("/ChargeCostInfo", nil)
matches := 0
for _, info := range appRows(charge, 1) {
items := appRows(info, 2)
if len(items) != 1 {
t.Fatal("invalid cost item")
}
if appValue(items[0], 3) != 55 {
continue
}
matches++
if appValue(items[0], 4) != tickets {
t.Fatal("fishing charge balance disagrees with login")
}
stamp := time.UnixMilli(int64(appValue(info, 1))).UTC()
now := time.Now().UTC()
if stamp.Hour() != 0 || stamp.Minute() != 0 || stamp.Second() != 0 || now.Sub(stamp) < 0 || now.Sub(stamp) >= 24*time.Hour {
t.Fatalf("invalid last charge timestamp %v", stamp)
}
}
if matches != 1 {
t.Fatalf("fishing schedules=%d want1", matches)
}
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.
@@ -275,7 +275,7 @@ func TestNativeGuildRaidSettlesBothMembersAndClaimsOnce(t *testing.T) {
scores := map[string]uint64{}
for i, g := range []*guildGameplay{a, b} {
_, character := g.ownedPVPDeck()
deck := appScalar(1, character)
deck := append(appScalar(1, character), appScalar(3, 1)...)
g.pvpCall("/GuildRaidDeckSave", appMessage(2, deck))
entered := g.pvpCall("/GuildRaidBossBattleEnter", appScalar(2, level))
if appValue(entered, 4) != 1 {
@@ -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) }
@@ -32,7 +32,6 @@ func (p *playerAssembly) commerce(ctx command.Context) error {
if err != nil {
return fmt.Errorf("load clear-package claims: %w", err)
}
p.clearPackages.AttachProgress(p.worldService.CashPackagePackCleared, nil)
p.cashService.SetClock(time.Now, p.design.eventAPReset.ResetSeconds-9*3600)
if err := p.cashService.AttachPackageRules(p.design.cashDesign.Packages); err != nil {
return fmt.Errorf("attach cash package progression: %w", err)
+5
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)
@@ -103,6 +107,7 @@ func (p *playerAssembly) events(ctx command.Context) error {
return nil, err
}
rows = append(rows, huntingRows...)
rows = append(rows, p.fishingService.ChargeInfo()...)
if p.pvpService != nil {
pvpRows, err := p.pvpService.ChargeInfo(ctx)
if err != nil {
+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() {
@@ -62,6 +55,7 @@ func (p *playerAssembly) optionalGameplay(ctx command.Context) error {
p.worldService.AttachFieldPackEconomy(p.eventEconomy)
p.datingService.AttachFirstMeeting(p.cafeteriaService.CanMeet)
p.castleService = castle.NewService(p.design.castle)
p.clearPackages.AttachProgress(p.worldService.CashPackagePackCleared, p.castleService.CashPackageTowerCleared)
p.castleService.AttachTotalWarTextCheck(p.checkProfileText)
if err := p.castleService.AttachTotalWarRuntime(p.worldService.CharacterService(), p.collection, p.ownedEquipment, p.wallet); err != nil {
return err
+20
View File
@@ -141,6 +141,26 @@ func (r *playerRegistry) Acquire(ctx context.Context, accountID string) (*player
}
}
// Touch records authenticated traffic without loading an absent player.
func (r *playerRegistry) Touch(accountID string, generation uint64) bool {
r.mu.Lock()
defer r.mu.Unlock()
slot := r.players[accountID]
if r.closing || slot == nil || slot.retiring {
return false
}
select {
case <-slot.ready:
if slot.err != nil || slot.runtime == nil || slot.runtime.Generation() != generation {
return false
}
slot.lastUsed = time.Now()
return true
default:
return false
}
}
func (r *playerRegistry) load(accountID string, slot *playerSlot) {
r.mu.Lock()
if r.closing {
@@ -304,3 +304,59 @@ func TestRegistryShutdownClosesLoadingAndLeasedAccountWriters(t *testing.T) {
}
}
}
func TestRegistryHeartbeatKeepsGenerationUntilTrafficStops(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
registry := newPlayerRegistry(factory, 15*time.Minute)
t.Cleanup(func() {
if err := registry.Close(context.Background()); err != nil {
t.Error(err)
}
})
runtime, release, err := registry.Acquire(context.Background(), accounts[0])
if err != nil {
t.Fatal(err)
}
generation := runtime.Generation()
release()
registry.mu.Lock()
slot := registry.players[accounts[0]]
slot.lastUsed = time.Now().Add(-21 * time.Minute)
stale := slot.lastUsed
registry.mu.Unlock()
if registry.Touch("absent-player", generation) || registry.Touch(accounts[0], generation+1) {
t.Fatal("unknown player or stale generation accepted")
}
registry.mu.Lock()
unchanged := slot.lastUsed.Equal(stale) && slot.leases == 0 && len(registry.players) == 1
registry.mu.Unlock()
if !unchanged {
t.Fatal("invalid heartbeat loaded or renewed a player")
}
if !registry.Touch(accounts[0], generation) {
t.Fatal("current resident heartbeat rejected")
}
registry.expire(time.Now())
current, release, err := registry.Acquire(context.Background(), accounts[0])
if err != nil {
t.Fatal(err)
}
if current != runtime || current.Generation() != generation {
release()
t.Fatal("active game replaced during local battle")
}
registryExecute(t, current, registryCommand(accounts[0], "after-long-local-battle", "/EquipInfo", appScalar(1, 1)))
release()
registry.expire(time.Now().Add(16 * time.Minute))
if registry.Touch(accounts[0], generation) {
t.Fatal("expired player resurrected")
}
replacement, release, err := registry.Acquire(context.Background(), accounts[0])
if err != nil {
t.Fatal(err)
}
defer release()
if replacement.Generation() == generation || registry.Touch(accounts[0], generation) {
t.Fatal("old generation accepted after reload")
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ func (p *playerAssembly) session(ctx command.Context) error {
return published.SupporterDetails, err
}},
p.profileService,
social.RoomCommerce{Design: p.design.roomCommerce, Rooms: p.design.rooms, Economy: p.eventEconomy},
social.RoomCommerce{Design: p.design.roomCommerce, Rooms: p.design.rooms, Economy: p.eventEconomy, PackCleared: p.worldService.CashPackagePackCleared},
commerce.PackInfoHandler{World: p.worldService, Claims: p.clearPackages},
p.worldService,
p.progressState,
@@ -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")
@@ -8,7 +8,6 @@ import (
"fmt"
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/runtime/player"
@@ -96,43 +95,6 @@ func (g *puzzleGameplay) wordCurrency() uint64 {
return balances[54]
}
func (g *puzzleGameplay) grantTokens(count uint64) {
g.t.Helper()
tx, err := g.owner.repository.BeginCommand(context.Background())
if err != nil {
g.t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
ctx := command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}
if _, err := g.owner.assembly.ownedItems.GrantOnce(ctx, fmt.Sprintf("puzzle-budget-%d", g.seq), []gamedata.BattleReward{{Type: 8, ID: 2021, Count: count}}); err != nil {
g.t.Fatal(err)
}
if err := tx.Commit(); err != nil {
g.t.Fatal(err)
}
}
func (g *puzzleGameplay) cost(field int, count uint64) []byte {
g.t.Helper()
tx, err := g.owner.repository.BeginCommand(context.Background())
if err != nil {
g.t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
items, err := g.owner.assembly.ownedItems.SelectMutable(command.Context{State: tx, InstanceIDs: g.factory.instanceIDs()}, 8, 2021, count)
if err != nil {
g.t.Fatal(err)
}
var fields []byte
for _, item := range items {
row := append(appScalar(1, item.InvenIndex), appScalar(2, item.ID)...)
row = append(row, appScalar(3, item.Type)...)
row = append(row, appScalar(4, item.Count)...)
fields = append(fields, appMessage(field, row)...)
}
return fields
}
func puzzleNumbers(t *testing.T, row []byte, wanted int) []uint64 {
t.Helper()
var numbers []uint64
@@ -163,37 +125,3 @@ func puzzleNumbers(t *testing.T, row []byte, wanted int) []uint64 {
}
return numbers
}
func (g *puzzleGameplay) info(uid uint64) []byte {
g.t.Helper()
rows := appRows(g.call("/MiniPuzzleInfo", appScalar(2, uid)), 1)
if len(rows) != 1 || appValue(rows[0], 1) != uid {
g.t.Fatalf("puzzle info does not identify schedule %d: %x", uid, rows)
}
return rows[0]
}
func puzzleResponseState(t *testing.T, response []byte, field int) []byte {
t.Helper()
rows := appRows(response, field)
if len(rows) != 1 {
t.Fatalf("puzzle response field %d: got %d rows", field, len(rows))
}
return rows[0]
}
func puzzleWordReward(t *testing.T, response []byte, itemType, id, count uint64) {
t.Helper()
bundle := puzzleResponseState(t, response, 5)
rows := appRows(bundle, 1)
if len(rows) != 1 || appValue(rows[0], 3) != itemType || appValue(rows[0], 2) != id || appValue(rows[0], 4) != count {
t.Fatalf("wrong word reward: %x; want %d/%d x %d", bundle, itemType, id, count)
}
}
// 2.36.7 MiniGamePuzzleUI.GetPossiblePlayCount bounds maximum-open by the
// available token balance and unopened cells. GameData 20261008155037 puzzle
// event 10 has 25-cell stages, token 8/2021 x 1, stage-1 word cells 1..7 with
// currency 44 x 500, stage-2 material 8/113 x 600, and a terminal stage 12.
// This exercises actual client requests, the production reward economy and
// the account SQLite transaction rather than an isolated imitation of play.
@@ -4,7 +4,10 @@ package app
import (
"context"
"fmt"
"reflect"
"slices"
"strings"
"testing"
"time"
@@ -22,6 +25,15 @@ func TestNativeRoomPurchasesAndExpansionAreAtomicAndDurable(t *testing.T) {
if err != nil {
t.Fatal(err)
}
fixtureCtx := command.Context{State: tx}
for _, pack := range []int{1, 2} {
for _, quest := range factory.design.world.Story.Packs[pack].MainQuestIDs {
if err := actor.assembly.progressState.ClearQuest(fixtureCtx, quest, pack, 0); err != nil {
_ = tx.Rollback()
t.Fatal(err)
}
}
}
_, err = actor.assembly.eventEconomy.Apply(command.Context{State: tx}, "room-commerce-fixture", nil, []gamedata.Reward{{Type: 4, Count: 3000000}, {Type: 44, Count: 300}})
if err != nil {
_ = tx.Rollback()
@@ -128,14 +140,55 @@ func TestNativeRoomPurchasesAndExpansionAreAtomicAndDurable(t *testing.T) {
slices.Sort(ids)
return ids
}
rejections := 0
reject := func(path string, fields []byte, code int, reason string) {
t.Helper()
rejections++
runtime, release, err := registry.Acquire(context.Background(), accounts[0])
if err != nil {
t.Fatal(err)
}
defer release()
request := registryCommand(accounts[0], fmt.Sprintf("room-rejection-%d", rejections), path, append(appScalar(1, uint64(rejections)), fields...))
future, err := runtime.Submit(context.Background(), request)
if err != nil {
t.Fatal(err)
}
_, err = future.Wait(context.Background())
if err == nil || !strings.Contains(err.Error(), fmt.Sprintf("game packet %d error 9003", code)) || !strings.Contains(err.Error(), reason) {
t.Fatalf("%s rejection = %v, want packet %d error 9003 containing %q", path, err, code, reason)
}
client = friendHTTPLogin(t, registry, accounts[0])
}
initialRooms := roomIDs()
client.send("/MyRoomExpand", wire.AppendBytes(wire.AppendVarint(nil, 2, 4), 3, payment(44, 200)), 418, 0)
expectedRooms := append(slices.Clone(initialRooms), 4)
// MyRoomPacket prices by owned count + 1; its requested ID is the clicked grid cell.
// Current MyRoomExpandTable stages 4/5 cost 200/350 decoration coins.
for _, id := range []uint64{0, 1, 10} {
reject("/MyRoomExpand", wire.AppendBytes(wire.AppendVarint(nil, 2, id), 3, payment(44, 200)), 418, "cannot be purchased")
}
reject("/MyRoomExpand", wire.AppendBytes(wire.AppendVarint(nil, 2, 5), 3, payment(44, 350)), 418, "matches no price")
if got := roomIDs(); !slices.Equal(got, initialRooms) {
t.Fatalf("rejected expansion changed room ownership: %v", got)
}
if got := read(); got != initial {
t.Fatalf("rejected expansion changed assets: %+v want%+v", got, initial)
}
expand := wire.AppendBytes(wire.AppendVarint(nil, 2, 5), 3, payment(44, 200))
client.send("/MyRoomExpand", expand, 418, 0)
client.seq--
client.send("/MyRoomExpand", expand, 418, 0)
expectedRooms := append(slices.Clone(initialRooms), 5)
slices.Sort(expectedRooms)
if got := roomIDs(); !slices.Equal(got, expectedRooms) {
t.Fatalf("paid room unavailable immediately: %v want%v", got, expectedRooms)
}
client.send("/MyRoomExpand", wire.AppendBytes(wire.AppendVarint(nil, 2, 4), 3, payment(44, 200)), 418, 9003)
reject("/MyRoomExpand", expand, 418, "cannot be purchased")
reject("/MyRoomExpand", wire.AppendBytes(wire.AppendVarint(nil, 2, 9), 3, payment(44, 200)), 418, "matches no price")
afterExpansion := initial
afterExpansion.coins -= 200
if got := read(); got != afterExpansion {
t.Fatalf("expansion replay or rejected purchase changed assets: %+v want%+v", got, afterExpansion)
}
client.send("/MyRoomShopBuy", buy(1, 1, 4, 500000), 246, 0)
client.seq--
client.send("/MyRoomShopBuy", buy(1, 1, 4, 500000), 246, 0)
@@ -151,7 +204,7 @@ func TestNativeRoomPurchasesAndExpansionAreAtomicAndDurable(t *testing.T) {
}
batch := wire.AppendBytes(nil, 2, row(1, 1, 4, 500000))
batch = wire.AppendBytes(batch, 2, row(2, 2, 44, 100))
client.send("/MyRoomShopMultiBuy", batch, 646, 9003)
reject("/MyRoomShopMultiBuy", batch, 646, "")
if got := read(); got != beforeFailure {
t.Fatalf("insufficient mixed-currency batch changed assets: %+v want%+v", got, beforeFailure)
}
@@ -173,7 +226,7 @@ func TestNativeRoomPurchasesAndExpansionAreAtomicAndDurable(t *testing.T) {
if !historyFound {
t.Fatal("failed batch removed previous purchase history")
}
client.send("/MyRoomShopBuy", buy(1, 1, 4, 1), 246, 9003)
reject("/MyRoomShopBuy", buy(1, 1, 4, 1), 246, "matches no price")
if got := read(); got != beforeFailure {
t.Fatalf("tampered price changed assets: %+v", got)
}
@@ -209,3 +262,78 @@ func TestNativeRoomPurchasesAndExpansionAreAtomicAndDurable(t *testing.T) {
t.Fatalf("purchase assets changed after restart: %+v want%+v", got, committed)
}
}
// Current MyRoomItemTable 101 has packId=1, questLevel=0; LocalText140059
// requires Knight of Blood Normal. MyRoomShopScrollItem uses that same gate.
func TestNativeRoomShopRequiresCompletedPackBeforeCharging(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if _, err := p.eventEconomy.Apply(ctx, "locked-room-shop-fixture", nil, []gamedata.Reward{{Type: 4, Count: 3000000}, {Type: 44, Count: 300}}); err != nil {
t.Fatal(err)
}
})
payment := func(typ, id, n uint64) []byte {
return wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 3, typ), 2, id), 4, n)
}
buy := wire.AppendVarint(wire.AppendVarint(nil, 2, 1), 3, 1)
buy = wire.AppendBytes(buy, 4, payment(4, 0, 500000))
var beforeItems any
var beforeGold uint64
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
beforeGold = p.wallet.Snapshot(ctx).Gold
beforeItems = p.ownedItems.All(ctx)
})
if _, err := s.execute("/MyRoomShopBuy", append(appScalar(1, 10), buy...)); err == nil || !strings.Contains(err.Error(), "requires pack 1 difficulty 0") {
t.Fatalf("locked purchase: %v", err)
}
s.reopen(t)
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
if p.wallet.Snapshot(ctx).Gold != beforeGold || !reflect.DeepEqual(p.ownedItems.All(ctx), beforeItems) {
t.Fatal("locked single purchase changed currency or inventory")
}
})
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
for _, quest := range factory.design.world.Story.Packs[1].MainQuestIDs {
if err := p.progressState.ClearQuest(ctx, quest, 1, 0); err != nil {
t.Fatal(err)
}
}
})
var lockedID uint64
for id, product := range factory.design.roomCommerce.Products {
if item := factory.design.rooms.Items[product.Reward.ID]; item.PackID > 1 && (lockedID == 0 || id < lockedID) {
lockedID = id
}
}
if lockedID == 0 {
t.Fatal("GameData fixture lacks another locked pack furnishing")
}
product := factory.design.roomCommerce.Products[lockedID]
price := product.Prices[0]
first := wire.AppendBytes(wire.AppendVarint(wire.AppendVarint(nil, 1, 1), 2, 1), 3, payment(4, 0, 500000))
second := wire.AppendBytes(wire.AppendVarint(wire.AppendVarint(nil, 1, lockedID), 2, 1), 3, payment(price.Type, price.ID, price.Count))
batch := wire.AppendBytes(wire.AppendBytes(appScalar(1, 11), 2, first), 2, second)
if _, err := s.execute("/MyRoomShopMultiBuy", batch); err == nil || !strings.Contains(err.Error(), "requires pack") {
t.Fatalf("mixed unlocked/locked purchase: %v", err)
}
s.reopen(t)
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
if got := p.wallet.Snapshot(ctx).Gold; got != beforeGold {
t.Fatalf("locked batch charged gold: %d want %d", got, beforeGold)
}
if !reflect.DeepEqual(p.ownedItems.All(ctx), beforeItems) {
t.Fatal("locked purchase changed inventory")
}
})
if got := s.protocol(t, "/MyRoomShopInfo", appScalar(1, 12)); len(appRows(got, 1)) != 0 {
t.Fatal("locked purchase recorded a purchase count")
}
s.protocol(t, "/MyRoomShopBuy", append(appScalar(1, 13), buy...))
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
if got := p.wallet.Snapshot(ctx).Gold; got != beforeGold-500000 {
t.Fatalf("completed pack purchase gold=%d want %d", got, beforeGold-500000)
}
})
}
+4 -5
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
@@ -102,6 +102,7 @@ func Serve(args []string) (serveErr error) {
if err != nil {
return err
}
game.TouchPlayer = registry.Touch
shared.friends.AttachPresence(game.AccountOnline)
var authHandler http.Handler
@@ -167,7 +168,7 @@ func Serve(args []string) (serveErr error) {
}
dispatcher := transport.Bootstrap{Config: c.bootstrap, Notices: c.notices, LoginsClosed: loginsClosed, Broadcast: game.Broadcast}
handler := transport.HTTP{
Dispatcher: dispatcher, Raw: game, Authentication: c.authentication,
Dispatcher: dispatcher, Raw: game, SessionActivity: game.RecordCookieActivity, Authentication: c.authentication,
AuthenticationHandler: authHandler, ResourcePolicy: c.publicResources,
CommerceManifest: func() any { return design.cashCatalog.Manifest() }, Availability: availability, InstanceID: instanceID, RealtimeTickets: realtimeTickets,
StoryCheckpoints: storyCheckpoints{game: game, players: registry}, Console: console.Handler(),
@@ -178,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)
@@ -778,3 +793,62 @@ func TestNativePVPGameplayUsesOwnedSnapshotsAndTickets(t *testing.T) {
}
}
}
// Both native matching callbacks handle errorType 2 as "Unable to find battle
// opponent" (LocalText108902), then close matching without removing a ticket.
func TestColosseumNoOpponentReturnsNativeErrorWithoutSpendingTicket(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
state, err := openSharedRuntime(context.Background(), factory.options, factory.design)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := state.store.Close(); err != nil {
t.Error(err)
}
})
factory.shared, factory.pvpSource = state, state.pvp
decks := make([][]byte, 2)
for i, account := range accounts[:2] {
actor := &guildGameplay{t: t, factory: factory, account: account}
actor.open()
decks[i], _ = actor.ownedPVPDeck()
actor.close()
}
registry := newPlayerRegistry(factory, time.Minute)
t.Cleanup(func() {
if err := registry.Close(context.Background()); err != nil {
t.Error(err)
}
})
attacker := friendHTTPLogin(t, registry, accounts[0])
ticketBefore := appValue(appRows(attacker.loginBody, 1)[0], 58)
if ticketBefore == 0 {
t.Fatal("test account has no arena ticket")
}
attacker.send("/ColosseumDeckSave", appMessage(2, decks[0]), 476, 0)
drainFriendPublications(t, registry, state, accounts[0])
for range 2 {
attacker.send("/ColosseumBattleMatching", nil, 483, 2)
}
attacker.send("/ColosseumDeckInfo", nil, 475, 0)
attacker = friendHTTPLogin(t, registry, accounts[0])
if tickets := appValue(appRows(attacker.loginBody, 1)[0], 58); tickets != ticketBefore {
t.Fatalf("empty matching spent tickets: before=%d after=%d", ticketBefore, tickets)
}
defender := friendHTTPLogin(t, registry, accounts[1])
defender.send("/ColosseumDeckSave", appMessage(2, decks[1]), 476, 0)
drainFriendPublications(t, registry, state, accounts[1])
matched := attacker.send("/ColosseumBattleMatching", nil, 483, 0)
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])
if tickets := appValue(appRows(attacker.loginBody, 1)[0], 58); tickets != ticketBefore-1 {
t.Fatalf("valid matching ticket debit=%d want %d", tickets, ticketBefore-1)
}
}
@@ -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)
}
}
@@ -366,3 +366,69 @@ func TestSkyWayCrystalDispatchUsesTorchesAndSurvivesRetryAndReopen(t *testing.T)
t.Fatal("reopened cancellation refunded torches twice")
}
}
// SkyWayEnter selects a dungeon map without SaveUserPosition; PackInGameInfo
// resets that run when returning to the ship's sole safe map (MapTable 30021).
func TestSkyWayTalentsResolveShipAndRunWithoutSavedPosition(t *testing.T) {
s := newSkyWayPlayerScenario(t)
var caster, group uint64
tx, err := s.owner.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "skyway-client"}, State: tx, InstanceIDs: s.factory.instanceIDs()}
p := s.owner.assembly
// CharTable80 has default costume801 and talent205 (FastDash); its only
// banned pack in the current TalentTable is3010, so SkyWay permits it.
if _, err := p.collection.GrantCostumes(ctx, "skyway-dash-caster", []uint64{801}, p.design.rewardCostumes); err != nil {
t.Fatal(err)
}
for _, owned := range p.collection.Characters() {
if owned.ID != 80 {
continue
}
owned.TalentLevel = 1
if err := p.collection.UpdateCharacter(ctx, owned.ID, owned); err != nil {
t.Fatal(err)
}
caster, group = owned.InvenIndex, 205
}
if caster == 0 {
t.Fatal("current GameData has no available dash caster for SkyWay")
}
if err := p.wallet.ExchangeOnce(ctx, "skyway-talent-catalyst", nil, []gamedata.Reward{{Type: 12, Count: 100}}); err != nil {
t.Fatal(err)
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
checkMap := func(want uint64) {
t.Helper()
tx, err := s.owner.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
ctx := command.Context{Identity: command.Identity{AccountID: s.account, SessionID: "skyway-client"}, State: tx}
pack, current, battle, err := s.owner.assembly.worldService.TalentFieldContext(ctx)
if err != nil || pack != 3004 || current != want || battle {
t.Fatalf("talent scene: pack=%d map=%d battle=%t err=%v, want map=%d", pack, current, battle, err, want)
}
}
checkMap(30021)
cast := s.request(caster)
reply := s.call(t, "/TalentSkillUse", cast)
if rows := appRows(reply, 1); len(rows) != 1 || appValue(rows[0], 1) != group {
t.Fatal("ship cast did not return the caster's talent state")
}
s.reopen(t)
checkMap(30021)
if replay := s.call(t, "/TalentSkillUse", cast); !bytes.Equal(reply, replay) {
t.Fatal("ship talent retry after reopen changed its acknowledged response")
}
s.call(t, "/SkyWayEnter", s.request(3004, 1, 10, 0))
checkMap(30027)
s.call(t, "/PackInGameInfo", s.request(3004))
checkMap(30021)
}
@@ -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
}
Loaded 100 of 322 files, more files were not shown because too many files have changed in this diff. Show more