Compare commits
No files matched your search
+9
-3
@@ -10,9 +10,9 @@ This started with one missed item: **Arrowward**.
|
||||
|
||||
The plan was to get it back. That grew into a small editor with item search, map filters and icons from the game. Find something, add it to your inventory, adjust its quantity or upgrade level, then save. You can recover a missed piece of gear or try another weapon without leaving the window.
|
||||
|
||||
**[Download the Windows app](https://github.com/qry6868/PBZ-Editor/releases/download/v0.3.1/PBZ-Editor-0.3.1-windows-x64.zip)** · [Release notes and checksums](https://github.com/qry6868/PBZ-Editor/releases/tag/v0.3.1)
|
||||
**[Download the Windows app](https://github.com/qry6868/PBZ-Editor/releases/download/v0.4.0/PBZ-Editor-0.4.0-windows-x64.zip)** · [Release notes and checksums](https://github.com/qry6868/PBZ-Editor/releases/tag/v0.4.0)
|
||||
|
||||
The current release is **v0.3.1 preview** for Windows x64. After a game update, the editor checks the save and item data automatically. Features that pass the checks remain available. Steam build **26266538** is the reference environment.
|
||||
The current release is **v0.4.0 preview** for Windows x64. This version adds map collection scans and batch repair. Steam build **26266538** is the reference environment for inventory editing. The editor checks compatibility after game updates.
|
||||
|
||||
## A quick look
|
||||
|
||||
@@ -32,7 +32,7 @@ These are captures of the actual app using a generated demo inventory. The file
|
||||
|
||||
## Give it a try
|
||||
|
||||
1. Download `PBZ-Editor-0.3.1-windows-x64.zip`, **extract the whole archive**, and exit the game to the desktop.
|
||||
1. Download `PBZ-Editor-0.4.0-windows-x64.zip`, **extract the whole archive**, and exit the game to the desktop.
|
||||
2. Run `PBZ-Editor.exe`. It usually finds the game and save for you. If it doesn't, choose them manually; if several accounts appear, pick your own progress.
|
||||
3. Search the item library by name, or browse by category and map. Select an item and click **Add to inventory**.
|
||||
4. Adjust its quantity or level on the right, then click **Save changes** in the top corner.
|
||||
@@ -43,6 +43,12 @@ Switch between **简体中文 / English** at the top. Pending edits stay with yo
|
||||
|
||||
If the editor says the save file changed, exit the game and choose **Reload save**. Once it opens, check the selected progress and make your changes again. Choose **Keep current edits** if you want to review your draft first.
|
||||
|
||||
## Map collection
|
||||
|
||||
Select a save slot and open **Map collection** from the toolbar. Review the eight regions that count toward map collection in the game. Choose one region or **All maps**, then use **Fill and save** to repair eligible entries with one automatic backup.
|
||||
|
||||
Blackstone and Sha-Chi Amber repairs update the pickup records and preserve their inventory quantities. Bells, challenges and entries that require further verification appear under **Entries requiring other action**. Batch saving and rescanning were verified with an isolated Steam build **26936481** save. [Validation scope and limits](docs/validation.en.md)
|
||||
|
||||
## What you can edit
|
||||
|
||||
Main weapons, phantom weapons, accessories, items and materials, medicines, and full outfits: **799 editable entries** in the supported build. Names, descriptions and icons come from your installed game, as do the map associations. Where English text is missing, the original name or internal ID stays visible.
|
||||
|
||||
@@ -10,9 +10,9 @@ Windows 离线存档编辑器 · 免费开源(MIT) · 中文 / English
|
||||
|
||||
原本只是想把它补回来,后来索性把物品搜索、地图筛选和游戏图标都做进去了:找到想要的东西,加进背包,改好数量或等级,再保存。补一件错过的装备,或是试试别的武器,都能在一个窗口里完成。
|
||||
|
||||
**[直接下载 Windows 运行包](https://github.com/qry6868/PBZ-Editor/releases/download/v0.3.1/PBZ-Editor-0.3.1-windows-x64.zip)** · [更新说明与校验和](https://github.com/qry6868/PBZ-Editor/releases/tag/v0.3.1)
|
||||
**[直接下载 Windows 运行包](https://github.com/qry6868/PBZ-Editor/releases/download/v0.4.0/PBZ-Editor-0.4.0-windows-x64.zip)** · [更新说明与校验和](https://github.com/qry6868/PBZ-Editor/releases/tag/v0.4.0)
|
||||
|
||||
目前是 **v0.3.1 预览版**,运行于 Windows x64。游戏更新后会自动检查存档和物品数据,兼容的部分可以继续编辑。参考环境为 Steam build **26266538**。
|
||||
目前是 **v0.4.0 预览版**,运行于 Windows x64。本版加入地图收集扫描和批量补齐。背包编辑的参考环境为 Steam build **26266538**,游戏更新后会自动检查兼容性。
|
||||
|
||||
## 看看怎么用
|
||||
|
||||
@@ -32,7 +32,7 @@ Windows 离线存档编辑器 · 免费开源(MIT) · 中文 / English
|
||||
|
||||
## 先用起来
|
||||
|
||||
1. 下载 `PBZ-Editor-0.3.1-windows-x64.zip`,**完整解压**,把游戏退出到桌面。
|
||||
1. 下载 `PBZ-Editor-0.4.0-windows-x64.zip`,**完整解压**,把游戏退出到桌面。
|
||||
2. 双击 `PBZ-Editor.exe`。通常会自动找到游戏和存档;没找到就手动选一下,有多个账号时选自己的进度。
|
||||
3. 在物品库搜索名称,或按类别、地图找。选中物品,点「添加到背包」。
|
||||
4. 在右侧调整数量、等级,最后点右上角的「保存存档」。
|
||||
@@ -43,6 +43,12 @@ Windows 离线存档编辑器 · 免费开源(MIT) · 中文 / English
|
||||
|
||||
如果保存时提示存档已更新,先退出游戏,再点「重新读取存档」。读取成功后,请确认上方的进度,再按最新背包重新修改。想先查看旧草稿,可以点「保留当前修改」。
|
||||
|
||||
## 地图收集
|
||||
|
||||
选中进度槽后,点顶部的「地图收集」。可以查看游戏计入收集度的 8 张区域地图,选择单张或「全部地图」,再用「补齐并保存」处理可补齐的缺项。一次操作会自动备份一次。
|
||||
|
||||
黑石和杀气琥珀碎片只补对应领取点的地图记录,避免重复增加背包数量。铃铛、挑战和当前无法确认的缺项会列在「需另行处理」。地图收集适用于已核对的游戏数据,Steam build **26936481** 已用隔离副本验证批量写入和重新扫描。 [测试范围与限制](docs/validation.zh-CN.md)
|
||||
|
||||
## 能改什么
|
||||
|
||||
主武器、影之武装、饰品、道具材料、药品和完整服装,目前共有 **799 个可编辑条目**。物品名称、说明和图标都从本机游戏读取,地图筛选也来自游戏里的关联信息。英文资源缺少翻译的地方,会保留原名或内部 ID。
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# pbz-editor · 中文说明
|
||||
|
||||
> 本仓库是上游 [qry6868/PBZ-Editor](https://github.com/qry6868/PBZ-Editor) 的 Gitea 镜像(全量镜像,含 4 个 tag),**代码与版权归原作者**。
|
||||
> 中文说明与服务器构建记录由镜像方补充;许可证:MIT。
|
||||
|
||||
## 这是什么
|
||||
|
||||
离线存档与背包编辑器(Windows 桌面,PySide6)。不注入游戏进程,直接读写《影之刃零》的存档文件:物品库检索、按地图筛选、加入背包、改数量/强化等级、撤销与自动备份。
|
||||
|
||||
## 安装 / 使用
|
||||
|
||||
1. Windows 下解压发布包,运行 `PBZ-Editor.exe`(或 `python launcher.py`)。
|
||||
2. 首次启动选择存档目录(默认在 `%LOCALAPPDATA%\..\Saved\SaveGames` 一类路径,程序也会自动探测)。
|
||||
3. 改动前程序会自动备份;右键物品可改数量、强化、品质。
|
||||
4. 改完保存,再进游戏读取。**改存档前请自己再复制一份**,游戏更新后存档结构可能变。
|
||||
|
||||
## 服务器构建(Linux,已实测)
|
||||
|
||||
```bash
|
||||
# 依赖:python3(>=3.11)、pip
|
||||
cd /opt/build/pbz
|
||||
python3 -m pip wheel --no-deps -w dist/pbz-editor pbz-editor # 出 wheel
|
||||
tar czf dist/pbz-editor/pbz-editor-src-0.4.0.tar.gz --exclude=.git -C . pbz-editor
|
||||
```
|
||||
说明:Linux 上**不能**直接产出 Windows exe(PyInstaller 需在 Windows 上跑)。服务器构建产出的是 wheel 与源码包,Windows 发布包请用上游 Release 或在 Windows 上按下面的原生构建走一遍。
|
||||
|
||||
## Windows 原生构建
|
||||
|
||||
```powershell
|
||||
python -m venv .venv; .\.venv\Scripts\activate
|
||||
pip install -r requirements-dev.txt
|
||||
pip install -e .
|
||||
python launcher.py # 开发运行
|
||||
pyinstaller pbz_editor.spec # 需仓库自带 spec,或 pyinstaller launcher.py --name PBZ-Editor --windowed
|
||||
```
|
||||
|
||||
## 版本与兼容
|
||||
|
||||
- 上游版本:`0.4.0`
|
||||
- 上游地址:https://github.com/qry6868/PBZ-Editor
|
||||
- 镜像时间:2026-11-30
|
||||
|
||||
## 注意
|
||||
|
||||
物品图标来自游戏资源,仓库不含游戏本体素材;请自备正版游戏。
|
||||
|
||||
---
|
||||
|
||||
*本文档由镜像方自动生成;构建步骤在服务器(OpenCloudOS 9 / x86_64)上验证。Windows 专属工具链(MSVC / .NET Framework / PowerShell)无法在 Linux 运行,已在对应小节注明。*
|
||||
@@ -1,4 +1,4 @@
|
||||
PBZ Editor 0.3.1 — Start here
|
||||
PBZ Editor 0.4.0 — Start here
|
||||
简体中文: START-HERE.txt
|
||||
|
||||
1. Extract the complete archive. Keep the EXE and _internal folder together.
|
||||
@@ -8,6 +8,7 @@ PBZ Editor 0.3.1 — Start here
|
||||
5. Switch 简体中文 / English at the top. Backups are created before saving; use Backups to view or restore them.
|
||||
|
||||
If the save file changed, exit the game and choose Reload save. Once it opens, make your changes again using the updated progress.
|
||||
Open Map collection from the toolbar to check for gaps. Choose one region or All maps, review the results and select Fill and save.
|
||||
|
||||
Runs on Windows x64. Steam build 26266538 is the tested reference; updates are checked automatically.
|
||||
Incompatible categories become read-only. Search and category browsing work without maps. Unverifiable saves are not written.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
PBZ Editor 0.3.1 — 开始使用
|
||||
PBZ Editor 0.4.0 — 开始使用
|
||||
English: START-HERE.en.txt
|
||||
|
||||
1. 完整解压运行包,保留 EXE 及 _internal 文件夹。
|
||||
@@ -8,6 +8,7 @@ English: START-HERE.en.txt
|
||||
5. 顶部可以切换简体中文 / English。保存前自动备份,顶部“备份”可查看和恢复。
|
||||
|
||||
如果提示存档已更新,先退出游戏,再选“重新读取存档”。读取成功后按最新进度重新修改。
|
||||
地图缺项可以点顶部“地图收集”查看。选择单张地图或“全部地图”,确认结果后点“补齐并保存”。
|
||||
|
||||
运行环境:Windows x64。参考验证版本为 Steam build 26266538,其他更新自动检查兼容性。
|
||||
不兼容的类别会设为只读;地图不可用时仍可搜索和按类别查找。无法验证的存档不会写入。
|
||||
|
||||
@@ -9,6 +9,7 @@ Steam build **26266538** is the reference environment. Since v0.3.0, the editor
|
||||
| Automated tests | Synthetic saves cover read/write boundaries, backups, external changes, untouched slots, UI behavior and language switching; they run without game resources |
|
||||
| Local game resources | 844 catalog entries, 799 editable entries and 714 item icons; compared against the local baseline using installed game text and map data |
|
||||
| File roundtrip | Disposable copies passed edits, export, backup, restore and independent decoder checks; unrelated JSON and untouched slots were checked |
|
||||
| Map collection | The packaged v0.4.0 editor scanned eight map regions using Steam build **26936481** data and an isolated save. Readback confirmed one repair per region, one exact backup and unchanged ciphertext for the other slots. The in-game map panel still needs a separate test |
|
||||
| Game readback | Five categories passed load, manual save, exit and readback in v0.2.0. For v0.3.1, an isolated save from Steam build **26367565** was used to verify save conflict recovery and confirm a count of 7 Blackstone fragments in the game inventory |
|
||||
| Automatic compatibility | Synthetic cases cover EXE changes, key relocation/rotation, future containers, category failures and updates during checks; reference resources also receive in-memory value-change and layout-corruption checks |
|
||||
| Packaged app | Locally checked fresh data, Chinese/space paths, minimal PATH, portable mode, migration, subsequent launch, backup-preserving upgrades and error handling |
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
| 自动测试 | 合成存档覆盖读写、边界、备份、外部变化拦截、未修改槽保护、界面与语言切换;可在无游戏资源的机器运行 |
|
||||
| 本机资源 | 844 条目录、799 条可编辑、714 个物品图标;与本机基准比较,文字与地图信息来自已安装游戏 |
|
||||
| 文件往返 | 本机副本通过修改、导出、备份、恢复与独立解码检查;验证未修改槽和无关 JSON 保留 |
|
||||
| 地图收集 | v0.4.0 用 Steam build **26936481** 的游戏数据和隔离存档,在打包后的修改器扫描了 8 张区域地图。每张图各补一项,重新读取后确认共补 8 项、只生成一份备份,其他存档槽密文一致。游戏内地图面板待实测 |
|
||||
| 游戏回读 | v0.2.0 的五类样品(道具、主武器、影之武装、饰品、药品)通过载入、手动保存、退出后回读。v0.3.1 在 Steam build **26367565** 的隔离副本上验证了存档冲突恢复,并确认修改后的黑石碎片数量在游戏背包显示为 7 个 |
|
||||
| 自动兼容 | 合成样本覆盖 EXE 变化、密钥移动/轮换、未来容器只读、单类别异常和检查期间更新;真实参考资源另做内存数值变更与布局损坏检查 |
|
||||
| 运行包 | 本机新数据目录、中文空格路径、精简 PATH、便携模式、旧数据迁移、再次启动、升级保留备份及错误提示已检查 |
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
"""PBZ Editor: local inventory and save editing for Phantom Blade Zero."""
|
||||
__version__ = "0.3.1"
|
||||
__version__ = "0.4.0"
|
||||
+9
-3
@@ -890,6 +890,9 @@ class SaveSession:
|
||||
|
||||
def _candidate(self, slot: str, operations: list[dict], compression="preserve"):
|
||||
replacements,changes = self._edit_plan(slot,operations)
|
||||
return self._encode_checked(replacements, compression), changes
|
||||
|
||||
def _encode_checked(self, replacements, compression="preserve"):
|
||||
candidate = self.container.encode(self.entries, replacements, compression) if replacements else self.source
|
||||
checked = self.container.decode(candidate)
|
||||
if len(checked) != len(self.entries):
|
||||
@@ -899,7 +902,7 @@ class SaveSession:
|
||||
raise EditorError("写出校验失败。")
|
||||
if before["name"] not in replacements and (before["raw"] != after["raw"] or before["block"] != after["block"]):
|
||||
raise EditorError("非目标存档槽发生变化,已取消写入。")
|
||||
return candidate, changes
|
||||
return candidate
|
||||
|
||||
def preview(self, slot: str, operations: list[dict]) -> dict:
|
||||
replacements,changes = self._edit_plan(slot,operations)
|
||||
@@ -984,10 +987,13 @@ class SaveSession:
|
||||
"operation_count": len(changes), 'affected_slots':list(dict.fromkeys(c['slot'] for c in changes)), "file_verified": True, "game_runtime_verified": False}
|
||||
|
||||
def apply(self, slot: str, operations: list[dict], compression="preserve") -> dict:
|
||||
return self._apply_candidate(slot, lambda: self._candidate(slot, operations, compression))
|
||||
|
||||
def _apply_candidate(self, slot, make_candidate, *, running_message=None):
|
||||
if _game_processes(self.game_dir):
|
||||
raise EditorError("游戏仍在运行。请完全退出游戏到桌面,再点击保存存档。")
|
||||
raise EditorError(running_message or "游戏仍在运行。请完全退出游戏到桌面,再点击保存存档。")
|
||||
self._check_source()
|
||||
candidate, changes = self._candidate(slot, operations, compression)
|
||||
candidate, changes = make_candidate()
|
||||
if candidate == self.source:
|
||||
return {"destination": str(self.save_path), "backup_path": None, "sha256": self.source_sha256,
|
||||
"slot": slot, "operation_count": 0, "file_verified": True, "game_runtime_verified": False}
|
||||
|
||||
@@ -84,6 +84,35 @@
|
||||
"已移出背包 · 可撤销": "Removed from inventory · Undo available",
|
||||
"已解锁": "Unlocked",
|
||||
"庞镇": "庞镇",
|
||||
"后街": "Backstreet",
|
||||
"地图收集": "Map collection",
|
||||
"扫描当前进度槽的地图收集": "Scan map collection in the selected save slot",
|
||||
"正在扫描地图收集…": "Scanning map collection…",
|
||||
"地图收集已扫描。": "Map collection scan completed.",
|
||||
"所选地图收集已齐全。": "Collection is complete in the selected maps.",
|
||||
"全部地图": "All maps",
|
||||
"收集范围": "Collection scope",
|
||||
"收集扫描结果": "Collection scan results",
|
||||
"当前进度槽 {0}": "Selected save slot {0}",
|
||||
"铃铛": "Bells",
|
||||
"武器及影之武装": "Weapons and phantom weapons",
|
||||
"饰品及药瓶": "Accessories and medicines",
|
||||
"挑战地点": "Challenge sites",
|
||||
"杀气琥珀碎片": "Sha-Chi Amber fragments",
|
||||
"黑石碎片": "Blackstone fragments",
|
||||
"记忆之花": "Memory Flowers",
|
||||
"可补齐 {0} 项。碎片只补地图领取记录,背包数量保持原样。": "{0} entries can be filled. Fragment pickup records are updated and inventory quantities stay the same.",
|
||||
"有 {0} 项需在游戏里处理,或当前存档暂不支持自动补齐。": "{0} entries need in-game action or are unavailable for automatic repair in this save.",
|
||||
"可补齐的项目": "Entries available to fill",
|
||||
"需另行处理的项目": "Entries requiring other action",
|
||||
"补齐并保存": "Fill and save",
|
||||
"正在补齐地图收集并保存…": "Filling map collection and saving…",
|
||||
"已补齐 {0} 项地图收集,已自动备份。": "Filled {0} collection entries and created a backup.",
|
||||
"当前游戏版本的地图收集数据尚未验证,已取消扫描。": "Map collection data for this game version has not been verified. The scan was cancelled.",
|
||||
"所选进度的地图收集记录无法识别。": "The selected slot has unrecognized map collection records.",
|
||||
"所选地图不在当前的收集数据中。": "The selected map is not in the current collection data.",
|
||||
"地图收集校验未通过,已取消写入。": "Map collection verification failed. Writing was cancelled.",
|
||||
"游戏仍在运行。请完全退出游戏到桌面,再扫描并补齐。": "The game is still running. Exit to the desktop, then scan and fill again.",
|
||||
"开始使用": "Get started",
|
||||
"强化": "Upgrade",
|
||||
"当前用户数据目录不可写。请检查权限,或将完整运行包解压到可写文件夹并放入 portable.flag 以使用便携模式。": "The user data directory is not writable. Check its permissions, or extract the full package to a writable folder and add portable.flag to use portable mode.",
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
"""Scan the game's collection regions and fill verified gaps in one save slot."""
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import re
|
||||
import struct
|
||||
|
||||
from .core import CATEGORY_FIELDS, EditorError, LosslessJSON, SaveChangedError, edit_inventory, sha256
|
||||
from .pak_reader import PakReader
|
||||
from .region_builder import debug_map, fname, header, read_map_groups, u32
|
||||
from .resources_reader import IoStore, Reader, name_batch
|
||||
|
||||
|
||||
BUCKETS = {
|
||||
'BellDatas': 'bells', 'WeaponItemDatas': 'weapons', 'ShaChiWeaponItemDatas': 'weapons',
|
||||
'AccessoryItemDatas': 'equipment', 'MedicineItemDatas': 'equipment',
|
||||
'RongShu': 'challenges', 'LongZhu': 'challenges', 'DaoCaoRen': 'challenges',
|
||||
'HupoItemData': 'amber', 'HeiShiItemData': 'blackstone', 'MemoryFlowerData': 'flowers',
|
||||
}
|
||||
ITEM_CATEGORIES = {
|
||||
'WeaponItemDatas': 'weapon', 'ShaChiWeaponItemDatas': 'phantom',
|
||||
'AccessoryItemDatas': 'accessory', 'MedicineItemDatas': 'medicine', 'MemoryFlowerData': 'goods',
|
||||
}
|
||||
NATIVE_ARRAYS = (
|
||||
'BellDatas', 'HeiShiItemData', 'HupoItemData', 'MemoryFlowerData', 'YaoShiItemData',
|
||||
'PrimaryItemData', 'WeaponItemDatas', 'ShaChiWeaponItemDatas', 'AccessoryItemDatas',
|
||||
'MedicineItemDatas', 'RongShu', 'LongZhu', 'DaoCaoRen',
|
||||
)
|
||||
RESOURCE_ERROR = '当前游戏版本的地图收集数据尚未验证,已取消扫描。'
|
||||
SAVE_ERROR = '所选进度的地图收集记录无法识别。'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Point:
|
||||
map_id: str
|
||||
kind: str
|
||||
item_id: str
|
||||
actor: str = 'None'
|
||||
domain: str = 'None'
|
||||
nodes: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CollectionRegion:
|
||||
map_ids: tuple[str, ...]
|
||||
points: tuple[Point, ...]
|
||||
|
||||
|
||||
def _decode_points(data):
|
||||
names, _ = name_batch(data)
|
||||
fields, zeros, pos = header(data, u32(data, 4))
|
||||
count = u32(data, pos + 4)
|
||||
if fields != [0, 1] or zeros or u32(data, pos) or not 1 <= count <= 30:
|
||||
raise ValueError('Invalid map item table')
|
||||
pos += 8
|
||||
maps = {}
|
||||
base = ('name', 'name', 'nodes', 'name', 'name', 'name', 'position')
|
||||
for _ in range(count):
|
||||
map_id, pos = fname(data, pos, names)
|
||||
fields, zeros, pos = header(data, pos)
|
||||
if fields != list(range(len(NATIVE_ARRAYS))) or zeros or map_id.casefold() in maps:
|
||||
raise ValueError('Invalid map item arrays')
|
||||
points = maps[map_id.casefold()] = []
|
||||
for kind in NATIVE_ARRAYS:
|
||||
length = u32(data, pos)
|
||||
pos += 4
|
||||
schema = ('name', 'name', 'position') if kind == 'BellDatas' else base
|
||||
if kind in ITEM_CATEGORIES and kind != 'MemoryFlowerData':
|
||||
schema = ('name',) + schema
|
||||
if length > 500:
|
||||
raise ValueError('Invalid collection array size')
|
||||
for _ in range(length):
|
||||
fields, zeros, pos = header(data, pos)
|
||||
if fields != list(range(len(schema))):
|
||||
raise ValueError('Invalid collection point')
|
||||
values = []
|
||||
for i, field in enumerate(schema):
|
||||
if i in zeros:
|
||||
values.append(() if field == 'nodes' else 'None')
|
||||
elif field == 'name':
|
||||
# Native actor instance names use the full FName number range.
|
||||
value, pos = fname(data, pos, names, max_number=0xffffffff)
|
||||
values.append(value)
|
||||
elif field == 'position':
|
||||
pos += 12
|
||||
values.append(None)
|
||||
else:
|
||||
reader = Reader(data, pos)
|
||||
node_count = reader.u32()
|
||||
if node_count > 100:
|
||||
raise ValueError('Invalid collection node count')
|
||||
values.append(tuple(reader.fstring() for _ in range(node_count)))
|
||||
pos = reader.p
|
||||
if kind == 'BellDatas':
|
||||
ident, point_map, _ = values
|
||||
point = Point(map_id, kind, ident)
|
||||
else:
|
||||
actor, item, nodes, domain, _, point_map, _ = values[-7:]
|
||||
point = Point(map_id, kind, values[0] if len(values) == 8 else item, actor, domain, nodes)
|
||||
if point_map.casefold() != map_id.casefold():
|
||||
raise ValueError('Mismatched collection map')
|
||||
if kind in BUCKETS:
|
||||
points.append(point)
|
||||
_, end = debug_map(data, pos, names)
|
||||
if end != len(data) - 4 or data[end:] != b'\0' * 4:
|
||||
raise ValueError('Invalid map item table boundary')
|
||||
return maps
|
||||
|
||||
|
||||
def _build_regions(points, map_groups, merge_groups, excluded):
|
||||
# Match the game's map panel grouping. Some display maps contain several
|
||||
# native submaps, whose collection points appear on the same panel.
|
||||
groups = {key.casefold(): tuple(dict.fromkeys(name.casefold() for name in (members or [key])))
|
||||
for key, members in map_groups.items()}
|
||||
for key, members in merge_groups.items():
|
||||
merged = dict.fromkeys(members)
|
||||
for name in members:
|
||||
merged.update(dict.fromkeys(groups.get(name, ())))
|
||||
if name != key:
|
||||
groups.pop(name, None)
|
||||
groups[key] = tuple(merged)
|
||||
regions, included = {}, set()
|
||||
for key, members in groups.items():
|
||||
allowed = tuple(name for name in members if name not in excluded)
|
||||
entries = tuple(point for name in allowed for point in points.get(name, ()))
|
||||
if not entries:
|
||||
continue
|
||||
if included.intersection(allowed):
|
||||
raise ValueError('Overlapping collection maps')
|
||||
included.update(allowed)
|
||||
regions[key] = CollectionRegion(allowed, entries)
|
||||
if not regions or {name for name, entries in points.items() if entries and name not in excluded} - included:
|
||||
raise ValueError('Incomplete collection map coverage')
|
||||
return regions
|
||||
|
||||
|
||||
def _load_regions(session):
|
||||
session._check_game()
|
||||
root = session.game_dir / 'ProjectPBZ/Content/Paks'
|
||||
codec = session.container.codec
|
||||
try:
|
||||
pak = PakReader(root / 'ProjectPBZ-Windows.pak', codec)
|
||||
rules = pak.read_file('ProjectPBZ/Content/JavaScript/UI/Widget/Foundation/MapItemCompletion.js')
|
||||
map_panel = pak.read_file('ProjectPBZ/Content/JavaScript/UI/Widget/Map.js')
|
||||
total_rules = pak.read_file('ProjectPBZ/Content/JavaScript/Library/MapItemCompletionCalc.js')
|
||||
group_rules = pak.read_file('ProjectPBZ/Content/JavaScript/Library/MapAreaGroups.js')
|
||||
store = IoStore(root / 'ProjectPBZ-Windows.utoc', codec)
|
||||
assets = {path.casefold(): path for path in store.files}
|
||||
data = store.read_file(assets['projectpbz/content/pbzcontent/maps/dt_mapitemdata.uasset'])
|
||||
groups_data = store.read_file(assets['projectpbz/content/pbzcontent/ui/ingame/map/da_mapidasset.uasset'])
|
||||
inventory = store.read_file(assets['projectpbz/content/pbzcontent/datatable/item/dt_inventorydata.uasset'])
|
||||
# These fingerprints bind point records, panel rules and the game's
|
||||
# exclusions. Flower points on the included maps are F_/FS_ entries.
|
||||
if (sha256(rules) not in ('031ff506593d2efb6ce7eda60e87cbecb8c58e137e1ca0f6a660dcde29144b8e',
|
||||
'dc7a7f44aa7af0e4f6816bed2c5afe3b6316fa7619de9ca25816f76c437f95f5')
|
||||
or sha256(map_panel) not in ('3ccc47ea79060153c8e824a16c0a358d208bb7dcab343fdf5b348b2cd1f87bb8',
|
||||
'44e6a10741403af0cc5dee63ec816dd2096a71d08668ec8f864994ceb945dc70')
|
||||
or sha256(total_rules) not in ('e1a363d0e5e00985338da53d628c3e861c6bb9b67b2098de8dbe6bf7a412dcf8',
|
||||
'cd832b207f1fe2a03126ec17d032acac9c1733c16f2766618b238d7842c6f4a7')
|
||||
or sha256(group_rules) not in ('dbeaca0b683da5fc5e9aae7d32a8254590130f0d67be590b1e7d9946952419e4',
|
||||
'3243861835d4d97545bbb8ff73d3cd2443fc228aa806db3b9193951a96323886')
|
||||
or sha256(data) != '64010746ef71ac987d9261c4251d733bacc4780feb44b5dbbe55c33bbe5624d1'
|
||||
or sha256(groups_data) != '08c28b715674bdeae1df52c7ffddba662b7d8b2676507320c64c3aa583c3f0c7'
|
||||
or sha256(inventory) != '9bd49f00745d39b08dde6fa3ef8ce1b7020baa00b5e1c5842293625facf6ab65'):
|
||||
raise ValueError('Unverified collection resources')
|
||||
excluded = json.loads(re.search(rb'const TOTAL_COMPLETION_EXCLUDED_MAP_IDS = (\[[^;]+\]);', total_rules).group(1))
|
||||
merge_literal = re.search(rb'const MAP_MERGE_GROUPS = (\{[^;]+\});', group_rules).group(1)
|
||||
merge_groups = json.loads(re.sub(rb',\s*}', b'}', merge_literal))
|
||||
regions = _build_regions(_decode_points(data), read_map_groups(groups_data), merge_groups, set(excluded))
|
||||
if any(point.kind == 'MemoryFlowerData' and not point.item_id.startswith(('F_', 'FS_'))
|
||||
for region in regions.values() for point in region.points):
|
||||
raise ValueError('Unverified flower point')
|
||||
return regions
|
||||
except (OSError, ValueError, AttributeError, IndexError, KeyError, struct.error) as error:
|
||||
raise EditorError(RESOURCE_ERROR) from error
|
||||
|
||||
|
||||
def _key_index(value):
|
||||
if not isinstance(value, dict):
|
||||
raise EditorError(SAVE_ERROR)
|
||||
index = {key.casefold(): key for key in value}
|
||||
if len(index) != len(value):
|
||||
raise EditorError(SAVE_ERROR)
|
||||
return index
|
||||
|
||||
|
||||
def _name_list(value):
|
||||
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
|
||||
raise EditorError(SAVE_ERROR)
|
||||
return {item.casefold() for item in value}
|
||||
|
||||
|
||||
def _plan(session, slot, data, points, catalog):
|
||||
try:
|
||||
system = data['PBZGameSystem']
|
||||
cycle = system['CycleCount']
|
||||
if type(cycle) is not int or cycle < 0:
|
||||
raise EditorError(SAVE_ERROR)
|
||||
domains = _name_list(system.get('CompleteAddItemMobDomainNames', []))
|
||||
actors = _key_index(data['LevelActorManager'])
|
||||
nodes = _key_index(data['EventPipeline']['ExecuteNodeGuid'])
|
||||
bells = _name_list(data['BellManager']['ActivateBellIDs']) | _name_list(data['BellManager']['ActivateCraneBellIDs'])
|
||||
inventories = data['Inventory']
|
||||
indexes = {cat: _key_index(inventories.get(CATEGORY_FIELDS[cat], {})) for cat in ITEM_CATEGORIES.values()}
|
||||
except (TypeError, KeyError, AttributeError) as error:
|
||||
raise EditorError(SAVE_ERROR) from error
|
||||
totals = {bucket: [0, 0] for bucket in ('bells', 'weapons', 'equipment', 'challenges', 'amber', 'blackstone', 'flowers')}
|
||||
fixes, unresolved, seen = [], [], set()
|
||||
for point in points:
|
||||
kind, ident = point.kind, point.item_id.casefold()
|
||||
category = ITEM_CATEGORIES.get(kind)
|
||||
if kind == 'BellDatas' or category and category != 'goods':
|
||||
if (kind, ident) in seen:
|
||||
continue
|
||||
seen.add((kind, ident))
|
||||
bucket = BUCKETS[kind]
|
||||
label = point.item_id
|
||||
fix = None
|
||||
if category:
|
||||
field = CATEGORY_FIELDS[category]
|
||||
key = indexes[category].get(ident)
|
||||
record = inventories[field].get(key) if key else None
|
||||
acquired = record.get('AcquiredCycle') if isinstance(record, dict) else None
|
||||
collected = type(acquired) is int and acquired == cycle
|
||||
item = catalog.get(point.item_id, category)
|
||||
if not collected and item and item.get('supported', True) and not item.get('experimental') and session.can_edit(slot, category):
|
||||
if key is None:
|
||||
operation = {'action': 'add', 'category': category, 'id': item['id'], 'name': item['name']}
|
||||
if 'base_capacity' in item:
|
||||
operation['base_capacity'] = item['base_capacity']
|
||||
fix = ('inventory', operation)
|
||||
elif isinstance(record, dict) and (acquired is None or type(acquired) is int and acquired <= cycle):
|
||||
fix = ('set', (['Inventory', field, key, 'AcquiredCycle'], cycle))
|
||||
elif kind == 'BellDatas':
|
||||
collected = ident in bells
|
||||
else:
|
||||
executed = any(node.casefold() in nodes for node in point.nodes)
|
||||
actor, domain = point.actor.casefold(), point.domain.casefold()
|
||||
if bucket == 'challenges':
|
||||
collected = executed
|
||||
label = point.nodes[0] if point.nodes else kind
|
||||
else:
|
||||
collected = (executed or (domain != 'none' and domain in domains) or
|
||||
(actor != 'none' and (actor in actors or actor.split('-', 1)[-1] in actors)))
|
||||
label = point.actor if actor != 'none' else point.domain if domain != 'none' else point.item_id
|
||||
if not collected:
|
||||
if domain != 'none' and actor == 'none' and not point.nodes:
|
||||
fix = ('domain', point.domain)
|
||||
elif actor != 'none' and domain == 'none' and not point.nodes:
|
||||
actor_name = actor.split('-', 1)[-1]
|
||||
state = {'SwitchState': True} if actor_name.startswith('bp_chest_c_') else {'Destroy': True} if actor_name.startswith('bp_rubbish_c_') else None
|
||||
if state:
|
||||
fix = ('set', (['LevelActorManager', point.actor], state))
|
||||
totals[bucket][0] += int(collected)
|
||||
totals[bucket][1] += 1
|
||||
if not collected:
|
||||
detail = (bucket, point.map_id, label)
|
||||
if fix and not session.read_only:
|
||||
fixes.append((detail, fix))
|
||||
else:
|
||||
unresolved.append(detail)
|
||||
return totals, fixes, unresolved
|
||||
|
||||
|
||||
def _points_in_scope(regions, scope):
|
||||
if scope is None:
|
||||
return tuple(point for region in regions.values() for point in region.points)
|
||||
if scope not in regions:
|
||||
raise EditorError('所选地图不在当前的收集数据中。')
|
||||
return regions[scope].points
|
||||
|
||||
|
||||
def scan_collection(session, slot, catalog):
|
||||
data = session._entry(slot)['json']
|
||||
regions = _load_regions(session)
|
||||
|
||||
def describe(scope):
|
||||
totals, fixes, unresolved = _plan(session, slot, data, _points_in_scope(regions, scope), catalog)
|
||||
return {'totals': totals, 'fixable': [detail for detail, _ in fixes], 'unresolved': unresolved}
|
||||
|
||||
reports = {scope: describe(scope) for scope in regions}
|
||||
reports[None] = describe(None)
|
||||
level = data['PBZGameSystem'].get('CurrentLevelName', '')
|
||||
level_id = level.casefold().removeprefix('pbz_').removesuffix('_wp') if isinstance(level, str) else ''
|
||||
current_region = next((key for key, region in regions.items() if level_id in region.map_ids), None)
|
||||
return {'scopes': reports, 'current_region': current_region, 'source_sha256': session.source_sha256}
|
||||
|
||||
|
||||
def apply_collection(session, slot, catalog, scope, expected_source_sha256):
|
||||
if session.source_sha256 != expected_source_sha256:
|
||||
raise SaveChangedError('存档已被游戏或其他程序更新。请重新打开存档,再应用修改。')
|
||||
|
||||
def candidate():
|
||||
points = _points_in_scope(_load_regions(session), scope)
|
||||
entry = session._entry(slot)
|
||||
_, fixes, unresolved = _plan(session, slot, entry['json'], points, catalog)
|
||||
if not fixes:
|
||||
return session.source, []
|
||||
plans = [fix for _, fix in fixes]
|
||||
inventory_ops = {(value['category'], value['id'].casefold()): value for kind, value in plans if kind == 'inventory'}
|
||||
raw = entry['raw']
|
||||
if inventory_ops:
|
||||
raw, _ = edit_inventory(raw, list(inventory_ops.values()))
|
||||
editor = LosslessJSON(raw)
|
||||
domains = [value for kind, value in plans if kind == 'domain']
|
||||
if domains:
|
||||
original = entry['json']['PBZGameSystem'].get('CompleteAddItemMobDomainNames', [])
|
||||
editor.set(['PBZGameSystem', 'CompleteAddItemMobDomainNames'], original + list(dict.fromkeys(domains)))
|
||||
updates = {}
|
||||
for kind, value in plans:
|
||||
if kind == 'set':
|
||||
path, field = value
|
||||
updates[tuple(path)] = field
|
||||
for path, field in updates.items():
|
||||
editor.set(path, field)
|
||||
modified = editor.bytes()
|
||||
_, remaining, unresolved_after = _plan(session, slot, json.loads(modified), points, catalog)
|
||||
if remaining or unresolved_after != unresolved:
|
||||
raise EditorError('地图收集校验未通过,已取消写入。')
|
||||
changes = [{'slot': slot} for _ in fixes]
|
||||
return session._encode_checked({slot: modified}), changes
|
||||
|
||||
return session._apply_candidate(slot, candidate, running_message='游戏仍在运行。请完全退出游戏到桌面,再扫描并补齐。')
|
||||
@@ -5,9 +5,9 @@ from .resources_reader import Reader,name_batch
|
||||
def u32(b, p): return struct.unpack_from('<I', b, p)[0]
|
||||
|
||||
|
||||
def fname(b, p, names):
|
||||
def fname(b, p, names, max_number=1_000_000):
|
||||
index, number = struct.unpack_from('<II', b, p)
|
||||
if index >= len(names) or number > 1000000: raise ValueError('FName invalid')
|
||||
if index >= len(names) or number > max_number: raise ValueError('FName invalid')
|
||||
return names[index] + (f'_{number - 1}' if number else ''), p + 8
|
||||
|
||||
|
||||
@@ -50,6 +50,31 @@ def debug_map(b, p, names):
|
||||
return result, p
|
||||
|
||||
|
||||
def read_map_groups(data):
|
||||
names, _ = name_batch(data)
|
||||
_, _, pos = header(data, u32(data, 4))
|
||||
count = u32(data, pos + 4)
|
||||
if u32(data, pos) or not 1 <= count <= 30:
|
||||
raise ValueError('Invalid map groups')
|
||||
pos += 8
|
||||
groups = {}
|
||||
for _ in range(count):
|
||||
parent, pos = fname(data, pos, names)
|
||||
fields, zeros, pos = header(data, pos)
|
||||
length = u32(data, pos)
|
||||
if fields != [0] or zeros or parent in groups or length > 30:
|
||||
raise ValueError('Invalid map group')
|
||||
pos += 4
|
||||
children = []
|
||||
for _ in range(length):
|
||||
child, pos = fname(data, pos, names)
|
||||
children.append(child)
|
||||
groups[parent] = children
|
||||
if pos != len(data) - 4:
|
||||
raise ValueError('Invalid map group boundary')
|
||||
return groups
|
||||
|
||||
|
||||
def build_regions(assets, loc, catalog_data, group_script_text, english=None):
|
||||
b = assets['DT_MapItemData']; names, _ = name_batch(b)
|
||||
if hashlib.sha256(b).hexdigest() != '64010746ef71ac987d9261c4251d733bacc4780feb44b5dbbe55c33bbe5624d1':
|
||||
@@ -112,17 +137,7 @@ def build_regions(assets, loc, catalog_data, group_script_text, english=None):
|
||||
assert len(rows) == declared
|
||||
|
||||
# Official big-map/sub-map relation; merge only if names are also equal.
|
||||
ab = assets['DA_MapIDAsset']; an, _ = name_batch(ab)
|
||||
_, _, ap = header(ab, u32(ab, 4)); assert u32(ab, ap) == 0
|
||||
n = u32(ab, ap + 4); ap += 8; groups = {}
|
||||
for _ in range(n):
|
||||
parent, ap = fname(ab, ap, an); fields, zeros, ap = header(ab, ap)
|
||||
assert fields == [0] and not zeros
|
||||
length = u32(ab, ap); ap += 4; children = []
|
||||
for _ in range(length):
|
||||
child, ap = fname(ab, ap, an); children.append(child)
|
||||
groups[parent] = children
|
||||
assert ap == len(ab) - 4
|
||||
groups = read_map_groups(assets['DA_MapIDAsset'])
|
||||
canonical = {ident: ident for ident in native_ids}
|
||||
for parent, children in groups.items():
|
||||
parent_native = next((i for i in native_ids if i.casefold() == parent.casefold()), None)
|
||||
|
||||
@@ -93,6 +93,9 @@ class EditorWindow(QMainWindow):
|
||||
self.backups_button = button(tr('备份'), self.show_backups)
|
||||
self.backups_button.setObjectName('quiet')
|
||||
h.addWidget(self.backups_button)
|
||||
self.map_collection_button = button(tr('地图收集'), self.scan_map_collection)
|
||||
self.map_collection_button.setToolTip(tr('扫描当前进度槽的地图收集'))
|
||||
h.addWidget(self.map_collection_button)
|
||||
self.more_button = QPushButton(tr('更多'))
|
||||
self.more_button.setObjectName('quiet')
|
||||
self.more_menu = QMenu(self)
|
||||
@@ -1079,6 +1082,7 @@ class EditorWindow(QMainWindow):
|
||||
self.changes_label.style().unpolish(self.changes_label)
|
||||
self.changes_label.style().polish(self.changes_label)
|
||||
self.apply_button.setEnabled(ready and bool(count))
|
||||
self.map_collection_button.setEnabled(ready and self.catalog is not None)
|
||||
self.undo_button.setEnabled(ready and bool(self.draft.history or self._typing))
|
||||
item = self.selected_item
|
||||
present = bool(item and item_key(item) in self.owned and item['category'] in UNIQUE | {'medicine'})
|
||||
@@ -1175,6 +1179,104 @@ class EditorWindow(QMainWindow):
|
||||
self.run_task(tr('正在导出背包副本…'), lambda: session.export(slot, operations, path),
|
||||
lambda result: self.status.setText(tr('副本已导出,当前源文件未写入。')))
|
||||
|
||||
def scan_map_collection(self):
|
||||
if self.busy or not self.draft or not self.catalog:
|
||||
return
|
||||
from .map_collection import scan_collection
|
||||
|
||||
def start():
|
||||
session, slot, catalog = self.session, self.slot_name(), self.catalog
|
||||
self.run_task(tr('正在扫描地图收集…'), lambda: scan_collection(session, slot, catalog),
|
||||
lambda report: self._show_map_collection(session, slot, catalog, report))
|
||||
|
||||
self._resolve_changes(start)
|
||||
|
||||
def _show_map_collection(self, session, slot, catalog, report):
|
||||
from .map_collection import apply_collection
|
||||
names = {'bells': tr('铃铛'), 'weapons': tr('武器及影之武装'), 'equipment': tr('饰品及药瓶'),
|
||||
'challenges': tr('挑战地点'), 'amber': tr('杀气琥珀碎片'), 'blackstone': tr('黑石碎片'),
|
||||
'flowers': tr('记忆之花')}
|
||||
definitions = catalog.metadata.get('region_definitions', [])
|
||||
maps = {region['id'].casefold(): (region.get('name_en') or region['name']) if language() == 'en-US' else region['name']
|
||||
for region in definitions}
|
||||
maps['houjie'] = tr('后街')
|
||||
scopes = report['scopes']
|
||||
order = {region['id'].casefold(): i for i, region in enumerate(definitions)}
|
||||
regions = sorted((key for key in scopes if key is not None), key=lambda key: (order.get(key, len(order)), key))
|
||||
dialog = QDialog(self)
|
||||
dialog.setWindowTitle(tr('地图收集'))
|
||||
dialog.resize(620, 530)
|
||||
layout = QVBoxLayout(dialog)
|
||||
layout.addWidget(label(tr('当前进度槽 {0}', slot), 'section'))
|
||||
selector = QComboBox()
|
||||
selector.setObjectName('collectionScope')
|
||||
selector.setAccessibleName(tr('收集范围'))
|
||||
selector.addItem(tr('全部地图'), None)
|
||||
for scope in regions:
|
||||
selector.addItem(maps.get(scope, scope), scope)
|
||||
selector.setCurrentIndex(max(0, selector.findData(report['current_region'])))
|
||||
layout.addWidget(selector)
|
||||
summary = label('', 'muted', True)
|
||||
layout.addWidget(summary)
|
||||
results = QPlainTextEdit()
|
||||
results.setReadOnly(True)
|
||||
results.setAccessibleName(tr('收集扫描结果'))
|
||||
layout.addWidget(results, 1)
|
||||
row = QHBoxLayout()
|
||||
row.addStretch()
|
||||
close = button(tr('关闭'), dialog.reject)
|
||||
close.setDefault(True)
|
||||
row.addWidget(close)
|
||||
fill = button(tr('补齐并保存'), dialog.accept, True)
|
||||
fill.setAutoDefault(False)
|
||||
row.addWidget(fill)
|
||||
layout.addLayout(row)
|
||||
|
||||
def details(heading, points):
|
||||
rows = []
|
||||
for bucket, map_id, ident in points:
|
||||
item = catalog.get(ident)
|
||||
name = localized_item(item)['name'] if item else ident
|
||||
rows.append(f'{names[bucket]} · {maps.get(map_id.casefold(), map_id)} · {name}')
|
||||
return heading + '\n' + '\n'.join(rows)
|
||||
|
||||
def update_scope():
|
||||
scope = selector.currentData()
|
||||
selected = scopes[scope]
|
||||
fixable, unresolved = selected['fixable'], selected['unresolved']
|
||||
if scope is None:
|
||||
counts = []
|
||||
for region in regions:
|
||||
totals = scopes[region]['totals'].values()
|
||||
current, total = map(sum, zip(*totals))
|
||||
counts.append(f'{maps.get(region, region)} {current}/{total}')
|
||||
else:
|
||||
counts = [f'{names[key]} {current}/{total}' for key, (current, total) in selected['totals'].items()]
|
||||
messages, blocks = [], ['\n'.join(counts)]
|
||||
if fixable:
|
||||
messages.append(tr('可补齐 {0} 项。碎片只补地图领取记录,背包数量保持原样。', len(fixable)))
|
||||
blocks.append(details(tr('可补齐的项目'), fixable))
|
||||
if unresolved:
|
||||
messages.append(tr('有 {0} 项需在游戏里处理,或当前存档暂不支持自动补齐。', len(unresolved)))
|
||||
blocks.append(details(tr('需另行处理的项目'), unresolved))
|
||||
summary.setText('\n'.join(messages) if messages else tr('所选地图收集已齐全。'))
|
||||
results.setPlainText('\n\n'.join(blocks))
|
||||
fill.setEnabled(bool(fixable))
|
||||
|
||||
selector.currentIndexChanged.connect(update_scope)
|
||||
update_scope()
|
||||
self.status.setText(tr('地图收集已扫描。'))
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
scope = selector.currentData()
|
||||
|
||||
def saved(result):
|
||||
self._new_draft(slot)
|
||||
self.status.setText(tr('已补齐 {0} 项地图收集,已自动备份。', result['operation_count']))
|
||||
|
||||
self.run_task(tr('正在补齐地图收集并保存…'),
|
||||
lambda: apply_collection(session, slot, catalog, scope, report['source_sha256']),
|
||||
saved, on_error=self._offer_save_reload)
|
||||
|
||||
def advanced_add(self):
|
||||
if not self.draft:
|
||||
return
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "pbz-editor"
|
||||
version = "0.3.1"
|
||||
version = "0.4.0"
|
||||
description = "Offline inventory and save editor for Phantom Blade Zero"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = ["PySide6>=6.8,<7", "cryptography>=43", "texture2ddecoder==1.0.6"]
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import json
|
||||
import zlib
|
||||
|
||||
import pytest
|
||||
|
||||
from pbz_editor import map_collection
|
||||
from pbz_editor.catalog import Catalog
|
||||
from pbz_editor.core import EditorError, PBZSContainer, SaveChangedError, SaveSession
|
||||
from pbz_editor.map_collection import CollectionRegion, Point, apply_collection, scan_collection
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def collection_case(tmp_path, monkeypatch):
|
||||
source = tmp_path / 'collection.sav'
|
||||
container = PBZSContainer(bytes(range(32)))
|
||||
data = {
|
||||
'PBZGameSystem': {'CycleCount': 1, 'CurrentLevelName': 'PBZ_HouJie_WP',
|
||||
'CompleteAddItemMobDomainNames': ['existing-domain']},
|
||||
'Inventory': {
|
||||
'AccessoryInfos': {'AC_ResistRanged': {'CurrentLevel': 1, 'AcquiredCycle': 0, 'Note': 'keep'}},
|
||||
'AccessoryIDs': ['AC_ResistRanged'],
|
||||
'InventoryInfos': {'Item_Piece_001': {'CurrentAmount': 7, 'MaxAmount': 39, 'AcquiredCycle': 1}},
|
||||
},
|
||||
'EventPipeline': {'ExecuteNodeGuid': {'completed-challenge': {'flag': 1}}},
|
||||
'LevelActorManager': {'bp_rubbish_c_already': {'Destroy': True}},
|
||||
'BellManager': {'ActivateBellIDs': [], 'ActivateCraneBellIDs': []},
|
||||
}
|
||||
raw = json.dumps(data).encode()[:-1] + b', "Unrelated": 0.10000000000000001}'
|
||||
entries = []
|
||||
for name, slot_data in [('__Advanced__', b'{"LastContinueSlot":"AutoSave0"}'), ('AutoSave0', raw), ('ManualSave1', raw)]:
|
||||
entries.append({'name': name, 'raw': slot_data, 'json': json.loads(slot_data), 'algorithm': 1,
|
||||
'flag': 1, 'block': container.seal(zlib.compress(slot_data))})
|
||||
source.write_bytes(container.encode(entries, {}))
|
||||
session = SaveSession(source, tmp_path / 'game', container, source.read_bytes(), tmp_path / 'private')
|
||||
catalog = Catalog([{'id': 'AC_ResistRanged', 'category': 'accessory', 'name': '避箭护符'},
|
||||
{'id': 'F_06003', 'category': 'goods', 'name': '其一:断指'}])
|
||||
points = (
|
||||
Point('PangZhen', 'AccessoryItemDatas', 'AC_ResistRanged'),
|
||||
Point('HouJie', 'AccessoryItemDatas', 'ac_resistranged'),
|
||||
Point('PangZhen', 'MemoryFlowerData', 'F_06003'),
|
||||
Point('HouJie', 'HeiShiItemData', 'Item_Piece_001', domain='missing-domain'),
|
||||
Point('PangZhen', 'HeiShiItemData', 'Item_Piece_001', actor='MapA-BP_Rubbish_C_Already'),
|
||||
Point('PangZhen', 'BellDatas', 'bell-to-activate'),
|
||||
Point('HouJie', 'RongShu', 'None', nodes=('completed-challenge',)),
|
||||
Point('XiMeng', 'LongZhu', 'None', nodes=('unfinished-challenge',)),
|
||||
)
|
||||
mountain_points = (Point('DuanHunYa', 'MemoryFlowerData', 'F_06003'),
|
||||
Point('DuanHunYa', 'HeiShiItemData', 'Item_Piece_001', actor='MapB-BP_Chest_C_New'))
|
||||
regions = {'pangzhen': CollectionRegion(('pangzhen', 'houjie', 'ximeng'), points),
|
||||
'duanhunshan': CollectionRegion(('duanhunshan', 'duanhunya'), mountain_points)}
|
||||
monkeypatch.setattr(map_collection, '_load_regions', lambda _: regions)
|
||||
monkeypatch.setattr('pbz_editor.core._game_processes', lambda _: [])
|
||||
return session, catalog
|
||||
|
||||
|
||||
def test_scans_and_fills_only_verified_collection_records(collection_case):
|
||||
session, catalog = collection_case
|
||||
slot = 'AutoSave0'
|
||||
before = session.source
|
||||
previous = session._entry(slot)['json']
|
||||
other_slot = session._entry('ManualSave1')['block']
|
||||
scan = scan_collection(session, slot, catalog)
|
||||
assert scan['current_region'] == 'pangzhen'
|
||||
report = scan['scopes']['pangzhen']
|
||||
assert {key: report['totals'][key] for key in ('equipment', 'blackstone', 'flowers', 'challenges')} == {
|
||||
'equipment': [0, 1], 'blackstone': [1, 2], 'flowers': [0, 1], 'challenges': [1, 2],
|
||||
}
|
||||
assert len(report['fixable']) == 3
|
||||
assert [point[0] for point in report['unresolved']] == ['bells', 'challenges']
|
||||
assert session.save_path.read_bytes() == before and not session.backup_dir.exists()
|
||||
|
||||
applied = apply_collection(session, slot, catalog, 'pangzhen', scan['source_sha256'])
|
||||
after = session._entry(slot)['json']
|
||||
assert applied['operation_count'] == 3 and applied['affected_slots'] == [slot]
|
||||
assert len(list(session.backup_dir.glob('*.sav'))) == 1
|
||||
assert next(session.backup_dir.glob('*.sav')).read_bytes() == before
|
||||
assert session._entry('ManualSave1')['block'] == other_slot
|
||||
assert b'0.10000000000000001' in session._entry(slot)['raw']
|
||||
assert after['Inventory']['AccessoryInfos']['AC_ResistRanged'] == {'CurrentLevel': 1, 'AcquiredCycle': 1, 'Note': 'keep'}
|
||||
assert after['Inventory']['InventoryInfos']['F_06003']['AcquiredCycle'] == 1
|
||||
assert after['Inventory']['InventoryInfos']['Item_Piece_001'] == previous['Inventory']['InventoryInfos']['Item_Piece_001']
|
||||
assert after['Inventory']['AccessoryIDs'] == previous['Inventory']['AccessoryIDs']
|
||||
assert after['PBZGameSystem']['CompleteAddItemMobDomainNames'] == ['existing-domain', 'missing-domain']
|
||||
assert after['EventPipeline'] == previous['EventPipeline'] and after['BellManager'] == previous['BellManager']
|
||||
assert after['LevelActorManager'] == previous['LevelActorManager']
|
||||
|
||||
rescanned = scan_collection(session, slot, catalog)
|
||||
final = rescanned['scopes']['pangzhen']
|
||||
assert not final['fixable'] and final['unresolved'] == report['unresolved']
|
||||
assert final['totals']['blackstone'] == [2, 2]
|
||||
assert rescanned['scopes']['duanhunshan']['totals']['blackstone'] == [0, 1]
|
||||
assert apply_collection(session, slot, catalog, 'pangzhen', rescanned['source_sha256'])['operation_count'] == 0
|
||||
assert len(list(session.backup_dir.glob('*.sav'))) == 1
|
||||
|
||||
|
||||
def test_batch_fills_all_regions_with_one_backup_and_no_double_grant(collection_case):
|
||||
session, catalog = collection_case
|
||||
slot = 'AutoSave0'
|
||||
scan = scan_collection(session, slot, catalog)
|
||||
assert len(scan['scopes'][None]['fixable']) == 5
|
||||
result = apply_collection(session, slot, catalog, None, scan['source_sha256'])
|
||||
assert result['operation_count'] == 5
|
||||
after = session._entry(slot)['json']
|
||||
assert after['Inventory']['InventoryInfos']['F_06003']['CurrentAmount'] == 1
|
||||
assert after['LevelActorManager']['MapB-BP_Chest_C_New'] == {'SwitchState': True}
|
||||
refreshed = scan_collection(session, slot, catalog)
|
||||
assert all(not report['fixable'] for report in refreshed['scopes'].values())
|
||||
assert len(list(session.backup_dir.glob('*.sav'))) == 1
|
||||
|
||||
|
||||
def test_map_groups_match_cross_area_points_and_excluded_rows():
|
||||
points = {name: [Point(name, 'BellDatas', name)] for name in
|
||||
('xigu', 'pangzhen', 'houjie', 'ximeng', 'duanhunya', 'test', 'legacy')}
|
||||
groups = {'XiGu': [], 'PangZhen': ['XiMeng', 'HouJie', 'PangZhen'], 'HouJie': [],
|
||||
'DuanHunShan': ['DuanHunShan', 'DuanHunYa'], 'Empty': [], 'Test': []}
|
||||
regions = map_collection._build_regions(points, groups, {'pangzhen': ['pangzhen', 'houjie']}, {'test', 'legacy'})
|
||||
assert set(regions) == {'xigu', 'pangzhen', 'duanhunshan'}
|
||||
assert set(regions['pangzhen'].map_ids) == {'pangzhen', 'houjie', 'ximeng'}
|
||||
assert regions['duanhunshan'].map_ids == ('duanhunshan', 'duanhunya')
|
||||
with pytest.raises(ValueError, match='Incomplete'):
|
||||
map_collection._build_regions(points, groups, {'pangzhen': ['pangzhen', 'houjie']}, {'test'})
|
||||
|
||||
|
||||
@pytest.mark.parametrize('conflict,error', [('running', EditorError), ('disk', SaveChangedError), ('session', SaveChangedError)])
|
||||
def test_map_fill_checks_game_and_both_source_snapshots(collection_case, monkeypatch, conflict, error):
|
||||
session, catalog = collection_case
|
||||
report = scan_collection(session, 'AutoSave0', catalog)
|
||||
if conflict == 'running':
|
||||
monkeypatch.setattr('pbz_editor.core._game_processes', lambda _: [123])
|
||||
elif conflict == 'disk':
|
||||
session.save_path.write_bytes(b'fresh game progress')
|
||||
else:
|
||||
report['source_sha256'] = '0' * 64
|
||||
before = session.save_path.read_bytes()
|
||||
with pytest.raises(error):
|
||||
apply_collection(session, 'AutoSave0', catalog, 'pangzhen', report['source_sha256'])
|
||||
assert session.save_path.read_bytes() == before
|
||||
assert not session.backup_dir.exists()
|
||||
@@ -395,6 +395,51 @@ def test_failed_reload_keeps_edits(opened, monkeypatch):
|
||||
assert opened.session is session and opened.pending[0]['quantity'] == 6
|
||||
assert session.save_path.read_bytes() == b'invalid replacement'
|
||||
|
||||
|
||||
def test_map_collection_button_scans_selected_slot_and_can_fill(opened, monkeypatch):
|
||||
from pbz_editor import map_collection
|
||||
|
||||
opened.slot_combo.setCurrentIndex(opened.slot_combo.findData('ManualSave1'))
|
||||
calls = []
|
||||
source_hash = opened.session.source_sha256
|
||||
|
||||
def scan(session, slot, catalog):
|
||||
calls.append(('scan', session, slot, catalog))
|
||||
pangzhen = {'totals': {'blackstone': [11, 12]},
|
||||
'fixable': [('blackstone', 'HouJie', 'drop-point')], 'unresolved': []}
|
||||
mountain = {'totals': {'blackstone': [1, 1]}, 'fixable': [], 'unresolved': []}
|
||||
return {'scopes': {None: pangzhen, 'pangzhen': pangzhen, 'duanhunshan': mountain},
|
||||
'source_sha256': source_hash, 'current_region': 'pangzhen'}
|
||||
|
||||
def fill(session, slot, catalog, scope, expected):
|
||||
calls.append(('fill', session, slot, catalog, scope, expected))
|
||||
return {'operation_count': 1}
|
||||
|
||||
exec_dialog = ui.QDialog.exec
|
||||
|
||||
def choose_fill(dialog):
|
||||
combo = dialog.findChild(ui.QComboBox, 'collectionScope')
|
||||
results = dialog.findChild(ui.QPlainTextEdit)
|
||||
button = next(b for b in dialog.findChildren(ui.QPushButton) if b.text() == '补齐并保存')
|
||||
assert combo.count() == 3 and combo.currentData() == 'pangzhen'
|
||||
assert '11/12' in results.toPlainText() and button.isEnabled()
|
||||
combo.setCurrentIndex(combo.findData('duanhunshan'))
|
||||
assert '1/1' in results.toPlainText() and not button.isEnabled()
|
||||
combo.setCurrentIndex(0)
|
||||
assert 'pangzhen 11/12' in results.toPlainText() and button.isEnabled()
|
||||
QTimer.singleShot(0, button.click)
|
||||
return exec_dialog(dialog)
|
||||
|
||||
monkeypatch.setattr(map_collection, 'scan_collection', scan)
|
||||
monkeypatch.setattr(map_collection, 'apply_collection', fill)
|
||||
monkeypatch.setattr(ui.QDialog, 'exec', choose_fill)
|
||||
assert opened.map_collection_button.isVisible() and opened.map_collection_button.isEnabled()
|
||||
QTest.mouseClick(opened.map_collection_button, Qt.MouseButton.LeftButton)
|
||||
wait(opened)
|
||||
assert calls == [('scan', opened.session, 'ManualSave1', opened.catalog),
|
||||
('fill', opened.session, 'ManualSave1', opened.catalog, None, source_hash)]
|
||||
assert '已补齐 1 项地图收集' in opened.status.text()
|
||||
|
||||
def test_new_medicine_replacement_is_visible_and_undoable(opened):
|
||||
choose(opened, 'Medicine_Recover')
|
||||
opened.add_selected()
|
||||
|
||||
Reference in new issue
Block a user