feat(all): improve downloads, mod loading and story battle recovery
Show localized download progress and improve resource transfer handling. Unify plugin builds, caching, installation and releases; include BrownDustX acceleration. Fix exhausted story combat parties and inn placement handling. Release client 0.2.4 with signed multilingual update metadata.
This commit is contained in:
1 parent
56125dd330
commit
2cd9b30263
56 files changed
+3291
-317
No files matched your search
@@ -1,5 +1,44 @@
|
||||
# 更新日志
|
||||
|
||||
## client 2.36.7+client.0.2.4 · 2026-10-19
|
||||
|
||||
> type: update
|
||||
|
||||
### en_us: Download progress and story battle recovery
|
||||
|
||||
- Show game and resource download progress during preparation.
|
||||
- Improve resource downloads and resume handling.
|
||||
- Add BrownDustX character mod loading acceleration.
|
||||
- Fix story battles getting stuck when the combat party is exhausted, including recovery and inn return.
|
||||
|
||||
### zh_cn: 下载进度与剧情战斗恢复
|
||||
|
||||
- 准备游戏时显示游戏和资源的下载进度。
|
||||
- 改进资源下载与断点续传处理。
|
||||
- 加入 BrownDustX 角色模组加载加速。
|
||||
- 修复战斗队伍全部虚脱时剧情入战卡住,补全恢复与返回旅馆流程。
|
||||
|
||||
### zh_tw: 下載進度與劇情戰鬥恢復
|
||||
|
||||
- 準備遊戲時顯示遊戲與資源下載進度。
|
||||
- 改善資源下載與續傳處理。
|
||||
- 加入 BrownDustX 角色模組載入加速。
|
||||
- 修復戰鬥隊伍全員虛脫時劇情入戰卡住,補全恢復與返回旅館流程。
|
||||
|
||||
### ja_jp: ダウンロード進捗とストーリー戦闘の復帰
|
||||
|
||||
- 準備中にゲームとリソースのダウンロード進捗を表示します。
|
||||
- リソースのダウンロードと再開処理を改善しました。
|
||||
- BrownDustX のキャラクターMOD読み込みを高速化します。
|
||||
- 戦闘パーティー全員が戦闘不能の場合にストーリー戦闘へ進めなくなる問題を修正し、回復と宿屋への帰還処理を補いました。
|
||||
|
||||
### ko_kr: 다운로드 진행 상황 및 스토리 전투 복구
|
||||
|
||||
- 준비 중 게임과 리소스 다운로드 진행 상황을 표시합니다.
|
||||
- 리소스 다운로드와 이어받기 처리를 개선했습니다.
|
||||
- BrownDustX 캐릭터 모드 로딩 가속을 추가했습니다.
|
||||
- 전투 파티 전원이 탈진한 경우 스토리 전투에서 멈추는 문제를 수정하고 회복 및 여관 복귀 흐름을 보완했습니다.
|
||||
|
||||
## client 2.36.7+client.0.2.3 · 2026-10-18
|
||||
|
||||
> type: update
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"key_id": "6ba6c06138973875",
|
||||
"signature": "lukndUZhkAn69wsHMgB8KbJtcebdRecn96/x0bWa+fVlEs6dn43XZ2xej6kVDLmjI/rJRo/G6IULpDDGU522AQ=="
|
||||
"signature": "4p3ZZI08ucrw9b0DAdY+Qyidniz3gTj3715SaLNafA4ZuqiZA0/EJd6W+Aa8WGWwC6ecINAheCxR8iu4aJV1Dw=="
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
{"fingerprint":{"client_version":"2.36.7+client.0.2.3","game":{"build_origins":["https://cdn.dev.bd2.pmang.cloud","https://dl.dev.bd2.pmang.cloud"],"bundle_version":"20261007175947","catalog_bytes":67338179,"catalog_hash":"0f90a94601be05737f86a4ec7a1c889f","catalog_sha256":"c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385","data_bytes":191790996,"data_sha256":"0f28881e08029a1a53f86d5b113ba80b70b6d904bec35175b54ecfe90c2b6715","game_bytes":413552979,"game_data_version":"20261012190548","game_path":"/Build/Windows/20261002/StandaloneWindows64.2.36.7.zip","game_sha256":"3ca28b7c94d65b2cb4e33784d843902758415a3a83870c5f6198f5cd90e3bff3","game_version":"2.36.7","platform":"StandaloneWindows64","resource_files":[{"path":"GameData/20261012190548/design.version","sha256":"129dfa96fc813b22a4778a2b64dbd0afef7ab61b63550d0674066a232c40c19f","size":67},{"path":"GameData/20261012190548/release/common-dbdata.bin","sha256":"0f28881e08029a1a53f86d5b113ba80b70b6d904bec35175b54ecfe90c2b6715","size":191790996},{"path":"GameData/20261012190548/release/common-dbdata.info","sha256":"c043d0bc41f19bd06018a0453ca3c07442fa572a00f5ca204ad5c5b29d52b95d","size":10},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/catalog_alpha.hash","sha256":"743c225766ddb255b707872703dfc7dbf87e2f25b0f2d67214808f55511718e1","size":32},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/catalog_alpha.json","sha256":"c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385","size":67338179},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatar-char-group0_assets_charavatar.bundle","sha256":"c723a309b7b61bc2189f539f6911c852b21783b5fcb0a7a167e2f1d073fc2b5f","size":101738625},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatar-char-group0_scenes_charavatar.bundle","sha256":"56676c7f48d3d7c90f8956b02bc3f15f3074af7e8ff0ef64e1f9b8289eb08d52","size":31379},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarfishingicon_1_assets_all.bundle","sha256":"3407127468d588ff84e5158d31f2b791fb144582fc914340d307e7b79b96be22","size":44897},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarfishingicon_l_1_assets_all.bundle","sha256":"78ebf960a6b4f3b83fe28de1597e36f9ba7db1142bc1c0acdc9c65cd974cbbb4","size":2932480},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avataricon_1_assets_all.bundle","sha256":"b11d1072756c56a879f8b18ffc0dcb2ab16405d94418fcd9bc1e3ffb4404e321","size":2839270},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifehousing_1_assets_all.bundle","sha256":"1c844bc153dabe18b153157e466d7f7f0fa12e40c3b3ef6fc00af31abcf354e0","size":42443},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifehousing_l_1_assets_all.bundle","sha256":"c12e4bae20aedf8889d7f916cca0b3d55167a4b787bd649e07f10d21db0c49bc","size":2334709},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifeicon_1_assets_all.bundle","sha256":"bf6b432dc821a6e864993f649fedc1d03244d1ee2c93310bd0ce55d99ab8b743","size":16286},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifeicon_l_1_assets_all.bundle","sha256":"528dec1ed0c867bb6dcd59b985dc3911280f5f560c0d4b000a1e979f46f6e335","size":824161},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bgmalbum_1_assets_all.bundle","sha256":"16d606338d9b9e53a8d99d063613a8830dc943cb4225047f23b060f11614a7fc","size":614361},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-animation_assets_all.bundle","sha256":"8fb500400acf16f22516a298afbef6435c42c30969c762d7eee92c1d936cf06c","size":26191},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-animator_assets_all.bundle","sha256":"098045676a9b7d2c58703745bd608b2f9856027dd461012d3bde66d2f8266a16","size":6987},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-mesh_assets_all.bundle","sha256":"32a77141ffce92a510deb79f6af3309624b274c6e66493832946169a20612075","size":1617979},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-meterial_assets_all.bundle","sha256":"5d252406b5f875ca3add9da3bbbde4f7161f0fdd61f9592b3df780ce8c0ed1e1","size":384695},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group10_assets_all_49ba98afca0c02be2fc3424f638f5847.bundle","sha256":"71724987a41def2769d3bbdf79f1fb02933a0eb557d7f34a87c1e612e355c605","size":524718},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group11_assets_all_43fe4fab9a2c7d550e8bd6cc4f3b05e4.bundle","sha256":"31689c4ca268c96fd04e35d45f0bde1261b2810f32e339761889d1bebaaecfb6","size":665927},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group12_assets_all_622cf72083a2211233519e4d3074b754.bundle","sha256":"e86c377fd87f65a6092545e559a6bdd483e932741c03fe42538e9b9bc7b5dcc0","size":526015},{"path"Line truncated
|
||||
{"fingerprint":{"client_version":"2.36.7+client.0.2.4","game":{"build_origins":["https://cdn.dev.bd2.pmang.cloud","https://dl.dev.bd2.pmang.cloud"],"bundle_version":"20261007175947","catalog_bytes":67338179,"catalog_hash":"0f90a94601be05737f86a4ec7a1c889f","catalog_sha256":"c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385","data_bytes":191790996,"data_sha256":"0f28881e08029a1a53f86d5b113ba80b70b6d904bec35175b54ecfe90c2b6715","game_bytes":413552979,"game_data_version":"20261012190548","game_path":"/Build/Windows/20261002/StandaloneWindows64.2.36.7.zip","game_sha256":"3ca28b7c94d65b2cb4e33784d843902758415a3a83870c5f6198f5cd90e3bff3","game_version":"2.36.7","platform":"StandaloneWindows64","resource_files":[{"path":"GameData/20261012190548/design.version","sha256":"129dfa96fc813b22a4778a2b64dbd0afef7ab61b63550d0674066a232c40c19f","size":67},{"path":"GameData/20261012190548/release/common-dbdata.bin","sha256":"0f28881e08029a1a53f86d5b113ba80b70b6d904bec35175b54ecfe90c2b6715","size":191790996},{"path":"GameData/20261012190548/release/common-dbdata.info","sha256":"c043d0bc41f19bd06018a0453ca3c07442fa572a00f5ca204ad5c5b29d52b95d","size":10},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/catalog_alpha.hash","sha256":"743c225766ddb255b707872703dfc7dbf87e2f25b0f2d67214808f55511718e1","size":32},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/catalog_alpha.json","sha256":"c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385","size":67338179},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatar-char-group0_assets_charavatar.bundle","sha256":"c723a309b7b61bc2189f539f6911c852b21783b5fcb0a7a167e2f1d073fc2b5f","size":101738625},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatar-char-group0_scenes_charavatar.bundle","sha256":"56676c7f48d3d7c90f8956b02bc3f15f3074af7e8ff0ef64e1f9b8289eb08d52","size":31379},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarfishingicon_1_assets_all.bundle","sha256":"3407127468d588ff84e5158d31f2b791fb144582fc914340d307e7b79b96be22","size":44897},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarfishingicon_l_1_assets_all.bundle","sha256":"78ebf960a6b4f3b83fe28de1597e36f9ba7db1142bc1c0acdc9c65cd974cbbb4","size":2932480},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avataricon_1_assets_all.bundle","sha256":"b11d1072756c56a879f8b18ffc0dcb2ab16405d94418fcd9bc1e3ffb4404e321","size":2839270},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifehousing_1_assets_all.bundle","sha256":"1c844bc153dabe18b153157e466d7f7f0fa12e40c3b3ef6fc00af31abcf354e0","size":42443},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifehousing_l_1_assets_all.bundle","sha256":"c12e4bae20aedf8889d7f916cca0b3d55167a4b787bd649e07f10d21db0c49bc","size":2334709},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifeicon_1_assets_all.bundle","sha256":"bf6b432dc821a6e864993f649fedc1d03244d1ee2c93310bd0ce55d99ab8b743","size":16286},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifeicon_l_1_assets_all.bundle","sha256":"528dec1ed0c867bb6dcd59b985dc3911280f5f560c0d4b000a1e979f46f6e335","size":824161},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bgmalbum_1_assets_all.bundle","sha256":"16d606338d9b9e53a8d99d063613a8830dc943cb4225047f23b060f11614a7fc","size":614361},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-animation_assets_all.bundle","sha256":"8fb500400acf16f22516a298afbef6435c42c30969c762d7eee92c1d936cf06c","size":26191},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-animator_assets_all.bundle","sha256":"098045676a9b7d2c58703745bd608b2f9856027dd461012d3bde66d2f8266a16","size":6987},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-mesh_assets_all.bundle","sha256":"32a77141ffce92a510deb79f6af3309624b274c6e66493832946169a20612075","size":1617979},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-meterial_assets_all.bundle","sha256":"5d252406b5f875ca3add9da3bbbde4f7161f0fdd61f9592b3df780ce8c0ed1e1","size":384695},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group10_assets_all_49ba98afca0c02be2fc3424f638f5847.bundle","sha256":"71724987a41def2769d3bbdf79f1fb02933a0eb557d7f34a87c1e612e355c605","size":524718},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group11_assets_all_43fe4fab9a2c7d550e8bd6cc4f3b05e4.bundle","sha256":"31689c4ca268c96fd04e35d45f0bde1261b2810f32e339761889d1bebaaecfb6","size":665927},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group12_assets_all_622cf72083a2211233519e4d3074b754.bundle","sha256":"e86c377fd87f65a6092545e559a6bdd483e932741c03fe42538e9b9bc7b5dcc0","size":526015},{"path"Line truncated
|
||||
+4
-3
@@ -28,14 +28,14 @@ func main() {
|
||||
}
|
||||
|
||||
func usage() {
|
||||
fmt.Println(`Usage:
|
||||
fmt.Printf(`Usage:
|
||||
bd2w build [-GameDir directory] [-SkipTests] [-SchedulesOnly]
|
||||
bd2w release changelog --component server|client [--bump patch] | publish [--no-announcement] [--component all|schedules]
|
||||
bd2w runClient [client options]
|
||||
bd2w runClient2 [--instance player2] [--game-dir directory]
|
||||
bd2w plugins [--game-dir directory]
|
||||
bd2w runServer [server options]
|
||||
bd2w check-csharp [GameSdk GameNames LocalIdentity LoginUI CashShop FChat CaptureEnvironment]
|
||||
bd2w check-csharp [%s]
|
||||
bd2w sdk pack [--game-dir directory] [--package-version version] [--output-directory directory]
|
||||
bd2w sdk verify [--game-dir directory] [--package-version version] [--package-directory directory]
|
||||
bd2w sdk update-names --game-mapping file [--game-dir directory] [--version-config file]
|
||||
@@ -49,7 +49,8 @@ func usage() {
|
||||
Windows: .\bd2w build
|
||||
Linux/macOS: ./bd2w build
|
||||
Build automatically selects the native platform and architecture.
|
||||
The wrappers cache the build tool and refresh it when its sources change.`)
|
||||
The wrappers cache the build tool and refresh it when its sources change.
|
||||
`, strings.Join(csharpProjects(), " "))
|
||||
}
|
||||
|
||||
func run(args []string) error {
|
||||
|
||||
+16
-1
@@ -6,11 +6,12 @@ import (
|
||||
"path/filepath"
|
||||
"slices"
|
||||
|
||||
"bd2server/internal/client/plugin"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
func (t task) checkCSharp(projects []string) error {
|
||||
allowed := []string{"GameSdk", "GameNames", "LocalIdentity", "LoginUI", "CashShop", "FChat", "CaptureEnvironment"}
|
||||
allowed := csharpProjects()
|
||||
if len(projects) == 0 {
|
||||
projects = allowed
|
||||
}
|
||||
@@ -26,6 +27,12 @@ func (t task) checkCSharp(projects []string) error {
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
build, format := "csharp:build:"+project, "csharp:style:"+project
|
||||
tasks = append(tasks,
|
||||
taskgraph.Task{Name: build, Run: func(context.Context) error {
|
||||
@@ -41,3 +48,11 @@ 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
|
||||
}
|
||||
@@ -80,10 +80,7 @@ func (t task) runClient2(args []string) error {
|
||||
if err := clientplugin.BuildDevelopment(ctx, t.root, game, os.Stdout); err != nil {
|
||||
return err
|
||||
}
|
||||
plugins := func(name string) string {
|
||||
return filepath.Join(t.root, "plugins", name, "bin", "Release", "netstandard2.1", "BD2"+name+".dll")
|
||||
}
|
||||
_, err := clientsetup.InstallPlugins(instance.GameDirectory, plugins("LocalIdentity"), plugins("LoginUI"), plugins("CashShop"), plugins("FChat"))
|
||||
_, err := clientsetup.InstallPlugins(instance.GameDirectory, clientplugin.Development(t.root))
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "instance:launcher", DependsOn: []string{"instance:plugins"}, Run: func(context.Context) error {
|
||||
|
||||
@@ -2,17 +2,14 @@ package main
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/util"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
clientplugin "bd2server/internal/client/plugin"
|
||||
clientupdate "bd2server/internal/client/update"
|
||||
releasepkg "bd2server/internal/common/release"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
@@ -155,22 +152,10 @@ func (r *release) stageAssets() error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var shared []byte
|
||||
for _, plugin := range []string{"LocalIdentity", "LoginUI", "CashShop", "FChat"} {
|
||||
out := filepath.Join(root, "plugins", plugin, "bin", "Release", "netstandard2.1")
|
||||
raw, err := os.ReadFile(filepath.Join(out, "BD2.GameNames.dll"))
|
||||
if err != nil {
|
||||
for _, artifact := range clientplugin.Development(root) {
|
||||
if err := copyFile(artifact.Source, filepath.Join(r.client, "plugins", artifact.Name)); err != nil {
|
||||
return err
|
||||
}
|
||||
if shared != nil && !bytes.Equal(shared, raw) {
|
||||
return errors.New("plugins were built with different BD2.GameNames libraries")
|
||||
}
|
||||
shared = raw
|
||||
for _, name := range []string{"BD2" + plugin + ".dll", "BD2.GameNames.dll"} {
|
||||
if err := copyFile(filepath.Join(out, name), filepath.Join(r.client, "plugins", name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := copyTree(filepath.Join(root, "go", "seed"), filepath.Join(r.server, "go", "seed")); err != nil {
|
||||
return err
|
||||
@@ -239,20 +224,20 @@ func (r *release) writePluginStore() error {
|
||||
return err
|
||||
}
|
||||
byID := versions.Plugins.ByID()
|
||||
store := clientupdate.Store{Version: versions.ClientVersion}
|
||||
for _, spec := range clientplugin.Shipped {
|
||||
sum, err := util.SHA256File(filepath.Join(r.client, "plugins", spec.FileName()))
|
||||
store := clientplugin.Store{Version: versions.ClientVersion}
|
||||
for _, artifact := range clientplugin.Development(r.task.root) {
|
||||
sum, err := util.SHA256File(filepath.Join(r.client, "plugins", artifact.Name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id := pluginIDs[spec.FileName()]
|
||||
store.Files = append(store.Files, clientupdate.StoredFile{ID: id, Name: spec.FileName(), Version: byID[id], SHA256: sum})
|
||||
id := artifact.ID
|
||||
store.Files = append(store.Files, clientplugin.StoredFile{ID: id, Name: artifact.Name, Version: byID[artifact.VersionKey], SHA256: sum})
|
||||
}
|
||||
raw, err := json.MarshalIndent(store, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(filepath.Join(r.client, "plugins", clientupdate.StoreFile), append(raw, '\n'), 0o644)
|
||||
return os.WriteFile(filepath.Join(r.client, "plugins", clientplugin.StoreFile), append(raw, '\n'), 0o644)
|
||||
}
|
||||
|
||||
func (r *release) archive() error {
|
||||
|
||||
@@ -26,11 +26,6 @@ import (
|
||||
// serverPlatforms are the packages published for self-updating servers.
|
||||
var serverPlatforms = [][2]string{{"linux", "amd64"}, {"linux", "arm64"}}
|
||||
|
||||
// pluginIDs maps shipped plugin files to their versions.json keys.
|
||||
var pluginIDs = map[string]string{
|
||||
"BD2LocalIdentity.dll": "local_identity", "BD2LoginUI.dll": "login_ui", "BD2CashShop.dll": "cash_shop", "BD2FChat.dll": "fchat", "BD2.GameNames.dll": "game_names",
|
||||
}
|
||||
|
||||
func (t task) release(args []string) error {
|
||||
if len(args) == 0 || isHelp(args[0]) {
|
||||
fmt.Println(`Usage:
|
||||
@@ -343,10 +338,12 @@ func (t task) releasePublish(args []string) error {
|
||||
}
|
||||
|
||||
plugins := &releasepkg.Component{Version: versions.ClientVersion, Date: date(clientEntry), Notes: clientEntry.Notes()}
|
||||
pluginVersions := versions.Plugins.ByID()
|
||||
for _, spec := range clientplugin.Shipped {
|
||||
id := pluginIDs[spec.FileName()]
|
||||
f, err := publish(filepath.Join(clientPackage, "plugins", spec.FileName()), spec.FileName(), "", id, pluginVersions[id])
|
||||
packagedPlugins, err := clientplugin.Packaged(clientPackage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, artifact := range packagedPlugins {
|
||||
f, err := publish(artifact.Source, artifact.Name, "", artifact.ID, artifact.Version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -126,12 +126,9 @@ func runClientDevelopmentCommand(args []string) (bool, error) {
|
||||
}},
|
||||
taskgraph.Task{Name: "client:options", DependsOn: []string{"client:plugins"}, Run: func(context.Context) error {
|
||||
options = clientRunOptions{
|
||||
versionConfigPath: filepath.Join(root, "versions.json"),
|
||||
logExecutablePath: filepath.Join(root, "data", "bd2client-dev"),
|
||||
localIdentityPlugin: filepath.Join(root, "plugins", "LocalIdentity", "bin", "Release", "netstandard2.1", "BD2LocalIdentity.dll"),
|
||||
loginUIPlugin: filepath.Join(root, "plugins", "LoginUI", "bin", "Release", "netstandard2.1", "BD2LoginUI.dll"),
|
||||
cashShopPlugin: filepath.Join(root, "plugins", "CashShop", "bin", "Release", "netstandard2.1", "BD2CashShop.dll"),
|
||||
fChatPlugin: filepath.Join(root, "plugins", "FChat", "bin", "Release", "netstandard2.1", "BD2FChat.dll"),
|
||||
versionConfigPath: filepath.Join(root, "versions.json"),
|
||||
logExecutablePath: filepath.Join(root, "data", "bd2client-dev"),
|
||||
plugins: clientplugin.Development(root),
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
@@ -189,9 +186,7 @@ func findClientDevelopmentRoot() (string, error) {
|
||||
}
|
||||
for directory := filepath.Clean(working); ; directory = filepath.Dir(directory) {
|
||||
if clientDevelopmentFile(filepath.Join(directory, "versions.json")) &&
|
||||
clientDevelopmentFile(filepath.Join(directory, "go", "go.mod")) &&
|
||||
clientDevelopmentFile(filepath.Join(directory, "plugins", "LocalIdentity", "LocalIdentity.csproj")) &&
|
||||
clientDevelopmentFile(filepath.Join(directory, "plugins", "LoginUI", "LoginUI.csproj")) {
|
||||
clientDevelopmentFile(filepath.Join(directory, "go", "go.mod")) {
|
||||
return directory, nil
|
||||
}
|
||||
parent := filepath.Dir(directory)
|
||||
@@ -234,6 +229,6 @@ func buildDevelopmentPlugins(ctx context.Context, root, gameDir string) error {
|
||||
if !clientDevelopmentFile(filepath.Join(installation.BepInEx, "core", "BepInEx.dll")) {
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, "bd2client: preparing four development plugins; cached inputs will be reused")
|
||||
fmt.Fprintln(os.Stderr, "bd2client: preparing development plugins; cached inputs will be reused")
|
||||
return clientplugin.BuildDevelopment(ctx, root, gameDir, os.Stderr)
|
||||
}
|
||||
+12
-17
@@ -12,17 +12,15 @@ import (
|
||||
clientapp "bd2server/internal/client/app"
|
||||
clientconfig "bd2server/internal/client/config"
|
||||
"bd2server/internal/client/download"
|
||||
clientplugin "bd2server/internal/client/plugin"
|
||||
clientupdate "bd2server/internal/client/update"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
|
||||
type clientRunOptions struct {
|
||||
versionConfigPath string
|
||||
logExecutablePath string
|
||||
localIdentityPlugin string
|
||||
loginUIPlugin string
|
||||
cashShopPlugin string
|
||||
fChatPlugin string
|
||||
versionConfigPath string
|
||||
logExecutablePath string
|
||||
plugins clientplugin.Set
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -117,17 +115,14 @@ func runClient(args []string, options clientRunOptions) error {
|
||||
downloadManifest = filepath.Join(packageDirectory, "tools", "client", "client-download.json")
|
||||
}
|
||||
if err := clientapp.Run(clientapp.Options{
|
||||
InitialGameDir: *gameDir,
|
||||
Logger: logger,
|
||||
LogPath: logPath,
|
||||
Versions: versions,
|
||||
Development: options.versionConfigPath != "",
|
||||
PackageDirectory: packageDirectory,
|
||||
DownloadManifest: downloadManifest,
|
||||
LocalIdentityPlugin: options.localIdentityPlugin,
|
||||
LoginUIPlugin: options.loginUIPlugin,
|
||||
CashShopPlugin: options.cashShopPlugin,
|
||||
FChatPlugin: options.fChatPlugin,
|
||||
InitialGameDir: *gameDir,
|
||||
Logger: logger,
|
||||
LogPath: logPath,
|
||||
Versions: versions,
|
||||
Development: options.versionConfigPath != "",
|
||||
PackageDirectory: packageDirectory,
|
||||
DownloadManifest: downloadManifest,
|
||||
Plugins: options.plugins,
|
||||
}); err != nil {
|
||||
logger.Error("bd2client stopped with an error", "error", err)
|
||||
return err
|
||||
|
||||
@@ -27,17 +27,14 @@ var webFS embed.FS
|
||||
var errGameAlreadyRunning = errors.New("Brown Dust II is already running") //nolint:staticcheck // ST1005
|
||||
|
||||
type Options struct {
|
||||
InitialGameDir string
|
||||
Logger *slog.Logger
|
||||
LogPath string
|
||||
Versions versionconfig.Config
|
||||
Development bool
|
||||
PackageDirectory string
|
||||
DownloadManifest string
|
||||
LocalIdentityPlugin string
|
||||
LoginUIPlugin string
|
||||
CashShopPlugin string
|
||||
FChatPlugin string
|
||||
InitialGameDir string
|
||||
Logger *slog.Logger
|
||||
LogPath string
|
||||
Versions versionconfig.Config
|
||||
Development bool
|
||||
PackageDirectory string
|
||||
DownloadManifest string
|
||||
Plugins clientplugin.Set
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
@@ -94,13 +91,10 @@ type Studio struct {
|
||||
func NewStudio(options Options, host NativeHost) *Studio {
|
||||
s := &Studio{options: options, host: host, ctx: context.Background(), launch: launchGame, savePreferences: clientconfig.SavePreferences}
|
||||
if executable, err := os.Executable(); err == nil {
|
||||
var developmentPlugins []string
|
||||
if options.Development {
|
||||
developmentPlugins = []string{options.LocalIdentityPlugin, options.LoginUIPlugin, options.CashShopPlugin, options.FChatPlugin, filepath.Join(filepath.Dir(options.LocalIdentityPlugin), clientplugin.GameNames.FileName())}
|
||||
}
|
||||
|
||||
s.updates = clientupdate.New(clientupdate.Options{
|
||||
Versions: options.Versions, Directory: filepath.Dir(executable), Logger: options.Logger, Development: options.Development,
|
||||
DevelopmentPlugins: developmentPlugins,
|
||||
DevelopmentPlugins: options.Plugins,
|
||||
Games: func() string {
|
||||
preferences, err := clientconfig.LoadPreferences()
|
||||
if err != nil {
|
||||
@@ -300,7 +294,11 @@ func (s *Studio) Install(input Request) (Response, error) {
|
||||
if _, err := clientsetup.SaveSettings(input.GameDirectory, input.settings()); err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
result, err := clientsetup.InstallPlugins(input.GameDirectory, s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin, s.options.FChatPlugin)
|
||||
plugins, err := s.plugins()
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
result, err := clientsetup.InstallPlugins(input.GameDirectory, plugins)
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
@@ -364,7 +362,12 @@ func (s *Studio) Launch(input Request) (Response, error) {
|
||||
if !installation.SupportedOnHost() {
|
||||
return Response{}, fmt.Errorf("cannot launch a %s game client from this operating system", installation.Kind)
|
||||
}
|
||||
for _, name := range []string{"BD2LocalIdentity.dll", "BD2LoginUI.dll", "BD2CashShop.dll", "BD2FChat.dll"} {
|
||||
plugins, err := s.plugins()
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
for _, artifact := range plugins {
|
||||
name := artifact.Name
|
||||
info, err := os.Stat(filepath.Join(installation.Plugins, name))
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return Response{}, fmt.Errorf("install or update the client plugins before launching; %s is missing", name)
|
||||
@@ -459,3 +462,17 @@ func (s *Studio) Quit() {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Studio) plugins() (clientplugin.Set, error) {
|
||||
if s.options.Development {
|
||||
if _, err := s.options.Plugins.Sources(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.options.Plugins, nil
|
||||
}
|
||||
directory, err := s.packageDirectory()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return clientplugin.Packaged(directory)
|
||||
}
|
||||
@@ -8,7 +8,9 @@ import (
|
||||
"runtime"
|
||||
|
||||
clientconfig "bd2server/internal/client/config"
|
||||
"bd2server/internal/client/download"
|
||||
"bd2server/internal/client/preparation"
|
||||
clientupdate "bd2server/internal/client/update"
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
@@ -54,13 +56,16 @@ func (s *Studio) Prepare(input Request) (Response, error) {
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
if s.updates != nil {
|
||||
defer s.updates.EndDownload()
|
||||
}
|
||||
result, err := preparation.Run(s.context(), preparation.Options{
|
||||
PackageDirectory: directory, DownloadManifest: s.downloadManifest(directory),
|
||||
GameDirectory: input.GameDirectory, Settings: input.settings(), Versions: s.versions(input.GameDirectory),
|
||||
Workers: 8, DownloadIfMissing: true,
|
||||
LocalIdentityPlugin: s.options.LocalIdentityPlugin, LoginUIPlugin: s.options.LoginUIPlugin,
|
||||
CashShopPlugin: s.options.CashShopPlugin, FChatPlugin: s.options.FChatPlugin,
|
||||
Plugins: s.options.Plugins,
|
||||
SavePreferences: s.savePreferences,
|
||||
Progress: s.reportDownload(),
|
||||
PrepareGame: func(ctx context.Context, game string, settings clientconfig.Settings) (versionconfig.Config, error) {
|
||||
if s.updates != nil {
|
||||
if err := s.updates.PrepareGame(ctx, game, settings.ServerOrigin); err != nil {
|
||||
@@ -76,3 +81,18 @@ func (s *Studio) Prepare(input Request) (Response, error) {
|
||||
return success("Client prepared", result.Status), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Studio) reportDownload() func(download.Progress) {
|
||||
if s.updates == nil {
|
||||
return nil
|
||||
}
|
||||
return s.updates.ReportDownload(clientupdate.DownloadGame)
|
||||
}
|
||||
|
||||
// DownloadProgress reports the running download for the launcher's progress card.
|
||||
func (s *Studio) DownloadProgress() *clientupdate.Download {
|
||||
if s.updates == nil {
|
||||
return nil
|
||||
}
|
||||
return s.updates.DownloadProgress()
|
||||
}
|
||||
@@ -31,7 +31,7 @@ html,body{scrollbar-width:none}html::-webkit-scrollbar,body::-webkit-scrollbar{d
|
||||
@media(max-width:1050px){.topbar{padding-right:164px}}@media(max-width:760px){.topbar{padding-right:152px}.brand-name{font-size:11px;letter-spacing:.12em}.brand-name small{font-size:8px}.window-control{width:40px}}
|
||||
.lang-select{--wails-draggable:no-drag;flex-shrink:0;border:1px solid var(--line);border-radius:3px;background:#fffcf533;color:var(--muted);font:11px var(--sans);padding:5px 8px;cursor:pointer}.lang-select:hover:not(:disabled){color:var(--rust);border-color:#96543766}.lang-select:focus-visible{outline:2px solid var(--rust);outline-offset:3px}
|
||||
html:lang(ja){--sans:'Segoe UI','Yu Gothic UI',Meiryo,sans-serif;--serif:Georgia,'Yu Mincho','Noto Serif CJK JP',serif}html:lang(ko){--sans:'Segoe UI','Malgun Gothic','Apple SD Gothic Neo',sans-serif;--serif:Georgia,Batang,'Noto Serif CJK KR',serif}html:lang(zh-TW){--sans:'Segoe UI','Microsoft JhengHei','PingFang TC',sans-serif;--serif:Georgia,'Noto Serif CJK TC',PMingLiU,serif}
|
||||
</style>
|
||||
.download-card{position:fixed;inset:0;z-index:50;display:grid;place-items:center;background:#40322255;backdrop-filter:blur(6px)}.download-card[hidden]{display:none}.download-panel{width:min(440px,calc(100% - 40px));padding:26px 28px;border:1px solid #fff9;border-radius:5px;background:#f0e7d7;color:var(--ink);box-shadow:0 30px 140px #37271955;display:grid;gap:10px}.download-panel h2{margin:0;font-family:var(--serif);font-size:20px;font-weight:500}.download-row{display:flex;justify-content:space-between;gap:12px;font-size:13px;color:var(--muted)}.download-bar{height:8px;border-radius:4px;background:#d9cbb4;overflow:hidden}.download-bar i{display:block;height:100%;width:0;background:var(--rust);transition:width .3s var(--ease)}.download-bar.indeterminate i{width:35%;animation:download-slide 1.2s ease-in-out infinite}@keyframes download-slide{from{transform:translateX(-100%)}to{transform:translateX(290%)}}</style>
|
||||
</head>
|
||||
<body data-scene="directory">
|
||||
<div class="landscape" aria-hidden="true">
|
||||
@@ -65,6 +65,7 @@ html:lang(ja){--sans:'Segoe UI','Yu Gothic UI',Meiryo,sans-serif;--serif:Georgia
|
||||
</main>
|
||||
<footer class="bottom-bar" id="journey"><ol class="steps" data-i18n-attr="aria-label:launcher.steps.label"><li data-step="directory" class="active" aria-current="step"><span class="num">01</span><span data-i18n="launcher.steps.directory"></span></li><li data-step="server"><span class="num">02</span><span data-i18n="launcher.steps.server"></span></li><li data-step="desk"><span class="num">03</span><span data-i18n="launcher.title"></span></li></ol><span class="bottom-note">BROWN DUST II · GAME LAUNCHER</span></footer>
|
||||
<div id="proxyHome" hidden><div id="proxyFields"><label class="field-label" for="proxyMode" data-i18n="launcher.proxy.mode"></label><select id="proxyMode" class="proxy-select"><option value="direct" data-i18n="launcher.proxy.direct"></option><option value="manual" data-i18n="launcher.proxy.manual"></option></select><div id="proxyAddressField" hidden style="margin-top:18px"><label class="field-label" for="proxyURL" data-i18n="launcher.proxy.address"></label><input id="proxyURL" type="text" placeholder="http://127.0.0.1:7890" autocomplete="off" spellcheck="false"><p class="small-note" data-i18n="launcher.proxy.address_hint"></p></div><p class="small-note" data-i18n="launcher.proxy.apply_hint"></p><p class="small-note" data-i18n="launcher.proxy.https_hint"></p><p id="proxyResult" class="inline-result" role="status"></p></div></div>
|
||||
<div class="download-card" id="downloadCard" role="dialog" aria-modal="true" aria-labelledby="downloadTitle" hidden><div class="download-panel"><h2 id="downloadTitle"></h2><div class="download-row"><span id="downloadPhase"></span><span id="downloadPercent"></span></div><div class="download-bar" id="downloadTrack"><i id="downloadBar"></i></div><div class="download-row"><span id="downloadDetail"></span></div></div></div>
|
||||
<dialog id="editor" aria-labelledby="editorTitle"><div class="dialog-head"><h2 id="editorTitle" data-i18n="launcher.editor.title"></h2><button class="dialog-close" id="closeEditor" data-i18n-attr="aria-label:launcher.editor.close">×</button></div><div id="editorContent"></div><p class="small-note" data-i18n="launcher.editor.note"></p><div class="dialog-actions"><button class="btn primary" id="doneEditor" data-i18n="launcher.editor.done"></button></div></dialog>
|
||||
<div class="toast" id="toast" role="status" aria-live="polite"></div>
|
||||
<noscript><p style="padding:20px">Enable JavaScript to use the BD2 Launcher. / 请启用 JavaScript 以使用 BD2 启动器。</p></noscript>
|
||||
@@ -199,8 +200,10 @@ async function renderUpdates(u) {
|
||||
}
|
||||
async function updateAction(){const act=$('updateAction').dataset.act;const method=act==='apply'?'ApplyLauncherUpdate':'CheckUpdates';let data;try{data=await bridge()[method]()}catch(error){throw new Problem(problemText(error))}await show(backendText(data&&data.message))}
|
||||
$('updateAction').onclick=async ()=>await action('updateAction',updateAction);
|
||||
async function renderDownload(d){const card=$('downloadCard');if(!d){card.hidden=true;return}card.hidden=false;const known=d.total>0,pct=known?Math.min(100,Math.floor(d.done*100/d.total)):0;$('downloadTrack').classList.toggle('indeterminate',!known||d.phase==='extracting');$('downloadBar').style.width=known?pct+'%':'';$('downloadTitle').textContent=t('download.title.'+(d.kind||'game'));$('downloadPhase').textContent=t('download.phase.'+(d.phase||'preparing'));$('downloadPercent').textContent=known?pct+'%':'';const parts=[];if(known)parts.push(formatBytes(d.done)+' / '+formatBytes(d.total));if(d.files>0)parts.push(await dynamicText('download.files',d.files_done,d.files).getString());$('downloadDetail').textContent=parts.join(' · ')}
|
||||
async function pollDownload(){try{await renderDownload(await bridge().DownloadProgress())}catch(error){console.error(error)}}
|
||||
async function pollUpdates(){try{await renderUpdates(await bridge().UpdateStatus())}catch(error){await show(Component.literal(error.message||String(error)),true)}}
|
||||
async function start(){await loadTranslations();await setLocale(detectLocale(),false);setInterval(pollUpdates,4000);setTimeout(pollUpdates,1500);await initialize()}
|
||||
async function start(){await loadTranslations();await setLocale(detectLocale(),false);setInterval(pollUpdates,4000);setInterval(pollDownload,400);setTimeout(pollUpdates,1500);await initialize()}
|
||||
window.addEventListener('unhandledrejection',event=>{console.error(event.reason);const box=$('toast');box.textContent=String(event.reason&&event.reason.message||event.reason);box.className='toast show error';clearTimeout(toastTimer);toastTimer=setTimeout(()=>box.className='toast',5200)});
|
||||
await start();
|
||||
})();
|
||||
|
||||
@@ -176,6 +176,15 @@
|
||||
"update.plugins.applied_after_exit": "The game exited; the plugin update has been applied",
|
||||
"update.checking": "Checking for updates",
|
||||
"update.preparing": "Preparing to start the game",
|
||||
"download.title.game": "Downloading the game",
|
||||
"download.title.update": "Downloading the update",
|
||||
"download.phase.preparing": "Preparing download",
|
||||
"download.phase.game": "Downloading the game package",
|
||||
"download.phase.extracting": "Extracting the game",
|
||||
"download.phase.resources": "Downloading game resources",
|
||||
"download.phase.launcher": "Downloading the launcher update",
|
||||
"download.phase.plugins": "Downloading the plugin update",
|
||||
"download.files": "%[1]s / %[2]s files",
|
||||
"backend.server_maintenance": "The server is updating; try again after it finishes",
|
||||
"backend.game_mismatch": "Server game version %[1]s does not match client game version %[2]s",
|
||||
"launcher.brand.title": "BD2 LAUNCHER",
|
||||
|
||||
@@ -176,6 +176,15 @@
|
||||
"update.plugins.applied_after_exit": "ゲームが終了したため、プラグインの更新を適用しました",
|
||||
"update.checking": "更新を確認中",
|
||||
"update.preparing": "ゲームの起動を準備中",
|
||||
"download.title.game": "ゲームをダウンロード中",
|
||||
"download.title.update": "更新をダウンロード中",
|
||||
"download.phase.preparing": "ダウンロードを準備中",
|
||||
"download.phase.game": "ゲーム本体をダウンロード中",
|
||||
"download.phase.extracting": "ゲームを展開中",
|
||||
"download.phase.resources": "ゲームリソースをダウンロード中",
|
||||
"download.phase.launcher": "ランチャーの更新をダウンロード中",
|
||||
"download.phase.plugins": "プラグインの更新をダウンロード中",
|
||||
"download.files": "%[1]s / %[2]s ファイル",
|
||||
"backend.server_maintenance": "サーバーを更新中です。完了後にもう一度お試しください",
|
||||
"backend.game_mismatch": "サーバーのゲームバージョン %[1]s とクライアントのゲームバージョン %[2]s が一致しません",
|
||||
"launcher.brand.title": "BD2 ランチャー",
|
||||
|
||||
@@ -176,6 +176,15 @@
|
||||
"update.plugins.applied_after_exit": "게임이 종료되어 플러그인 업데이트를 적용했습니다",
|
||||
"update.checking": "업데이트 확인 중",
|
||||
"update.preparing": "게임 시작 준비 중",
|
||||
"download.title.game": "게임 다운로드 중",
|
||||
"download.title.update": "업데이트 다운로드 중",
|
||||
"download.phase.preparing": "다운로드 준비 중",
|
||||
"download.phase.game": "게임 본체 다운로드 중",
|
||||
"download.phase.extracting": "게임 압축 해제 중",
|
||||
"download.phase.resources": "게임 리소스 다운로드 중",
|
||||
"download.phase.launcher": "런처 업데이트 다운로드 중",
|
||||
"download.phase.plugins": "플러그인 업데이트 다운로드 중",
|
||||
"download.files": "%[1]s / %[2]s 파일",
|
||||
"backend.server_maintenance": "서버 업데이트 중입니다. 완료 후 다시 시도해 주세요",
|
||||
"backend.game_mismatch": "서버 게임 버전 %[1]s과 클라이언트 게임 버전 %[2]s이 일치하지 않습니다",
|
||||
"launcher.brand.title": "BD2 런처",
|
||||
|
||||
@@ -176,6 +176,15 @@
|
||||
"update.plugins.applied_after_exit": "游戏已退出,插件更新已生效",
|
||||
"update.checking": "正在检查更新",
|
||||
"update.preparing": "正在准备启动游戏",
|
||||
"download.title.game": "正在下载游戏",
|
||||
"download.title.update": "正在下载更新",
|
||||
"download.phase.preparing": "正在准备下载",
|
||||
"download.phase.game": "正在下载游戏本体",
|
||||
"download.phase.extracting": "正在解压游戏",
|
||||
"download.phase.resources": "正在下载游戏资源",
|
||||
"download.phase.launcher": "正在下载启动器更新",
|
||||
"download.phase.plugins": "正在下载插件更新",
|
||||
"download.files": "%[1]s / %[2]s 个文件",
|
||||
"backend.server_maintenance": "服务器正在更新,请稍后再试",
|
||||
"backend.game_mismatch": "服务器游戏版本 %[1]s 与客户端游戏版本 %[2]s 不一致",
|
||||
"launcher.brand.title": "BD2 启动器",
|
||||
|
||||
@@ -176,6 +176,15 @@
|
||||
"update.plugins.applied_after_exit": "遊戲已結束,插件更新已套用",
|
||||
"update.checking": "正在檢查更新",
|
||||
"update.preparing": "正在準備啟動遊戲",
|
||||
"download.title.game": "正在下載遊戲",
|
||||
"download.title.update": "正在下載更新",
|
||||
"download.phase.preparing": "正在準備下載",
|
||||
"download.phase.game": "正在下載遊戲本體",
|
||||
"download.phase.extracting": "正在解壓縮遊戲",
|
||||
"download.phase.resources": "正在下載遊戲資源",
|
||||
"download.phase.launcher": "正在下載啟動器更新",
|
||||
"download.phase.plugins": "正在下載插件更新",
|
||||
"download.files": "%[1]s / %[2]s 個檔案",
|
||||
"backend.server_maintenance": "伺服器正在更新,請稍後再試",
|
||||
"backend.game_mismatch": "伺服器遊戲版本 %[1]s 與用戶端遊戲版本 %[2]s 不一致",
|
||||
"launcher.brand.title": "BD2 啟動器",
|
||||
|
||||
@@ -19,6 +19,8 @@ type Options struct {
|
||||
Workers int
|
||||
ProbeOnly bool
|
||||
Pinned *release.GameResources
|
||||
// Progress, when set, receives byte and file counts while downloading.
|
||||
Progress func(Progress)
|
||||
}
|
||||
|
||||
type Installation struct {
|
||||
@@ -89,6 +91,7 @@ func Client(ctx context.Context, options Options, out io.Writer) (Installation,
|
||||
return result, err
|
||||
}
|
||||
defer d.client.CloseIdleConnections()
|
||||
d.progress = options.Progress
|
||||
dataPath := "/GameData/" + m.GameDataVersion
|
||||
serverPath := "/ServerData/" + m.Platform + "/HD/" + m.BundleVersion
|
||||
if options.ProbeOnly {
|
||||
@@ -112,12 +115,15 @@ func Client(ctx context.Context, options Options, out io.Writer) (Installation,
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
d.setPhase(PhaseGame)
|
||||
if err := d.receiveAll(ctx, []file{gameFile}, builds, 1); err != nil {
|
||||
return result, err
|
||||
}
|
||||
d.setPhase(PhaseExtracting)
|
||||
if err := extractArchive(archive, result.GameDir, true, m.GameSHA256); err != nil {
|
||||
return result, err
|
||||
}
|
||||
d.setPhase(PhaseResources)
|
||||
if err := d.resources(ctx, result.ResourceDir, m, serverPath, dataPath, m.ResourceOrigins, m.ResourceOrigins, options.Workers); err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
@@ -41,6 +41,11 @@ type downloader struct {
|
||||
records map[string]receipt
|
||||
dirty bool
|
||||
measureOrigins bool
|
||||
|
||||
progress func(Progress)
|
||||
progressMu sync.Mutex
|
||||
state Progress
|
||||
reported time.Time
|
||||
}
|
||||
|
||||
func newDownloader(root string, out io.Writer) (*downloader, error) {
|
||||
@@ -136,6 +141,7 @@ func (d *downloader) saveRecords() error {
|
||||
|
||||
func (d *downloader) receive(ctx context.Context, item file, origins []string) error {
|
||||
if d.verified(item) {
|
||||
d.addDone(max(item.size, 0))
|
||||
return nil
|
||||
}
|
||||
if len(origins) == 0 {
|
||||
@@ -155,7 +161,7 @@ func (d *downloader) receive(ctx context.Context, item file, origins []string) e
|
||||
return fmt.Errorf("download %s: %w", item.remote, last)
|
||||
}
|
||||
|
||||
func (d *downloader) receiveOnce(ctx context.Context, item file, origin string) error {
|
||||
func (d *downloader) receiveOnce(ctx context.Context, item file, origin string) (err error) {
|
||||
if err := os.MkdirAll(filepath.Dir(item.target), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -178,7 +184,21 @@ func (d *downloader) receiveOnce(ctx context.Context, item file, origin string)
|
||||
}
|
||||
defer func() { _ = temporary.Close(); _ = os.Remove(temporary.Name()) }()
|
||||
h := sha256.New()
|
||||
written, err := io.Copy(io.MultiWriter(temporary, h), response.Body)
|
||||
counted := &countingWriter{d: d}
|
||||
if item.size <= 0 && response.ContentLength > 0 {
|
||||
d.addTotal(response.ContentLength)
|
||||
defer func() {
|
||||
if err != nil {
|
||||
d.addTotal(-response.ContentLength)
|
||||
}
|
||||
}()
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
d.addDone(-counted.n)
|
||||
}
|
||||
}()
|
||||
written, err := io.Copy(io.MultiWriter(temporary, h, counted), response.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -225,6 +245,7 @@ func (d *downloader) receiveAll(ctx context.Context, files []file, origins []str
|
||||
var errOnce sync.Once
|
||||
completed := 0
|
||||
var progress sync.Mutex
|
||||
d.addFiles(files)
|
||||
for range min(workers, len(files)) {
|
||||
wg.Go(func() {
|
||||
for item := range jobs {
|
||||
@@ -232,6 +253,7 @@ func (d *downloader) receiveAll(ctx context.Context, files []file, origins []str
|
||||
errOnce.Do(func() { first = err; cancel() })
|
||||
return
|
||||
}
|
||||
d.fileDone()
|
||||
progress.Lock()
|
||||
completed++
|
||||
if completed%25 == 0 || completed == len(files) {
|
||||
@@ -345,3 +367,66 @@ func atomicWrite(path string, data []byte) error {
|
||||
}
|
||||
return os.Rename(tmp.Name(), path)
|
||||
}
|
||||
|
||||
// Download phases reported through Progress.
|
||||
const (
|
||||
PhaseGame = "game"
|
||||
PhaseExtracting = "extracting"
|
||||
PhaseResources = "resources"
|
||||
)
|
||||
|
||||
// Progress is a running download: bytes and files grow as the downloader
|
||||
// learns which files are missing.
|
||||
type Progress struct {
|
||||
Phase string `json:"phase"`
|
||||
Done int64 `json:"done"`
|
||||
Total int64 `json:"total"`
|
||||
Files int `json:"files"`
|
||||
FilesDone int `json:"files_done"`
|
||||
}
|
||||
|
||||
type countingWriter struct {
|
||||
d *downloader
|
||||
n int64
|
||||
}
|
||||
|
||||
func (w *countingWriter) Write(p []byte) (int, error) {
|
||||
w.n += int64(len(p))
|
||||
w.d.addDone(int64(len(p)))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (d *downloader) update(force bool, change func(*Progress)) {
|
||||
if d.progress == nil {
|
||||
return
|
||||
}
|
||||
d.progressMu.Lock()
|
||||
defer d.progressMu.Unlock()
|
||||
change(&d.state)
|
||||
if !force && time.Since(d.reported) < 200*time.Millisecond {
|
||||
return
|
||||
}
|
||||
d.reported = time.Now()
|
||||
d.progress(d.state)
|
||||
}
|
||||
|
||||
func (d *downloader) setPhase(phase string) {
|
||||
d.update(true, func(p *Progress) { p.Phase = phase })
|
||||
}
|
||||
|
||||
func (d *downloader) addDone(n int64) { d.update(false, func(p *Progress) { p.Done += n }) }
|
||||
|
||||
func (d *downloader) addTotal(n int64) { d.update(false, func(p *Progress) { p.Total += n }) }
|
||||
|
||||
func (d *downloader) addFiles(files []file) {
|
||||
d.update(true, func(p *Progress) {
|
||||
for _, item := range files {
|
||||
if item.size > 0 {
|
||||
p.Total += item.size
|
||||
}
|
||||
}
|
||||
p.Files += len(files)
|
||||
})
|
||||
}
|
||||
|
||||
func (d *downloader) fileDone() { d.update(true, func(p *Progress) { p.FilesDone++ }) }
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -19,13 +20,12 @@ import (
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
var developmentProjects = []struct{ name, key string }{
|
||||
{"LocalIdentity", "local_identity"}, {"LoginUI", "login_ui"}, {"CashShop", "cash_shop"}, {"FChat", "fchat"},
|
||||
}
|
||||
|
||||
// BuildDevelopment compiles the client plugins as one dependency graph, sharing
|
||||
// the game SDK and version preparation across the four entry projects.
|
||||
// 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
|
||||
}
|
||||
@@ -133,15 +133,18 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
|
||||
taskgraph.Task{Name: "versionSources", DependsOn: []string{"sdkPrepare"}, Run: func(context.Context) error {
|
||||
versionStarted := time.Now()
|
||||
_, _ = fmt.Fprintln(progress, "Client plugins: generating version and compilation fingerprints...")
|
||||
for _, project := range developmentProjects {
|
||||
if err := buildversion.Generate(versionConfig, filepath.Join(versionDir, project.key+".g.cs"), project.key); err != nil {
|
||||
for _, project := range definitions {
|
||||
if project.VersionKey == "" {
|
||||
continue
|
||||
}
|
||||
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.key+".g.cs"))
|
||||
inputStamp, err := projectFingerprint(root, inputs, project.Name(), filepath.Join(versionDir, project.VersionKey+".g.cs"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeBuildInput(filepath.Join(compileInputsDir, project.key+".g.cs"), inputStamp); err != nil {
|
||||
if err := writeBuildInput(filepath.Join(compileInputsDir, project.VersionKey+".g.cs"), inputStamp); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -151,11 +154,14 @@ 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()
|
||||
_, _ = fmt.Fprintln(progress, "Client plugins: compiling all four plugins as one parallel dependency graph...")
|
||||
if err := runPluginBuild(ctx, root, progress, "build", filepath.Join(root, "plugins", "ClientPlugins.proj"), "-m", "-c", "Release", "--nologo",
|
||||
if err := writeAggregateProject(filepath.Join(work, "ClientPlugins.proj"), root); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: compiling all %d plugins as one parallel dependency graph...\n", len(definitions))
|
||||
if err := runPluginBuild(ctx, root, progress, "build", filepath.Join(work, "ClientPlugins.proj"), "-m", "-c", "Release", "--nologo",
|
||||
"-p:GameDir="+installation.Root, "-p:BD2ManagedDir="+managed, "-p:BD2BepInExDir="+installation.BepInEx,
|
||||
"-p:BD2SdkPrepared=true", "-p:BD2SdkDir="+sdkDir, "-p:BD2SharedSdkDir="+shared,
|
||||
"-p:BD2SdkTool="+sdkTool,
|
||||
"-p:BD2PluginRegistryProps="+filepath.Join(work, "ClientPlugins.props"), "-p:BD2SdkTool="+sdkTool, "-p:GameNamesTable="+filepath.Join(shared, "names.json"),
|
||||
"-p:BD2PreparedVersionDir="+versionDir, "-p:BD2CompileInputsDir="+compileInputsDir, "-p:BD2NamesCompileInputsFile="+namesInputs, "-v:quiet", "-clp:NoSummary"); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -178,9 +184,14 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
|
||||
outputs = append(outputs, toolDependencies...)
|
||||
sdkOutputs := append([]string(nil), outputs...)
|
||||
outputs = append(outputs, namesInputs)
|
||||
for _, project := range developmentProjects {
|
||||
output := filepath.Join(root, "plugins", project.name, "bin", "Release", "netstandard2.1")
|
||||
outputs = append(outputs, filepath.Join(output, "BD2"+project.name+".dll"), filepath.Join(output, GameNames.fileName), filepath.Join(versionDir, project.key+".g.cs"), filepath.Join(compileInputsDir, project.key+".g.cs"))
|
||||
for _, project := range definitions {
|
||||
outputs = append(outputs, project.Output(root))
|
||||
if project.VersionKey != "" {
|
||||
outputs = append(outputs, filepath.Join(versionDir, project.VersionKey+".g.cs"), filepath.Join(compileInputsDir, project.VersionKey+".g.cs"))
|
||||
}
|
||||
}
|
||||
if err := verifyDependencyOutputs(root); err != nil {
|
||||
return err
|
||||
}
|
||||
sums := make(map[string]string, len(outputs))
|
||||
for _, output := range outputs {
|
||||
@@ -217,7 +228,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
|
||||
if err := graph.Run(ctx, "cacheCommit"); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: all four ready in %s\n", time.Since(started).Round(time.Millisecond))
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: all %d ready in %s\n", len(definitions), time.Since(started).Round(time.Millisecond))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -277,3 +288,42 @@ func runPluginBuild(ctx context.Context, root string, progress io.Writer, args .
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeAggregateProject(path, root string) error {
|
||||
var content, properties bytes.Buffer
|
||||
content.WriteString("<Project DefaultTargets=\"Build\"><ItemGroup>")
|
||||
properties.WriteString("<Project>")
|
||||
for _, definition := range definitions {
|
||||
content.WriteString("<ClientPlugin Include=\"")
|
||||
if err := xml.EscapeText(&content, []byte(definition.ProjectFile(root))); err != nil {
|
||||
return err
|
||||
}
|
||||
content.WriteString("\" />")
|
||||
properties.WriteString("<PropertyGroup Condition=\"'$(MSBuildProjectName)' == '")
|
||||
if err := xml.EscapeText(&properties, []byte(definition.Name())); err != nil {
|
||||
return err
|
||||
}
|
||||
properties.WriteString("'\"><BD2UsesGameSdk>")
|
||||
if definition.UsesGameSdk {
|
||||
properties.WriteString("true")
|
||||
} else {
|
||||
properties.WriteString("false")
|
||||
}
|
||||
properties.WriteString("</BD2UsesGameSdk><BD2PluginVersionKey>")
|
||||
if err := xml.EscapeText(&properties, []byte(definition.VersionKey)); err != nil {
|
||||
return err
|
||||
}
|
||||
properties.WriteString("</BD2PluginVersionKey></PropertyGroup>")
|
||||
}
|
||||
properties.WriteString("</Project>\n")
|
||||
content.WriteString("</ItemGroup><Target Name=\"Restore\"><MSBuild Projects=\"@(ClientPlugin)\" Targets=\"Restore\" BuildInParallel=\"true\" /></Target><Target Name=\"Build\"><MSBuild Projects=\"@(ClientPlugin)\" Targets=\"Build\" BuildInParallel=\"true\" /></Target></Project>\n")
|
||||
for filename, data := range map[string][]byte{path: content.Bytes(), filepath.Join(filepath.Dir(path), "ClientPlugins.props"): properties.Bytes()} {
|
||||
if previous, err := os.ReadFile(filename); err == nil && bytes.Equal(previous, data) {
|
||||
continue
|
||||
}
|
||||
if err := os.WriteFile(filename, data, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -85,36 +85,26 @@ func snapshotInputs(root, managed, bep string, cache fileDigestCache) (map[strin
|
||||
}
|
||||
|
||||
func projectFingerprint(root string, inputs map[string]string, project, versionSource string) (string, error) {
|
||||
relevant := make(map[string]string)
|
||||
for file, sum := range inputs {
|
||||
if strings.HasSuffix(file, ".go") || file == filepath.Join(root, "go", "go.mod") || file == filepath.Join(root, "go", "go.sum") {
|
||||
continue
|
||||
var definition Definition
|
||||
for _, candidate := range definitions {
|
||||
if candidate.Name() == project {
|
||||
definition = candidate
|
||||
break
|
||||
}
|
||||
relative, err := filepath.Rel(filepath.Join(root, "plugins"), file)
|
||||
folder, _, nested := strings.Cut(filepath.ToSlash(relative), "/")
|
||||
}
|
||||
relevant := selectDependencyInputs(root, inputs, definition)
|
||||
if versionSource != "" {
|
||||
sum, err := util.SHA256File(versionSource)
|
||||
if err != nil {
|
||||
nested = false
|
||||
return "", err
|
||||
}
|
||||
isPlugin := folder == "LocalIdentity" || folder == "LoginUI" || folder == "CashShop" || folder == "FChat"
|
||||
needsLoginUI := project == "CashShop" || project == "FChat"
|
||||
isDependency := folder == project || folder == "LoginUI" && needsLoginUI
|
||||
if nested && isPlugin && !isDependency {
|
||||
continue
|
||||
}
|
||||
if file == filepath.Join(root, "versions.json") {
|
||||
continue
|
||||
}
|
||||
relevant[file] = sum
|
||||
relevant[versionSource] = sum
|
||||
}
|
||||
sum, err := util.SHA256File(versionSource)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
relevant[versionSource] = sum
|
||||
return digestInputs(relevant), nil
|
||||
}
|
||||
|
||||
func dependencyFingerprint(root string, inputs map[string]string, project string) string {
|
||||
func selectDependencyInputs(root string, inputs map[string]string, definition Definition) map[string]string {
|
||||
projects := definition.dependencyProjects()
|
||||
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") {
|
||||
@@ -125,11 +115,48 @@ func dependencyFingerprint(root string, inputs map[string]string, project string
|
||||
continue
|
||||
}
|
||||
folder, _, nested := strings.Cut(filepath.ToSlash(relative), "/")
|
||||
if !nested || folder == ".." || folder == project || project == "GameSdk" && folder == "GameNames" {
|
||||
relevant[file] = sum
|
||||
if nested && folder != ".." {
|
||||
registered := false
|
||||
dependency := false
|
||||
for _, candidate := range definitions {
|
||||
if strings.HasPrefix(filepath.ToSlash(relative), filepath.ToSlash(filepath.Dir(candidate.ProjectPath))+"/") {
|
||||
registered = true
|
||||
dependency = projects[candidate.Name()]
|
||||
break
|
||||
}
|
||||
}
|
||||
if registered && !dependency {
|
||||
continue
|
||||
}
|
||||
if folder == "GameSdk" && folder != definition.Name() && !definition.UsesGameSdk {
|
||||
continue
|
||||
}
|
||||
if !registered && folder != "GameSdk" && folder != "Shared" {
|
||||
continue
|
||||
}
|
||||
}
|
||||
relevant[file] = sum
|
||||
}
|
||||
return relevant
|
||||
}
|
||||
|
||||
func dependencyFingerprint(root string, inputs map[string]string, project string) string {
|
||||
definition := Definition{ProjectPath: project + "/" + project + ".csproj"}
|
||||
for _, candidate := range definitions {
|
||||
if candidate.Name() == project {
|
||||
definition = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
return digestInputs(relevant)
|
||||
if project == "GameSdk" {
|
||||
for _, candidate := range definitions {
|
||||
if candidate.SharedRuntime {
|
||||
definition.Dependencies = append(definition.Dependencies, candidate.ID)
|
||||
}
|
||||
}
|
||||
definition.UsesGameSdk = true
|
||||
}
|
||||
return digestInputs(selectDependencyInputs(root, inputs, definition))
|
||||
}
|
||||
|
||||
func developmentInputs(root, managed, bep string) ([]string, error) {
|
||||
|
||||
@@ -24,27 +24,9 @@ const (
|
||||
managedFile = ".bd2-managed.json"
|
||||
)
|
||||
|
||||
type Spec struct {
|
||||
fileName string
|
||||
}
|
||||
|
||||
var (
|
||||
LocalIdentity = Spec{fileName: "BD2LocalIdentity.dll"}
|
||||
LoginUI = Spec{fileName: "BD2LoginUI.dll"}
|
||||
CashShop = Spec{fileName: "BD2CashShop.dll"}
|
||||
FChat = Spec{fileName: "BD2FChat.dll"}
|
||||
GameNames = Spec{fileName: "BD2.GameNames.dll"}
|
||||
)
|
||||
|
||||
// Shipped lists every plugin the launcher installs, including the shared
|
||||
// runtime the others depend on.
|
||||
var Shipped = []Spec{LocalIdentity, LoginUI, CashShop, FChat, GameNames}
|
||||
|
||||
func (s Spec) FileName() string { return s.fileName }
|
||||
|
||||
func (s Spec) validate() error {
|
||||
if s.fileName == "" || filepath.Base(s.fileName) != s.fileName || path.Base(s.fileName) != s.fileName || strings.ContainsAny(s.fileName, `\:`) || filepath.Ext(s.fileName) != ".dll" {
|
||||
return errors.New("clientplugin: invalid plugin specification")
|
||||
func validateName(name string) error {
|
||||
if name == "" || filepath.Base(name) != name || path.Base(name) != name || strings.ContainsAny(name, `\:`) || filepath.Ext(name) != ".dll" {
|
||||
return errors.New("clientplugin: invalid plugin file name")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -60,20 +42,6 @@ type SetResult struct {
|
||||
Removed []string `json:"removed,omitempty"`
|
||||
}
|
||||
|
||||
func ResolvePackaged(spec Spec, explicit string) (string, error) {
|
||||
if err := spec.validate(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if explicit != "" {
|
||||
return filepath.Clean(explicit), nil
|
||||
}
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("clientplugin: resolve client tool executable: %w", err)
|
||||
}
|
||||
return filepath.Join(filepath.Dir(executable), "plugins", spec.fileName), nil
|
||||
}
|
||||
|
||||
var installMu sync.Mutex
|
||||
|
||||
type staged struct {
|
||||
@@ -107,7 +75,7 @@ func InstallSet(gameDir string, sources []string) (SetResult, error) {
|
||||
names := make([]string, 0, len(sources))
|
||||
for _, source := range sources {
|
||||
name := filepath.Base(source)
|
||||
if err := (Spec{fileName: name}).validate(); err != nil {
|
||||
if err := validateName(name); err != nil {
|
||||
return SetResult{}, err
|
||||
}
|
||||
data, err := os.ReadFile(source)
|
||||
@@ -273,7 +241,7 @@ func readManaged(directory string) ([]string, error) {
|
||||
return nil, fmt.Errorf("clientplugin: duplicate managed plugin %q", name)
|
||||
}
|
||||
seen[strings.ToLower(name)] = true
|
||||
if err := (Spec{fileName: name}).validate(); err != nil {
|
||||
if err := validateName(name); err != nil {
|
||||
return nil, fmt.Errorf("clientplugin: invalid managed plugin %q", name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/common/util"
|
||||
)
|
||||
|
||||
type Definition struct {
|
||||
ID, ProjectPath, Framework, FileName, VersionKey string
|
||||
UsesGameSdk bool
|
||||
SharedRuntime bool
|
||||
Dependencies []string
|
||||
}
|
||||
|
||||
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"},
|
||||
}
|
||||
|
||||
func Definitions() []Definition {
|
||||
out := slices.Clone(definitions)
|
||||
for i := range out {
|
||||
out[i].Dependencies = slices.Clone(out[i].Dependencies)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func validateDefinitions() error {
|
||||
byID := make(map[string]Definition, len(definitions))
|
||||
outputs, projects := map[string]bool{}, map[string]bool{}
|
||||
for _, d := range definitions {
|
||||
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), "..") {
|
||||
return fmt.Errorf("clientplugin: invalid project definition %q", d.ID)
|
||||
}
|
||||
_, duplicate := byID[d.ID]
|
||||
if duplicate || outputs[strings.ToLower(d.FileName)] || projects[d.Name()] {
|
||||
return fmt.Errorf("clientplugin: duplicate plugin definition %s", d.ID)
|
||||
}
|
||||
byID[d.ID], outputs[strings.ToLower(d.FileName)], projects[d.Name()] = d, true, true
|
||||
}
|
||||
visited, visiting := map[string]bool{}, map[string]bool{}
|
||||
var visit func(string) error
|
||||
visit = func(id string) error {
|
||||
if visiting[id] {
|
||||
return fmt.Errorf("clientplugin: cyclic dependency at %s", id)
|
||||
}
|
||||
if visited[id] {
|
||||
return nil
|
||||
}
|
||||
d, ok := byID[id]
|
||||
if !ok {
|
||||
return fmt.Errorf("clientplugin: unknown dependency %s", id)
|
||||
}
|
||||
visiting[id] = true
|
||||
for _, dependency := range d.Dependencies {
|
||||
if err := visit(dependency); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
visiting[id], visited[id] = false, true
|
||||
return nil
|
||||
}
|
||||
for _, d := range definitions {
|
||||
if err := visit(d.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d Definition) Name() string {
|
||||
return strings.TrimSuffix(filepath.Base(d.ProjectPath), filepath.Ext(d.ProjectPath))
|
||||
}
|
||||
|
||||
func (d Definition) ProjectFile(root string) string {
|
||||
return filepath.Join(root, "plugins", filepath.FromSlash(d.ProjectPath))
|
||||
}
|
||||
|
||||
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 {
|
||||
projects := map[string]bool{d.Name(): true}
|
||||
var visit func(Definition)
|
||||
visit = func(current Definition) {
|
||||
for _, id := range current.Dependencies {
|
||||
for _, dependency := range definitions {
|
||||
if dependency.ID == id && !projects[dependency.Name()] {
|
||||
projects[dependency.Name()] = true
|
||||
visit(dependency)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
visit(d)
|
||||
return projects
|
||||
}
|
||||
|
||||
func verifyDependencyOutputs(root string) error {
|
||||
for _, d := range definitions {
|
||||
projects := d.dependencyProjects()
|
||||
for _, dependency := range definitions {
|
||||
if !dependency.SharedRuntime || d.ID == dependency.ID || !projects[dependency.Name()] {
|
||||
continue
|
||||
}
|
||||
canonical, err := util.SHA256File(dependency.Output(root))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
copied, err := util.SHA256File(filepath.Join(filepath.Dir(d.Output(root)), dependency.FileName))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if canonical != copied {
|
||||
return fmt.Errorf("clientplugin: %s uses a different %s", d.Name(), dependency.FileName)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Artifact struct {
|
||||
ID, Name, Source, VersionKey, Version, SHA256 string
|
||||
}
|
||||
|
||||
type Set []Artifact
|
||||
|
||||
func Development(root string) Set {
|
||||
set := make(Set, 0, len(definitions))
|
||||
for _, d := range definitions {
|
||||
set = append(set, Artifact{ID: d.ID, Name: d.FileName, Source: d.Output(root), VersionKey: d.VersionKey})
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
func (set Set) Sources() ([]string, error) {
|
||||
if len(set) == 0 {
|
||||
return nil, errors.New("clientplugin: plugin set contains no files")
|
||||
}
|
||||
sources := make([]string, 0, len(set))
|
||||
seen := map[string]bool{}
|
||||
for _, artifact := range set {
|
||||
if err := validateName(artifact.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if filepath.Base(artifact.Source) != artifact.Name {
|
||||
return nil, fmt.Errorf("clientplugin: source name differs from %s", artifact.Name)
|
||||
}
|
||||
key := strings.ToLower(artifact.Name)
|
||||
if seen[key] {
|
||||
return nil, fmt.Errorf("clientplugin: duplicate plugin %s", artifact.Name)
|
||||
}
|
||||
seen[key] = true
|
||||
sum, err := util.SHA256File(artifact.Source)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("clientplugin: read %s: %w", artifact.Name, err)
|
||||
}
|
||||
if artifact.SHA256 != "" && artifact.SHA256 != sum {
|
||||
return nil, fmt.Errorf("stored plugin %s failed verification", artifact.Name)
|
||||
}
|
||||
sources = append(sources, artifact.Source)
|
||||
}
|
||||
return sources, nil
|
||||
}
|
||||
|
||||
const StoreFile = "plugins.json"
|
||||
|
||||
type Store struct {
|
||||
Version string `json:"version"`
|
||||
Files []StoredFile `json:"files"`
|
||||
}
|
||||
|
||||
type StoredFile struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version,omitempty"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
func ReadStore(directory string) (Store, error) {
|
||||
var store Store
|
||||
raw, err := os.ReadFile(filepath.Join(directory, "plugins", StoreFile))
|
||||
if err != nil {
|
||||
return store, err
|
||||
}
|
||||
return store, json.Unmarshal(raw, &store)
|
||||
}
|
||||
|
||||
func Packaged(directory string) (Set, error) {
|
||||
store, err := ReadStore(directory)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("clientplugin: read packaged plugins: %w", err)
|
||||
}
|
||||
set := make(Set, 0, len(store.Files))
|
||||
for _, f := range store.Files {
|
||||
if err := validateName(f.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(f.SHA256) != 64 {
|
||||
return nil, fmt.Errorf("clientplugin: missing SHA-256 for %s", f.Name)
|
||||
}
|
||||
set = append(set, Artifact{ID: f.ID, Name: f.Name, Source: filepath.Join(directory, "plugins", f.Name), Version: f.Version, SHA256: f.SHA256})
|
||||
}
|
||||
if _, err := set.Sources(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
clientconfig "bd2server/internal/client/config"
|
||||
"bd2server/internal/client/download"
|
||||
"bd2server/internal/client/layout"
|
||||
"bd2server/internal/client/plugin"
|
||||
"bd2server/internal/client/setup"
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
@@ -26,9 +27,9 @@ type Options struct {
|
||||
Workers int
|
||||
DownloadOnly, BaseOnly, ProbeOnly, PlanOnly bool
|
||||
DownloadIfMissing bool
|
||||
LocalIdentityPlugin, LoginUIPlugin string
|
||||
CashShopPlugin, FChatPlugin string
|
||||
Plugins plugin.Set
|
||||
PrepareGame func(context.Context, string, clientconfig.Settings) (versionconfig.Config, error)
|
||||
Progress func(download.Progress)
|
||||
SavePreferences func(string) error
|
||||
}
|
||||
|
||||
@@ -93,7 +94,7 @@ func Run(ctx context.Context, options Options, out io.Writer) (Result, error) {
|
||||
installed, err := download.Client(ctx, download.Options{
|
||||
PackageDir: directory, Manifest: options.DownloadManifest,
|
||||
GameDir: result.GameDirectory, ResourceDir: result.ResourceDirectory, ServerOrigin: result.Settings.ServerOrigin,
|
||||
Workers: options.Workers, ProbeOnly: options.ProbeOnly,
|
||||
Workers: options.Workers, ProbeOnly: options.ProbeOnly, Progress: options.Progress,
|
||||
}, out)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -204,13 +205,15 @@ func Run(ctx context.Context, options Options, out io.Writer) (Result, error) {
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "base:plugins", DependsOn: []string{"base:patch"}, Run: func(context.Context) error {
|
||||
sources := []*string{&options.LocalIdentityPlugin, &options.LoginUIPlugin, &options.CashShopPlugin, &options.FChatPlugin}
|
||||
for n, name := range []string{"BD2LocalIdentity.dll", "BD2LoginUI.dll", "BD2CashShop.dll", "BD2FChat.dll"} {
|
||||
if *sources[n] == "" {
|
||||
*sources[n] = filepath.Join(directory, "plugins", name)
|
||||
plugins := options.Plugins
|
||||
if plugins == nil {
|
||||
var err error
|
||||
plugins, err = plugin.Packaged(directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err := setup.InstallPlugins(result.GameDirectory, options.LocalIdentityPlugin, options.LoginUIPlugin, options.CashShopPlugin, options.FChatPlugin)
|
||||
_, err := setup.InstallPlugins(result.GameDirectory, plugins)
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "base:preferences", DependsOn: []string{"base:plugins"}, Run: func(context.Context) error {
|
||||
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -116,32 +115,11 @@ func Patch(gameDir string) (introdb.Result, error) {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func InstallPlugins(
|
||||
gameDir string,
|
||||
localIdentitySource string,
|
||||
loginUISource string,
|
||||
cashShopSource string,
|
||||
fChatSource string,
|
||||
) (InstallResult, error) {
|
||||
installation, err := clientlayout.Resolve(gameDir)
|
||||
func InstallPlugins(gameDir string, plugins plugin.Set) (InstallResult, error) {
|
||||
sources, err := plugins.Sources()
|
||||
if err != nil {
|
||||
return InstallResult{}, err
|
||||
}
|
||||
if !regularFile(filepath.Join(installation.BepInEx, "core", "BepInEx.dll")) {
|
||||
return InstallResult{}, fmt.Errorf("BepInEx is not installed; install it from %s before installing the plugins", plugin.BepInExReleasesURL)
|
||||
}
|
||||
var sources []string
|
||||
for spec, explicit := range map[plugin.Spec]string{plugin.LocalIdentity: localIdentitySource, plugin.LoginUI: loginUISource, plugin.CashShop: cashShopSource, plugin.FChat: fChatSource} {
|
||||
source, err := plugin.ResolvePackaged(spec, explicit)
|
||||
if err != nil {
|
||||
return InstallResult{}, err
|
||||
}
|
||||
sources = append(sources, source)
|
||||
}
|
||||
// The shared runtime ships beside the plugins, including development builds.
|
||||
localSource, _ := plugin.ResolvePackaged(plugin.LocalIdentity, localIdentitySource)
|
||||
sources = append(sources, filepath.Join(filepath.Dir(localSource), plugin.GameNames.FileName()))
|
||||
sort.Strings(sources)
|
||||
return plugin.InstallSet(gameDir, sources)
|
||||
}
|
||||
|
||||
|
||||
@@ -158,7 +158,8 @@ func (m *Manager) ensureGame(ctx context.Context, game string) error {
|
||||
resources = filepath.Join(m.options.Directory, "resources")
|
||||
}
|
||||
m.options.Logger.Info("downloading required game and resources", "game", game, "resources", resources, "game_version", fp.Game.GameVersion, "bundle_version", fp.Game.BundleVersion, "game_data_version", fp.Game.GameDataVersion)
|
||||
installed, err := download.Client(ctx, download.Options{PackageDir: m.options.Directory, GameDir: game, ResourceDir: resources, Workers: 8, Pinned: fp.Game}, io.Discard)
|
||||
installed, err := download.Client(ctx, download.Options{PackageDir: m.options.Directory, GameDir: game, ResourceDir: resources, Workers: 8, Pinned: fp.Game, Progress: m.ReportDownload(DownloadGame)}, io.Discard)
|
||||
m.EndDownload()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/util"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -23,6 +22,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/client/download"
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
"bd2server/internal/client/plugin"
|
||||
"bd2server/internal/client/setup"
|
||||
@@ -32,21 +32,6 @@ import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
|
||||
// StoreFile describes the launcher's plugin store, plugins/plugins.json.
|
||||
const StoreFile = "plugins.json"
|
||||
|
||||
type Store struct {
|
||||
Version string `json:"version"`
|
||||
Files []StoredFile `json:"files"`
|
||||
}
|
||||
|
||||
type StoredFile struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version,omitempty"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type Offer struct {
|
||||
Version string `json:"version"`
|
||||
Date string `json:"date,omitempty"`
|
||||
@@ -68,8 +53,22 @@ type Status struct {
|
||||
// Waiting lists game directories whose new plugins install on exit.
|
||||
Waiting []string `json:"waiting,omitempty"`
|
||||
Message *Message `json:"message,omitempty"`
|
||||
// Download is the running download the launcher shows as a progress card.
|
||||
Download *Download `json:"download,omitempty"`
|
||||
}
|
||||
|
||||
// Download is a running download of the launcher, plugins or the game.
|
||||
type Download struct {
|
||||
Kind string `json:"kind"`
|
||||
download.Progress
|
||||
}
|
||||
|
||||
// Download kinds.
|
||||
const (
|
||||
DownloadUpdate = "update"
|
||||
DownloadGame = "game"
|
||||
)
|
||||
|
||||
// Message is a translation key with arguments, rendered by the launcher UI.
|
||||
type Message struct {
|
||||
Key string `json:"key"`
|
||||
@@ -84,7 +83,7 @@ type Options struct {
|
||||
Logger *slog.Logger
|
||||
Client *http.Client
|
||||
Development bool
|
||||
DevelopmentPlugins []string
|
||||
DevelopmentPlugins plugin.Set
|
||||
// Games returns the main game directory the launcher manages.
|
||||
Games func() string
|
||||
}
|
||||
@@ -137,6 +136,10 @@ func (m *Manager) Status() Status {
|
||||
return &out
|
||||
}
|
||||
out.Launcher, out.Plugins, out.Game = cloneOffer(out.Launcher), cloneOffer(out.Plugins), cloneOffer(out.Game)
|
||||
if out.Download != nil {
|
||||
progress := *out.Download
|
||||
out.Download = &progress
|
||||
}
|
||||
if out.Message != nil {
|
||||
message := *out.Message
|
||||
message.Args = slices.Clone(message.Args)
|
||||
@@ -368,18 +371,8 @@ func (m *Manager) pluginStaging(version string) string {
|
||||
return filepath.Join(m.options.Directory, ".update", "plugins", version)
|
||||
}
|
||||
|
||||
// ReadStore returns the launcher's plugin store description.
|
||||
func ReadStore(directory string) (Store, error) {
|
||||
var store Store
|
||||
raw, err := os.ReadFile(filepath.Join(directory, "plugins", StoreFile))
|
||||
if err != nil {
|
||||
return store, err
|
||||
}
|
||||
return store, json.Unmarshal(raw, &store)
|
||||
}
|
||||
|
||||
func (m *Manager) storeVersion() string {
|
||||
store, err := ReadStore(m.options.Directory)
|
||||
store, err := plugin.ReadStore(m.options.Directory)
|
||||
if err != nil || store.Version == "" {
|
||||
return m.options.Versions.ClientVersion
|
||||
}
|
||||
@@ -387,7 +380,7 @@ func (m *Manager) storeVersion() string {
|
||||
}
|
||||
|
||||
func (m *Manager) storeMatches(component *release.Component) bool {
|
||||
store, err := ReadStore(m.options.Directory)
|
||||
store, err := plugin.ReadStore(m.options.Directory)
|
||||
if err != nil || store.Version != component.Version || len(store.Files) != len(component.Files) {
|
||||
return false
|
||||
}
|
||||
@@ -433,20 +426,34 @@ func (m *Manager) Download(ctx context.Context) error {
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.status.Total = total
|
||||
files := 0
|
||||
for _, j := range jobs {
|
||||
files += len(j.files)
|
||||
}
|
||||
m.status.Download = &Download{Kind: DownloadUpdate, Progress: download.Progress{Total: total, Files: files}}
|
||||
m.mu.Unlock()
|
||||
defer m.EndDownload()
|
||||
var finished int64
|
||||
for _, j := range jobs {
|
||||
phase := "plugins"
|
||||
if j.offer == launcher {
|
||||
phase = "launcher"
|
||||
}
|
||||
for _, f := range j.files {
|
||||
m.options.Logger.Info("downloading update file", "version", j.offer.Version, "file", f.Name, "bytes", f.Size)
|
||||
_, err := release.Download(ctx, m.options.Client, m.manifestURL, f, j.staging, func(_ string, done, _ int64) {
|
||||
m.mu.Lock()
|
||||
m.status.Done = finished + done
|
||||
m.status.Download.Phase, m.status.Download.Done = phase, finished+done
|
||||
m.mu.Unlock()
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
finished += f.Size
|
||||
m.mu.Lock()
|
||||
m.status.Download.FilesDone++
|
||||
m.mu.Unlock()
|
||||
}
|
||||
m.mu.Lock()
|
||||
j.offer.Ready = true
|
||||
@@ -521,7 +528,7 @@ func (m *Manager) replaceStore(c *release.Component) error {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(next) }()
|
||||
store := Store{Version: c.Version}
|
||||
store := plugin.Store{Version: c.Version}
|
||||
for _, f := range c.Files {
|
||||
source := filepath.Join(current, f.Name)
|
||||
if !release.Matches(source, f) {
|
||||
@@ -536,9 +543,9 @@ func (m *Manager) replaceStore(c *release.Component) error {
|
||||
if !release.Matches(filepath.Join(next, f.Name), f) {
|
||||
return fmt.Errorf("plugin %s changed while copying", f.Name)
|
||||
}
|
||||
store.Files = append(store.Files, StoredFile{ID: f.ID, Name: f.Name, Version: f.Version, SHA256: f.SHA256})
|
||||
store.Files = append(store.Files, plugin.StoredFile{ID: f.ID, Name: f.Name, Version: f.Version, SHA256: f.SHA256})
|
||||
}
|
||||
if err := commonconfig.Save(filepath.Join(next, StoreFile), store, commonconfig.WriteOptions{}); err != nil {
|
||||
if err := commonconfig.Save(filepath.Join(next, plugin.StoreFile), store, commonconfig.WriteOptions{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.RemoveAll(previous); err != nil {
|
||||
@@ -564,30 +571,11 @@ func (m *Manager) StoreSources() ([]string, error) {
|
||||
}
|
||||
|
||||
func (m *Manager) storeSources() ([]string, error) {
|
||||
directory := filepath.Join(m.options.Directory, "plugins")
|
||||
store, err := ReadStore(m.options.Directory)
|
||||
set, err := plugin.Packaged(m.options.Directory)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var sources []string
|
||||
if len(store.Files) == 0 {
|
||||
return nil, errors.New("plugin store contains no files")
|
||||
}
|
||||
for _, f := range store.Files {
|
||||
if filepath.Base(f.Name) != f.Name || strings.ContainsAny(f.Name, `\:`) || filepath.Ext(f.Name) != ".dll" {
|
||||
return nil, fmt.Errorf("invalid stored plugin %q", f.Name)
|
||||
}
|
||||
source := filepath.Join(directory, f.Name)
|
||||
digest, err := util.SHA256File(source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if digest != f.SHA256 {
|
||||
return nil, fmt.Errorf("stored plugin %s failed verification", f.Name)
|
||||
}
|
||||
sources = append(sources, source)
|
||||
}
|
||||
return sources, nil
|
||||
return set.Sources()
|
||||
}
|
||||
|
||||
// EnsurePlugins installs the store set into a closed game instance when it
|
||||
@@ -604,21 +592,15 @@ func (m *Manager) ensurePlugins(game string) error {
|
||||
var sources []string
|
||||
var err error
|
||||
if m.options.Development {
|
||||
sources = m.options.DevelopmentPlugins
|
||||
if len(sources) == 0 {
|
||||
return errors.New("development plugin sources are missing")
|
||||
}
|
||||
sources, err = m.options.DevelopmentPlugins.Sources()
|
||||
} else {
|
||||
sources, err = m.storeSources()
|
||||
}
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if versions := m.Versions(game); versions.GameVersion != "" && !m.options.Development {
|
||||
store, err := ReadStore(m.options.Directory)
|
||||
store, err := plugin.ReadStore(m.options.Directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -799,7 +781,7 @@ func (m *Manager) CheckServer(ctx context.Context, client *http.Client, origin s
|
||||
installed := m.options.Versions.Plugins.ByID()
|
||||
if !m.options.Development {
|
||||
installed = map[string]string{}
|
||||
store, err := ReadStore(m.options.Directory)
|
||||
store, err := plugin.ReadStore(m.options.Directory)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
@@ -905,3 +887,30 @@ func (m *Manager) WithLaunch(ctx context.Context, client *http.Client, game, ori
|
||||
}
|
||||
return launch()
|
||||
}
|
||||
|
||||
// ReportDownload returns a progress callback that shows kind's download.
|
||||
func (m *Manager) ReportDownload(kind string) func(download.Progress) {
|
||||
return func(p download.Progress) {
|
||||
m.mu.Lock()
|
||||
m.status.Download = &Download{Kind: kind, Progress: p}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// EndDownload hides the download progress.
|
||||
func (m *Manager) EndDownload() {
|
||||
m.mu.Lock()
|
||||
m.status.Download = nil
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// DownloadProgress reports the running download, or nil.
|
||||
func (m *Manager) DownloadProgress() *Download {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.status.Download == nil {
|
||||
return nil
|
||||
}
|
||||
progress := *m.status.Download
|
||||
return &progress
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/client/plugin"
|
||||
"bd2server/internal/common/release"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
@@ -96,12 +97,12 @@ func TestPluginOnlyRemovalStillOffersAndAppliesTheNewSet(t *testing.T) {
|
||||
m.manifestURL, m.keys = server.URL+"/manifest.json", keys
|
||||
writeFixture(t, filepath.Join(root, "plugins", keep.Name), "same login")
|
||||
writeFixture(t, filepath.Join(root, "plugins", "BD2FChat.dll"), "old chat")
|
||||
store := Store{Version: "2.36.7+client.0.1.0", Files: []StoredFile{{Name: keep.Name, SHA256: keep.SHA256}, {Name: "BD2FChat.dll"}}}
|
||||
store := plugin.Store{Version: "2.36.7+client.0.1.0", Files: []plugin.StoredFile{{Name: keep.Name, SHA256: keep.SHA256}, {Name: "BD2FChat.dll"}}}
|
||||
encoded, err := json.Marshal(store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeFixture(t, filepath.Join(root, "plugins", StoreFile), string(encoded))
|
||||
writeFixture(t, filepath.Join(root, "plugins", plugin.StoreFile), string(encoded))
|
||||
if err := m.Check(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -115,7 +116,7 @@ func TestPluginOnlyRemovalStillOffersAndAppliesTheNewSet(t *testing.T) {
|
||||
if _, err := os.Stat(filepath.Join(root, "plugins", "BD2FChat.dll")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("dropped plugin remains: %v", err)
|
||||
}
|
||||
store, err = ReadStore(root)
|
||||
store, err = plugin.ReadStore(root)
|
||||
if err != nil || store.Version != component.Version || len(store.Files) != 1 {
|
||||
t.Fatalf("store = %+v, %v", store, err)
|
||||
}
|
||||
@@ -234,7 +235,7 @@ func TestPluginUpdateWaitsForRunningGameExitAndPreservesPlayerConfig(t *testing.
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertContent(t, filepath.Join(root, "plugins", f.Name), "new login")
|
||||
store, err := ReadStore(root)
|
||||
store, err := plugin.ReadStore(root)
|
||||
if err != nil || store.Version != component.Version || len(store.Files) != 1 || store.Files[0].SHA256 != f.SHA256 {
|
||||
t.Fatalf("committed plugin store = %+v, %v", store, err)
|
||||
}
|
||||
@@ -264,12 +265,21 @@ func TestWithLaunchKeepsUpdatesExcludedThroughProcessStartAndReturnsLaunchError(
|
||||
game := filepath.Join(root, "game")
|
||||
writeFixture(t, filepath.Join(game, "BrownDust II.exe"), "fixture")
|
||||
writeFixture(t, filepath.Join(game, "BrownDust II_Data", "resources.assets"), "fixture")
|
||||
file := releaseFile("BD2LoginUI.dll", "installed login")
|
||||
writeFixture(t, filepath.Join(root, "plugins", file.Name), "installed login")
|
||||
writeFixture(t, filepath.Join(game, "BepInEx", "plugins", file.Name), "installed login")
|
||||
store := plugin.Store{Version: "2.36.7+client.0.1.0", Files: []plugin.StoredFile{{Name: file.Name, SHA256: file.SHA256}}}
|
||||
encoded, err := json.Marshal(store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeFixture(t, filepath.Join(root, "plugins", plugin.StoreFile), string(encoded))
|
||||
server := httptest.NewServer(http.NotFoundHandler())
|
||||
defer server.Close()
|
||||
m := New(Options{Directory: root})
|
||||
failure := errors.New("process start failed")
|
||||
called := false
|
||||
err := m.WithLaunch(context.Background(), server.Client(), game, server.URL, func() error {
|
||||
err = m.WithLaunch(context.Background(), server.Client(), game, server.URL, func() error {
|
||||
called = true
|
||||
if !m.Busy() {
|
||||
t.Error("operation was released before process start")
|
||||
|
||||
@@ -25,10 +25,15 @@ func LoadInns(root, version string, pack int) ([]InnRule, error) {
|
||||
return nil, err
|
||||
}
|
||||
defer done()
|
||||
return loadInns(db, shared)
|
||||
scenes, closeScenes, err := openLogicalReadDB(root, version, "FieldObjectSceneData")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer closeScenes()
|
||||
return loadInns(db, shared, scenes, pack)
|
||||
}
|
||||
|
||||
func loadInns(db, shared *sql.DB) ([]InnRule, error) {
|
||||
func loadInns(db, shared, scenes *sql.DB, pack int) ([]InnRule, error) {
|
||||
rows, err := db.Query("SELECT id,ProtoBuf FROM FieldNpcTable ORDER BY id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -50,17 +55,12 @@ func loadInns(db, shared *sql.DB) ([]InnRule, error) {
|
||||
if !slices.Contains(interactions, uint64(2)) {
|
||||
continue
|
||||
}
|
||||
mapID, e := optionalScalar(raw, 14)
|
||||
if e != nil {
|
||||
_ = rows.Close()
|
||||
return nil, e
|
||||
}
|
||||
recovery, e := optionalScalar(raw, 21)
|
||||
if e != nil || recovery == 0 || mapID == 0 {
|
||||
if e != nil || recovery == 0 {
|
||||
_ = rows.Close()
|
||||
return nil, fmt.Errorf("gamedata: invalid motel NPC %d", id)
|
||||
}
|
||||
rules = append(rules, InnRule{NPCID: id, MapID: mapID})
|
||||
rules = append(rules, InnRule{NPCID: id})
|
||||
recoveryIDs = append(recoveryIDs, recovery)
|
||||
}
|
||||
err = rows.Err()
|
||||
@@ -68,6 +68,7 @@ func loadInns(db, shared *sql.DB) ([]InnRule, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var placed []InnRule
|
||||
for i := range rules {
|
||||
r := &rules[i]
|
||||
var raw []byte
|
||||
@@ -83,13 +84,37 @@ func loadInns(db, shared *sql.DB) ([]InnRule, error) {
|
||||
if r.Currency != 4 || r.ItemCount == 0 {
|
||||
return nil, fmt.Errorf("gamedata: unsupported inn currency or HP rate")
|
||||
}
|
||||
if err = shared.QueryRow("SELECT ProtoBuf FROM MapTable WHERE id=?", r.MapID).Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.MapGroup, err = optionalScalar(raw, 18)
|
||||
placements, err := scenes.Query(fmt.Sprintf("SELECT DISTINCT sceneName FROM FieldObjectSceneData%d WHERE objectType=1 AND tableId=? ORDER BY sceneName", pack), r.NPCID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for placements.Next() {
|
||||
var scene string
|
||||
if err = placements.Scan(&scene); err != nil {
|
||||
_ = placements.Close()
|
||||
return nil, err
|
||||
}
|
||||
p := *r
|
||||
if err = shared.QueryRow("SELECT id,ProtoBuf FROM MapTable WHERE packId=? AND mapScenePath=?", pack, scene).Scan(&p.MapID, &raw); err != nil {
|
||||
_ = placements.Close()
|
||||
return nil, fmt.Errorf("gamedata: inn NPC %d scene %s: %w", r.NPCID, scene, err)
|
||||
}
|
||||
p.MapGroup, err = optionalScalar(raw, 18)
|
||||
if err != nil {
|
||||
_ = placements.Close()
|
||||
return nil, err
|
||||
}
|
||||
placed = append(placed, p)
|
||||
}
|
||||
err = placements.Err()
|
||||
_ = placements.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for i := range placed {
|
||||
r := &placed[i]
|
||||
var raw []byte
|
||||
err = db.QueryRow("SELECT ProtoBuf FROM ReputationGroupTable WHERE id=?", r.MapGroup).Scan(&raw)
|
||||
if err == nil {
|
||||
r.GoodDiscount, err = optionalScalar(raw, 2)
|
||||
@@ -101,5 +126,5 @@ func loadInns(db, shared *sql.DB) ([]InnRule, error) {
|
||||
return nil, fmt.Errorf("gamedata: invalid motel discount")
|
||||
}
|
||||
}
|
||||
return rules, nil
|
||||
return placed, nil
|
||||
}
|
||||
@@ -1095,21 +1095,6 @@ func (s *Store) handleAutoRecovery(ctx command.Context, req []byte) (int, []byte
|
||||
if caster != settings.Caster {
|
||||
return fail(fmt.Errorf("deck: automatic recovery caster differs from saved setting"))
|
||||
}
|
||||
if n.FieldCharControlDeckType == 2 {
|
||||
allExhausted := true
|
||||
for _, v := range n.Deck {
|
||||
hp, err := s.characters.CurrentHealth(ctx, v.CharacterInvenIndex)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
if hp > 0 {
|
||||
allExhausted = false
|
||||
}
|
||||
}
|
||||
if allExhausted {
|
||||
mode = 3
|
||||
}
|
||||
}
|
||||
field := s.visibleFieldDeckLocked(ctx)
|
||||
var targets []uint64
|
||||
seen := map[uint64]bool{}
|
||||
@@ -1131,7 +1116,8 @@ func (s *Store) handleAutoRecovery(ctx command.Context, req []byte) (int, []byte
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if n.FieldCharControlDeckType == 0 { //nolint:staticcheck // QF1003
|
||||
// Story field actors do not replace the player's combat party.
|
||||
if n.FieldCharControlDeckType == 0 || n.FieldCharControlDeckType == 2 { //nolint:staticcheck // QF1003
|
||||
for _, v := range n.Deck {
|
||||
if e = add(v.CharacterInvenIndex); e != nil {
|
||||
return fail(e)
|
||||
|
||||
@@ -178,5 +178,5 @@ func (s *Service) InnContext(ctx command.Context, pack, npc uint64) (gamedata.In
|
||||
state, _, e := s.reputationState(ctx, current, d.Groups[r.MapGroup])
|
||||
return r, state, e
|
||||
}
|
||||
return empty, 0, fmt.Errorf("world: motel NPC outside current map")
|
||||
return empty, 0, fmt.Errorf("world: motel NPC outside current map: pack=%d map=%d npc=%d", current, position.Position.MapID, npc)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using BepInEx.Configuration;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
internal static class AccelSettings
|
||||
{
|
||||
private const long Megabyte = 1024 * 1024;
|
||||
|
||||
internal static bool Enabled { get; private set; }
|
||||
internal static int DecodeThreads { get; private set; }
|
||||
internal static long PrefetchBudgetBytes { get; private set; }
|
||||
internal static long SceneCacheBytes { get; private set; }
|
||||
internal static bool VerboseTiming { get; private set; }
|
||||
|
||||
internal static void Bind(ConfigFile config)
|
||||
{
|
||||
Enabled = config.Bind("General", "Enabled", true,
|
||||
"Accelerate BrownDustX character (Spine) mod loading. When false only load timings are logged, for comparison. Requires restart.").Value;
|
||||
DecodeThreads = config.Bind("Performance", "DecodeThreads", 0,
|
||||
"Background PNG decode threads. 0 uses the processor count minus one, capped at 8. Requires restart.").Value;
|
||||
PrefetchBudgetBytes = Megabyte * Math.Max(64, config.Bind("Performance", "PrefetchBudgetMB", 1024,
|
||||
"Decoded-but-not-yet-uploaded texture memory allowed while preloading all mods at startup. Requires restart.").Value);
|
||||
SceneCacheBytes = Megabyte * Math.Max(0, config.Bind("Performance", "SceneCacheMB", 512,
|
||||
"Texture memory kept across scene changes when BrownDustX loads mods on demand (Preload all Mods = No). 0 disables. Requires restart.").Value);
|
||||
VerboseTiming = config.Bind("Logging", "VerboseTiming", false,
|
||||
"Log one timing line per character mod during the startup preload.").Value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>disable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<AssemblyName>BD2BrownDustXAccel</AssemblyName>
|
||||
<RootNamespace>Bd2BrownDustXAccel</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="BepInEx">
|
||||
<HintPath>$(BD2BepInExDir)\core\BepInEx.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="0Harmony">
|
||||
<HintPath>$(BD2BepInExDir)\core\0Harmony.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="UnityEngine.CoreModule">
|
||||
<HintPath>$(BD2ManagedDir)\UnityEngine.CoreModule.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="UnityEngine">
|
||||
<HintPath>$(BD2ManagedDir)\UnityEngine.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="UnityEngine.IMGUIModule">
|
||||
<HintPath>$(BD2ManagedDir)\UnityEngine.IMGUIModule.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="UnityEngine.TextRenderingModule">
|
||||
<HintPath>$(BD2ManagedDir)\UnityEngine.TextRenderingModule.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="UnityEngine.ImageConversionModule">
|
||||
<HintPath>$(BD2ManagedDir)\UnityEngine.ImageConversionModule.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="spine-unity">
|
||||
<HintPath>$(BD2ManagedDir)\spine-unity.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="spine-csharp">
|
||||
<HintPath>$(BD2ManagedDir)\spine-csharp.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="UniTask">
|
||||
<HintPath>$(BD2ManagedDir)\UniTask.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using BepInEx.Configuration;
|
||||
using HarmonyLib;
|
||||
using Spine.Unity;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
/// <summary>Reflection view of the BrownDustX members the loader replaces; binding fails as a whole when any is missing.</summary>
|
||||
internal sealed class BrownDustXApi
|
||||
{
|
||||
internal const string PluginId = "lynesth.bd2.browndustx";
|
||||
internal const string AssemblyName = "lynesth.bd2.browndustx";
|
||||
|
||||
internal Type PreloadModData { get; private set; }
|
||||
internal Type PreparedRuntime { get; private set; }
|
||||
internal MethodInfo LoadModDataByName { get; private set; }
|
||||
internal MethodInfo LoadModDataPreloaded { get; private set; }
|
||||
internal MethodInfo PrepareModForLoading { get; private set; }
|
||||
internal Assembly Assembly { get; private set; }
|
||||
internal MethodInfo AddModFolder { get; private set; }
|
||||
internal MethodInfo GetMods { get; private set; }
|
||||
internal MethodInfo CheckModFolders { get; private set; }
|
||||
internal MethodInfo Cleanup { get; private set; }
|
||||
internal MethodInfo PrepareRuntimeAsync { get; private set; }
|
||||
internal MethodInfo BuildModDataFromPrepared { get; private set; }
|
||||
|
||||
private Type modData;
|
||||
private Func<string, string> shortPath;
|
||||
private Func<Texture2D, Texture2D> resizeToMultipleOf4;
|
||||
private FieldInfo spineShader;
|
||||
private FieldInfo watcherChangesDetected;
|
||||
private FieldInfo modsDirectoryPath;
|
||||
private FieldInfo preloadAllMods;
|
||||
private PropertyInfo shouldCompressTextures;
|
||||
private FieldInfo modfileFolder;
|
||||
private FieldInfo preloadName;
|
||||
private FieldInfo preloadSkeleton;
|
||||
private FieldInfo preloadAtlasFile;
|
||||
private FieldInfo preloadAtlasTextures;
|
||||
private FieldInfo preloadModfile;
|
||||
private FieldInfo modDataSkeleton;
|
||||
private FieldInfo modDataAtlas;
|
||||
private FieldInfo preparedFolder;
|
||||
private FieldInfo preparedSkeleton;
|
||||
private FieldInfo preparedAtlasText;
|
||||
private FieldInfo preparedTexturePaths;
|
||||
|
||||
internal static BrownDustXApi Bind(Assembly assembly)
|
||||
{
|
||||
Type modManager = RequireType(assembly, "BrownDustX.ModManager");
|
||||
Type main = RequireType(assembly, "BrownDustX.BrownDustX");
|
||||
Type conf = RequireType(assembly, "BrownDustX.Conf");
|
||||
Type utils = RequireType(assembly, "BrownDustX.Utils");
|
||||
Type spineReplacer = RequireType(assembly, "BrownDustX.HarmonyPatches.SpineReplacer");
|
||||
Type modfile = RequireType(assembly, "BrownDustX.ModManager+Modfile");
|
||||
var api = new BrownDustXApi
|
||||
{
|
||||
PreloadModData = RequireType(assembly, "BrownDustX.ModManager+PreloadModData"),
|
||||
PreparedRuntime = RequireType(assembly, "BrownDustX.HarmonyPatches.SpineReplacer+PreparedRuntime"),
|
||||
modData = RequireType(assembly, "BrownDustX.ModManager+ModData"),
|
||||
};
|
||||
Type invalidList = typeof(List<string>);
|
||||
api.LoadModDataByName = RequireMethod(modManager, "LoadModData", typeof(string), modfile, invalidList);
|
||||
api.LoadModDataPreloaded = RequireMethod(modManager, "LoadModData", api.PreloadModData);
|
||||
api.PrepareModForLoading = RequireMethod(modManager, "PrepareModForLoading", typeof(string), modfile, invalidList);
|
||||
api.Assembly = assembly;
|
||||
api.AddModFolder = RequireMethod(modManager, "AddModFolder", typeof(string), invalidList, invalidList, typeof(bool));
|
||||
api.GetMods = RequireMethod(modManager, "GetMods", main);
|
||||
api.CheckModFolders = RequireMethod(modManager, "CheckModFolders", typeof(string), typeof(int), invalidList, invalidList);
|
||||
api.Cleanup = RequireMethod(main, "Cleanup", typeof(bool));
|
||||
api.PrepareRuntimeAsync = RequireMethod(spineReplacer, "PrepareRuntimeAsync", api.PreloadModData);
|
||||
api.BuildModDataFromPrepared = RequireMethod(spineReplacer, "BuildModDataFromPrepared", api.PreparedRuntime);
|
||||
if (api.LoadModDataByName.ReturnType != api.modData || api.PrepareModForLoading.ReturnType != api.PreloadModData
|
||||
|| typeof(IEnumerator) != api.GetMods.ReturnType || typeof(IEnumerator) != api.CheckModFolders.ReturnType || typeof(IEnumerator) != api.Cleanup.ReturnType)
|
||||
{
|
||||
throw new MissingMethodException("BrownDustX mod loader signatures changed");
|
||||
}
|
||||
api.shortPath = (Func<string, string>)RequireMethod(modManager, "GetShortPath", typeof(string)).CreateDelegate(typeof(Func<string, string>));
|
||||
api.resizeToMultipleOf4 = (Func<Texture2D, Texture2D>)RequireMethod(utils, "ResizeToNearestMultipleOf4", typeof(Texture2D)).CreateDelegate(typeof(Func<Texture2D, Texture2D>));
|
||||
api.spineShader = RequireField(modManager, "SpineShader");
|
||||
api.watcherChangesDetected = RequireField(main, "WatcherChangesDetected");
|
||||
api.modsDirectoryPath = RequireField(main, "ModsDirectoryPath");
|
||||
api.preloadAllMods = RequireField(conf, "PreloadAllMods");
|
||||
api.shouldCompressTextures = AccessTools.Property(conf, "ShouldCompressTextures") ?? throw new MissingMemberException("BrownDustX.Conf", "ShouldCompressTextures");
|
||||
PropertyInfo useBytesPngs = AccessTools.Property(conf, "UseBytesPNGs") ?? throw new MissingMemberException("BrownDustX.Conf", "UseBytesPNGs");
|
||||
if ((bool)useBytesPngs.GetValue(null))
|
||||
{
|
||||
throw new NotSupportedException("BrownDustX LZ4 texture mode is not supported");
|
||||
}
|
||||
api.modfileFolder = RequireField(modfile, "folder");
|
||||
api.preloadName = RequireField(api.PreloadModData, "name");
|
||||
api.preloadSkeleton = RequireField(api.PreloadModData, "skeletonDataAsset");
|
||||
api.preloadAtlasFile = RequireField(api.PreloadModData, "atlasFile");
|
||||
api.preloadAtlasTextures = RequireField(api.PreloadModData, "atlasTexturesFiles");
|
||||
api.preloadModfile = RequireField(api.PreloadModData, "modfile");
|
||||
api.modDataSkeleton = RequireField(api.modData, "skeletonDataAsset");
|
||||
api.modDataAtlas = RequireField(api.modData, "spineAtlasAsset");
|
||||
api.preparedFolder = RequireField(api.PreparedRuntime, "folder");
|
||||
api.preparedSkeleton = RequireField(api.PreparedRuntime, "skeletonDataAsset");
|
||||
api.preparedAtlasText = RequireField(api.PreparedRuntime, "atlasText");
|
||||
api.preparedTexturePaths = RequireField(api.PreparedRuntime, "texturePaths");
|
||||
return api;
|
||||
}
|
||||
|
||||
internal string ShortPath(string folder) => shortPath(folder);
|
||||
internal Texture2D ResizeToMultipleOf4(Texture2D texture) => resizeToMultipleOf4(texture);
|
||||
internal Shader SpineShader => (Shader)spineShader.GetValue(null);
|
||||
internal bool WatcherChangesDetected => (bool)watcherChangesDetected.GetValue(null);
|
||||
internal string ModsDirectoryPath => (string)modsDirectoryPath.GetValue(null);
|
||||
internal bool PreloadAllMods => ((ConfigEntry<string>)preloadAllMods.GetValue(null)).Value == "Yes";
|
||||
internal bool ShouldCompressTextures => (bool)shouldCompressTextures.GetValue(null);
|
||||
|
||||
internal string ModfileFolder(object modfile) => (string)modfileFolder.GetValue(modfile);
|
||||
|
||||
internal string PreloadName(object preload) => (string)preloadName.GetValue(preload);
|
||||
internal object PreloadModfile(object preload) => preloadModfile.GetValue(preload);
|
||||
internal TextAsset PreloadSkeleton(object preload) => (TextAsset)preloadSkeleton.GetValue(preload);
|
||||
internal void SetPreloadSkeleton(object preload, TextAsset skeleton) => preloadSkeleton.SetValue(preload, skeleton);
|
||||
internal string PreloadAtlasFile(object preload) => (string)preloadAtlasFile.GetValue(preload);
|
||||
internal string[] PreloadAtlasTextures(object preload) => (string[])preloadAtlasTextures.GetValue(preload);
|
||||
|
||||
internal object NewPreload(string name, object modfile, string atlasFile, string[] atlasTextures)
|
||||
{
|
||||
object preload = Activator.CreateInstance(PreloadModData);
|
||||
preloadAtlasFile.SetValue(preload, atlasFile);
|
||||
preloadAtlasTextures.SetValue(preload, atlasTextures);
|
||||
preloadName.SetValue(preload, name);
|
||||
preloadModfile.SetValue(preload, modfile);
|
||||
return preload;
|
||||
}
|
||||
|
||||
internal object NewModData(TextAsset skeleton, SpineAtlasAsset atlas)
|
||||
{
|
||||
object data = Activator.CreateInstance(modData);
|
||||
modDataSkeleton.SetValue(data, skeleton);
|
||||
modDataAtlas.SetValue(data, atlas);
|
||||
return data;
|
||||
}
|
||||
|
||||
internal void FillPrepared(object prepared, string folder, TextAsset skeleton, string atlasText, string[] texturePaths)
|
||||
{
|
||||
preparedFolder.SetValue(prepared, folder);
|
||||
preparedSkeleton.SetValue(prepared, skeleton);
|
||||
preparedAtlasText.SetValue(prepared, atlasText);
|
||||
preparedTexturePaths.SetValue(prepared, texturePaths);
|
||||
}
|
||||
|
||||
private static Type RequireType(Assembly assembly, string name) =>
|
||||
assembly.GetType(name, false) ?? throw new TypeLoadException("BrownDustX type missing: " + name);
|
||||
|
||||
private static MethodInfo RequireMethod(Type type, string name, params Type[] parameters) =>
|
||||
AccessTools.Method(type, name, parameters) ?? throw new MissingMethodException(type.FullName, name);
|
||||
|
||||
private static FieldInfo RequireField(Type type, string name) =>
|
||||
AccessTools.Field(type, name) ?? throw new MissingFieldException(type.FullName, name);
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
/// <summary>Background threads that run file reads and PNG decodes; on-demand loads jump ahead of startup prefetch.</summary>
|
||||
internal static class DecodeScheduler
|
||||
{
|
||||
private static readonly object Gate = new();
|
||||
private static readonly Queue<DecodeJob> Urgent = new();
|
||||
private static readonly Queue<DecodeJob> Background = new();
|
||||
private static bool started;
|
||||
|
||||
internal static int WorkerCount { get; } = AccelSettings.DecodeThreads > 0
|
||||
? Math.Min(AccelSettings.DecodeThreads, 32)
|
||||
: Math.Max(1, Math.Min(8, Environment.ProcessorCount - 1));
|
||||
|
||||
internal static void Enqueue(DecodeJob job, bool urgent)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
if (!started)
|
||||
{
|
||||
started = true;
|
||||
for (int i = 0; i < WorkerCount; i++)
|
||||
{
|
||||
new Thread(Work) { IsBackground = true, Name = "BrownDustXAccel decode " + i, Priority = ThreadPriority.BelowNormal }.Start();
|
||||
}
|
||||
}
|
||||
(urgent ? Urgent : Background).Enqueue(job);
|
||||
Monitor.Pulse(Gate);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Work()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
DecodeJob job;
|
||||
lock (Gate)
|
||||
{
|
||||
while (Urgent.Count == 0 && Background.Count == 0)
|
||||
{
|
||||
Monitor.Wait(Gate);
|
||||
}
|
||||
job = Urgent.Count > 0 ? Urgent.Dequeue() : Background.Dequeue();
|
||||
}
|
||||
if (job.TryClaim())
|
||||
{
|
||||
job.Run();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One unit of background work whose result is owned by whoever calls <see cref="Wait"/>; abandoned results are released.</summary>
|
||||
internal sealed class DecodeJob(Func<DecodeJob, IReleasable> work)
|
||||
{
|
||||
private const int Pending = 0, Running = 1, Finished = 2, Cancelled = 3;
|
||||
private readonly object sync = new();
|
||||
private int state;
|
||||
private int released;
|
||||
private volatile bool cancelRequested;
|
||||
private IReleasable result;
|
||||
private Exception error;
|
||||
|
||||
internal bool CancelRequested => cancelRequested;
|
||||
|
||||
internal bool TryClaim() => Interlocked.CompareExchange(ref state, Running, Pending) == Pending;
|
||||
|
||||
internal void Run()
|
||||
{
|
||||
try
|
||||
{
|
||||
result = work(this);
|
||||
}
|
||||
catch (Exception failure)
|
||||
{
|
||||
error = failure;
|
||||
}
|
||||
lock (sync)
|
||||
{
|
||||
state = Finished;
|
||||
Monitor.PulseAll(sync);
|
||||
}
|
||||
if (cancelRequested)
|
||||
{
|
||||
ReleaseResult();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs the job inline when no worker has started it, otherwise waits for it to finish.</summary>
|
||||
internal void Complete()
|
||||
{
|
||||
if (TryClaim())
|
||||
{
|
||||
Run();
|
||||
}
|
||||
lock (sync)
|
||||
{
|
||||
while (state is Pending or Running)
|
||||
{
|
||||
Monitor.Wait(sync);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Completes the job; the caller owns the returned result.</summary>
|
||||
internal IReleasable Wait()
|
||||
{
|
||||
Complete();
|
||||
if (state == Cancelled)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (error != null)
|
||||
{
|
||||
ExceptionDispatchInfo.Capture(error).Throw();
|
||||
}
|
||||
return Interlocked.Exchange(ref released, 1) == 0 ? result : null;
|
||||
}
|
||||
|
||||
internal void Cancel()
|
||||
{
|
||||
cancelRequested = true;
|
||||
if (Interlocked.CompareExchange(ref state, Cancelled, Pending) == Pending)
|
||||
{
|
||||
lock (sync)
|
||||
{
|
||||
Monitor.PulseAll(sync);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (Volatile.Read(ref state) == Finished)
|
||||
{
|
||||
ReleaseResult();
|
||||
}
|
||||
}
|
||||
|
||||
private void ReleaseResult()
|
||||
{
|
||||
if (Interlocked.Exchange(ref released, 1) == 0)
|
||||
{
|
||||
result?.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal interface IReleasable
|
||||
{
|
||||
void Release();
|
||||
}
|
||||
|
||||
/// <summary>Caps decoded-but-unconsumed prefetch memory; the mod being consumed always proceeds so the loader cannot stall.</summary>
|
||||
internal sealed class PrefetchBudget(long limit)
|
||||
{
|
||||
private readonly object gate = new();
|
||||
private long used;
|
||||
private int demanded = -1;
|
||||
private bool closed;
|
||||
|
||||
internal bool Acquire(long bytes, int sequence, DecodeJob job)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
while (!closed && !job.CancelRequested && used > 0 && used + bytes > limit && sequence > demanded)
|
||||
{
|
||||
Monitor.Wait(gate, 200);
|
||||
}
|
||||
if (closed || job.CancelRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
used += bytes;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal void Release(long bytes)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
used -= bytes;
|
||||
Monitor.PulseAll(gate);
|
||||
}
|
||||
}
|
||||
|
||||
internal void Demand(int sequence)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
demanded = Math.Max(demanded, sequence);
|
||||
Monitor.PulseAll(gate);
|
||||
}
|
||||
}
|
||||
|
||||
internal void Close()
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
closed = true;
|
||||
Monitor.PulseAll(gate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A decoded atlas page, or the raw PNG when only Unity can decode it.</summary>
|
||||
internal sealed class PageResult : IReleasable
|
||||
{
|
||||
private PrefetchBudget budget;
|
||||
private long charged;
|
||||
|
||||
internal string Path { get; private set; }
|
||||
internal bool Missing { get; private set; }
|
||||
internal DecodedImage Image { get; private set; }
|
||||
internal byte[] RawPng { get; private set; }
|
||||
|
||||
internal static Func<DecodeJob, IReleasable> Work(string path, bool mipmaps, PrefetchBudget budget, int sequence) =>
|
||||
job => Load(job, path, mipmaps, budget, sequence);
|
||||
|
||||
public void Release()
|
||||
{
|
||||
if (Image != null)
|
||||
{
|
||||
BufferPool.Return(Image.Pixels);
|
||||
Image = null;
|
||||
}
|
||||
RawPng = null;
|
||||
if (budget != null)
|
||||
{
|
||||
budget.Release(charged);
|
||||
budget = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static PageResult Load(DecodeJob job, string path, bool mipmaps, PrefetchBudget budget, int sequence)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return new PageResult { Path = path, Missing = true };
|
||||
}
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.SequentialScan);
|
||||
int length = checked((int)stream.Length);
|
||||
byte[] file = BufferPool.Rent(length);
|
||||
try
|
||||
{
|
||||
for (int read = 0; read < length;)
|
||||
{
|
||||
int n = stream.Read(file, read, length - read);
|
||||
if (n <= 0)
|
||||
{
|
||||
throw new EndOfStreamException(path);
|
||||
}
|
||||
read += n;
|
||||
}
|
||||
long estimate = PngDecoder.EstimateBytes(file, length, mipmaps);
|
||||
if (budget != null && !budget.Acquire(estimate, sequence, job))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
var page = new PageResult { Path = path, budget = budget, charged = estimate };
|
||||
long started = Stopwatch.GetTimestamp();
|
||||
if (PngDecoder.TryDecode(file, length, mipmaps, out DecodedImage image))
|
||||
{
|
||||
page.Image = image;
|
||||
LoadStats.AddDecode(Stopwatch.GetTimestamp() - started, image.Length, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
page.RawPng = new byte[length];
|
||||
Buffer.BlockCopy(file, 0, page.RawPng, 0, length);
|
||||
LoadStats.AddDecode(0, 0, true);
|
||||
}
|
||||
return page;
|
||||
}
|
||||
finally
|
||||
{
|
||||
BufferPool.Return(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Skeleton (.json text or .skel bytes) read off the main thread.</summary>
|
||||
internal sealed class SkeletonResult : IReleasable
|
||||
{
|
||||
private PrefetchBudget budget;
|
||||
private long charged;
|
||||
|
||||
internal string Path { get; private set; }
|
||||
internal string Text { get; private set; }
|
||||
internal byte[] Bytes { get; private set; }
|
||||
|
||||
internal static Func<DecodeJob, IReleasable> Work(string path, bool json, PrefetchBudget budget, int sequence) => job =>
|
||||
{
|
||||
long size = new FileInfo(path).Length;
|
||||
if (budget != null && !budget.Acquire(size, sequence, job))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
var result = new SkeletonResult { Path = path, budget = budget, charged = size };
|
||||
if (json)
|
||||
{
|
||||
result.Text = File.ReadAllText(path);
|
||||
}
|
||||
else
|
||||
{
|
||||
result.Bytes = File.ReadAllBytes(path);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
public void Release()
|
||||
{
|
||||
if (budget != null)
|
||||
{
|
||||
budget.Release(charged);
|
||||
budget = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
/// <summary>Counters for the startup preload summary; decode figures are written from worker threads.</summary>
|
||||
internal static class LoadStats
|
||||
{
|
||||
private static long decodeTicks;
|
||||
private static long decodedBytes;
|
||||
private static int decodedPages;
|
||||
private static int fallbackPages;
|
||||
|
||||
internal static int Mods { get; set; }
|
||||
internal static int PrefetchedPages { get; set; }
|
||||
internal static long UploadTicks { get; set; }
|
||||
internal static long WaitTicks { get; set; }
|
||||
|
||||
internal static void AddDecode(long ticks, long bytes, bool fallback)
|
||||
{
|
||||
Interlocked.Add(ref decodeTicks, ticks);
|
||||
Interlocked.Add(ref decodedBytes, bytes);
|
||||
Interlocked.Increment(ref fallback ? ref fallbackPages : ref decodedPages);
|
||||
}
|
||||
|
||||
internal static void Reset()
|
||||
{
|
||||
Interlocked.Exchange(ref decodeTicks, 0);
|
||||
Interlocked.Exchange(ref decodedBytes, 0);
|
||||
Interlocked.Exchange(ref decodedPages, 0);
|
||||
Interlocked.Exchange(ref fallbackPages, 0);
|
||||
Mods = 0;
|
||||
PrefetchedPages = 0;
|
||||
UploadTicks = 0;
|
||||
WaitTicks = 0;
|
||||
}
|
||||
|
||||
internal static string Summary() => FormattableString.Invariant(
|
||||
$"{Mods} character mods, {Volatile.Read(ref decodedPages) + Volatile.Read(ref fallbackPages)} pages ({Volatile.Read(ref decodedBytes) / (1024 * 1024)} MB pixels, {PrefetchedPages} prefetched, {Volatile.Read(ref fallbackPages)} Unity-decoded); main thread upload {Milliseconds(UploadTicks)} ms, waiting {Milliseconds(WaitTicks)} ms; decode CPU {Milliseconds(Volatile.Read(ref decodeTicks))} ms on {DecodeScheduler.WorkerCount} threads");
|
||||
|
||||
internal static long Milliseconds(long ticks) => ticks * 1000 / Stopwatch.Frequency;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
/// <summary>
|
||||
/// Draws a progress bar and the mod folder being loaded under BrownDustX's "Loading mods" dialog. The total is counted
|
||||
/// on a background thread with the same folder rules as CheckModFolders; reloads from the file watcher only process
|
||||
/// changed folders, so they show the running count without a total.
|
||||
/// </summary>
|
||||
internal static class LoadingProgress
|
||||
{
|
||||
private static FieldInfo currentModal;
|
||||
private static FieldInfo windowRect;
|
||||
private static string root;
|
||||
private static object modal;
|
||||
private static volatile int total = -1;
|
||||
private static int loaded;
|
||||
private static string current = "";
|
||||
private static GUIStyle labelStyle;
|
||||
|
||||
internal static void Install(Harmony harmony, Assembly assembly, MethodInfo addModFolder)
|
||||
{
|
||||
Type modalType = assembly.GetType("BrownDustX.Tools.Modal", false);
|
||||
MethodInfo windowFunc = modalType == null ? null : AccessTools.Method(modalType, "WindowFunc", [typeof(int)]);
|
||||
currentModal = modalType == null ? null : AccessTools.Field(modalType, "CurrentModal");
|
||||
windowRect = modalType == null ? null : AccessTools.Field(modalType, "windowRect");
|
||||
if (windowFunc == null || currentModal == null || windowRect == null || windowRect.FieldType != typeof(Rect))
|
||||
{
|
||||
Plugin.Log.LogWarning("BrownDustX loading dialog not found; progress bar disabled");
|
||||
return;
|
||||
}
|
||||
harmony.Patch(addModFolder, prefix: new HarmonyMethod(typeof(LoadingProgress), nameof(AddModFolderPrefix)));
|
||||
harmony.Patch(windowFunc, postfix: new HarmonyMethod(typeof(LoadingProgress), nameof(WindowFuncPostfix)));
|
||||
}
|
||||
|
||||
/// <summary>Called when GetMods starts, before BrownDustX's one-second wait, so the count is usually ready in time.</summary>
|
||||
internal static void Begin(string modsRoot, bool fromWatcher)
|
||||
{
|
||||
root = modsRoot;
|
||||
loaded = 0;
|
||||
current = "";
|
||||
total = -1;
|
||||
if (fromWatcher || currentModal == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
total = CountMods(modsRoot, 0);
|
||||
}
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
})
|
||||
{ IsBackground = true, Name = "BrownDustXAccel count", Priority = System.Threading.ThreadPriority.BelowNormal }.Start();
|
||||
}
|
||||
|
||||
/// <summary>The root CheckModFolders step starts right after the dialog is shown; that dialog is the one to decorate.</summary>
|
||||
internal static void ScanStarted() => modal = currentModal?.GetValue(null);
|
||||
|
||||
internal static void ScanFinished() => modal = null;
|
||||
|
||||
internal static void Enter(string folder)
|
||||
{
|
||||
if (modal == null || root == null || folder == null || !folder.StartsWith(root, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
current = folder[root.Length..].TrimStart('\\', '/').Replace('\\', '/');
|
||||
}
|
||||
|
||||
private static void AddModFolderPrefix(bool allowIntro)
|
||||
{
|
||||
if (modal != null && !allowIntro)
|
||||
{
|
||||
loaded++;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WindowFuncPostfix(object __instance)
|
||||
{
|
||||
if (modal == null || !ReferenceEquals(__instance, modal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
var window = (Rect)windowRect.GetValue(__instance);
|
||||
labelStyle ??= new GUIStyle(GUI.skin.label) { fontSize = 16, alignment = TextAnchor.MiddleCenter, clipping = TextClipping.Clip, wordWrap = false };
|
||||
labelStyle.normal.textColor = new Color(0.85f, 0.85f, 0.85f, 1f);
|
||||
int count = total;
|
||||
float width = window.width - 50f;
|
||||
var bar = new Rect(25f, window.height - 62f, width, 22f);
|
||||
string label = count > 0
|
||||
? FormattableString.Invariant($"{Math.Min(loaded, count)} / {count} ({Math.Min(loaded, count) * 100 / count}%)")
|
||||
: loaded.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
GUI.Label(new Rect(25f, window.height - 98f, width, 30f), current, labelStyle);
|
||||
Color tint = GUI.color;
|
||||
GUI.color = new Color(1f, 1f, 1f, 0.15f);
|
||||
GUI.DrawTexture(bar, Texture2D.whiteTexture);
|
||||
GUI.color = new Color(0.35f, 0.65f, 1f, 1f);
|
||||
float fraction = count > 0 ? Mathf.Clamp01((float)loaded / count) : (Time.realtimeSinceStartup * 0.5f) % 1f;
|
||||
GUI.DrawTexture(new Rect(bar.x, bar.y, bar.width * fraction, bar.height), Texture2D.whiteTexture);
|
||||
GUI.color = tint;
|
||||
GUI.Label(bar, label, labelStyle);
|
||||
}
|
||||
|
||||
/// <summary>Same rules as ModManager.CheckModFolders: below the root, a folder with exactly one non-intro .modfile is a mod.</summary>
|
||||
private static int CountMods(string folder, int depth)
|
||||
{
|
||||
if (depth > 5)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
if (depth != 0 && Directory.EnumerateFiles(folder, "*.modfile")
|
||||
.Count(f => !string.Equals(Path.GetFileName(f), "intro.modfile", StringComparison.OrdinalIgnoreCase)) == 1)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
return Directory.EnumerateDirectories(folder).Sum(child => CountMods(child, depth + 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using Spine.Unity;
|
||||
using Unity.Collections;
|
||||
using UnityEngine;
|
||||
using UnityObject = UnityEngine.Object;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
/// <summary>Error text shown in BrownDustX's "Mods Errors" dialog, kept identical to the original messages.</summary>
|
||||
internal sealed class ModLoadException : Exception
|
||||
{
|
||||
public ModLoadException()
|
||||
{
|
||||
}
|
||||
|
||||
public ModLoadException(string message) : base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public ModLoadException(string message, Exception innerException) : base(message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
internal static ModLoadException MissingTextures(BrownDustXApi api, string folder) =>
|
||||
new(api.ShortPath(folder) + " <color=#FFFF4C>(Missing or invalid textures)</color>");
|
||||
}
|
||||
|
||||
/// <summary>Only Spine character assets are accelerated; intro and other mod types keep BrownDustX's own loader.</summary>
|
||||
internal static class ModNames
|
||||
{
|
||||
private static readonly string[] CharacterPrefixes = ["char", "npc", "cutscene", "illust", "specialillust", "storypack"];
|
||||
|
||||
internal static bool IsCharacter(string name)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
foreach (string prefix in CharacterPrefixes)
|
||||
{
|
||||
if (name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class AtlasPages
|
||||
{
|
||||
/// <summary>Page names exactly as BrownDustX reads them: every line but the last that ends in ".png".</summary>
|
||||
internal static List<string> Parse(string atlasText)
|
||||
{
|
||||
string[] lines = atlasText.Replace("\r", "", StringComparison.Ordinal).Split('\n');
|
||||
var pages = new List<string>();
|
||||
for (int i = 0; i < lines.Length - 1; i++)
|
||||
{
|
||||
string line = lines[i].Trim();
|
||||
if (line.EndsWith(".png", StringComparison.Ordinal))
|
||||
{
|
||||
pages.Add(line.Replace(".png", "", StringComparison.Ordinal));
|
||||
}
|
||||
}
|
||||
return pages;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class ModAssets
|
||||
{
|
||||
/// <summary>Binary skeleton TextAsset built the same way as BrownDustX's CreateBytesTextAssetFromFile.</summary>
|
||||
internal static TextAsset SkeletonFromBytes(byte[] bytes, string name)
|
||||
{
|
||||
var asset = new TextAsset(new string(' ', bytes.Length)) { name = name };
|
||||
NativeArray<byte> data = asset.GetData<byte>();
|
||||
if (!data.IsCreated || data.Length != bytes.Length)
|
||||
{
|
||||
throw new ModLoadException(FormattableString.Invariant($"Text Creation Error: {data.Length} vs {bytes.Length}"));
|
||||
}
|
||||
NativeArray<byte>.Copy(bytes, data);
|
||||
return asset;
|
||||
}
|
||||
|
||||
/// <summary>Uploads decoded pages and builds the runtime atlas on the main thread; every page result is released.</summary>
|
||||
internal static SpineAtlasAsset BuildAtlas(BrownDustXApi api, string folder, string atlasText, string[] textureNames, DecodeJob[] jobs,
|
||||
string[] paths, bool mipmaps, bool compress, List<Texture2D> created)
|
||||
{
|
||||
var materials = new Material[jobs.Length];
|
||||
try
|
||||
{
|
||||
foreach (DecodeJob job in jobs)
|
||||
{
|
||||
if (job.TryClaim())
|
||||
{
|
||||
job.Run();
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < jobs.Length; i++)
|
||||
{
|
||||
long waitStarted = Stopwatch.GetTimestamp();
|
||||
PageResult page;
|
||||
try
|
||||
{
|
||||
page = (PageResult)jobs[i].Wait() ?? (PageResult)new DecodeJob(PageResult.Work(paths[i], mipmaps, null, 0)).Wait();
|
||||
}
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
throw ModLoadException.MissingTextures(api, folder);
|
||||
}
|
||||
long uploadStarted = Stopwatch.GetTimestamp();
|
||||
LoadStats.WaitTicks += uploadStarted - waitStarted;
|
||||
try
|
||||
{
|
||||
if (page.Missing)
|
||||
{
|
||||
throw ModLoadException.MissingTextures(api, folder);
|
||||
}
|
||||
Texture2D texture = CreateTexture(api, folder, page, mipmaps, compress);
|
||||
texture.name = textureNames[i];
|
||||
created.Add(texture);
|
||||
materials[i] = new Material(api.SpineShader) { mainTexture = texture };
|
||||
}
|
||||
finally
|
||||
{
|
||||
page.Release();
|
||||
LoadStats.UploadTicks += Stopwatch.GetTimestamp() - uploadStarted;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (DecodeJob job in jobs)
|
||||
{
|
||||
job.Cancel();
|
||||
}
|
||||
}
|
||||
return SpineAtlasAsset.CreateRuntimeInstance(new TextAsset(atlasText), materials, false, null);
|
||||
}
|
||||
|
||||
private static Texture2D CreateTexture(BrownDustXApi api, string folder, PageResult page, bool mipmaps, bool compress)
|
||||
{
|
||||
Texture2D texture;
|
||||
try
|
||||
{
|
||||
if (page.Image != null)
|
||||
{
|
||||
DecodedImage image = page.Image;
|
||||
texture = new Texture2D(image.Width, image.Height, TextureFormat.RGBA32, mipmaps);
|
||||
if (texture.mipmapCount == image.MipCount)
|
||||
{
|
||||
for (int level = 0; level < image.MipCount; level++)
|
||||
{
|
||||
texture.SetPixelData(image.Pixels, level, image.MipOffset(level));
|
||||
}
|
||||
texture.Apply(false, !compress);
|
||||
}
|
||||
else
|
||||
{
|
||||
texture.SetPixelData(image.Pixels, 0, 0);
|
||||
texture.Apply(true, !compress);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
texture = new Texture2D(1, 1, TextureFormat.RGBA32, mipmaps);
|
||||
texture.LoadImage(page.RawPng, !compress);
|
||||
}
|
||||
if (compress)
|
||||
{
|
||||
Texture2D resized = api.ResizeToMultipleOf4(texture);
|
||||
if (resized != texture)
|
||||
{
|
||||
UnityObject.Destroy(texture);
|
||||
texture = resized;
|
||||
}
|
||||
texture.Compress(true);
|
||||
texture.Apply(false, true);
|
||||
}
|
||||
}
|
||||
catch (Exception error) when (error is not ModLoadException)
|
||||
{
|
||||
throw ModLoadException.MissingTextures(api, folder);
|
||||
}
|
||||
return texture;
|
||||
}
|
||||
|
||||
internal static long TextureBytes(Texture2D texture) =>
|
||||
(long)texture.width * texture.height * 4 * (texture.mipmapCount > 1 ? 4 : 3) / 3;
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
internal static class ModLoadPatches
|
||||
{
|
||||
private static BrownDustXApi api;
|
||||
|
||||
internal static void Install(Harmony harmony, BrownDustXApi bound)
|
||||
{
|
||||
api = bound;
|
||||
ModLoader.Api = bound;
|
||||
harmony.Patch(bound.GetMods, postfix: new HarmonyMethod(typeof(ModLoadPatches), nameof(GetModsPostfix)));
|
||||
harmony.Patch(bound.CheckModFolders, postfix: new HarmonyMethod(typeof(ModLoadPatches), nameof(CheckModFoldersPostfix)));
|
||||
if (!AccelSettings.Enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
LoadingProgress.Install(harmony, bound.Assembly, bound.AddModFolder);
|
||||
harmony.Patch(bound.Cleanup, prefix: new HarmonyMethod(typeof(ModLoadPatches), nameof(CleanupPrefix)));
|
||||
PrefixInjector.Inject(harmony, bound.LoadModDataByName, nameof(ModLoader.LoadModDataByName));
|
||||
PrefixInjector.Inject(harmony, bound.PrepareModForLoading, nameof(ModLoader.PrepareModForLoading));
|
||||
PrefixInjector.Inject(harmony, bound.LoadModDataPreloaded, nameof(ModLoader.LoadModDataPreloaded));
|
||||
PrefixInjector.Inject(harmony, bound.PrepareRuntimeAsync, nameof(ModLoader.PrepareRuntimeAsync));
|
||||
PrefixInjector.Inject(harmony, bound.BuildModDataFromPrepared, nameof(ModLoader.BuildModDataFromPrepared));
|
||||
}
|
||||
|
||||
private static void GetModsPostfix(ref IEnumerator __result) => __result = new ModScan(__result);
|
||||
|
||||
private static void CheckModFoldersPostfix(string folder, int depth, ref IEnumerator __result) => __result = new FolderStep(__result, folder, depth);
|
||||
|
||||
/// <summary>BrownDustX runs GC.Collect twice (plus UnloadUnusedAssets on the splash scene) after every compressed mod; one pass at the end is enough.</summary>
|
||||
private static bool CleanupPrefix(bool unloadAssets, ref IEnumerator __result)
|
||||
{
|
||||
if (unloadAssets || !FolderStep.ScanActive)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
__result = Enumerable.Empty<object>().GetEnumerator();
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Wraps ModManager.GetMods to time the whole (re)load and to run the startup prefetch for its duration.</summary>
|
||||
private sealed class ModScan(IEnumerator inner) : IEnumerator
|
||||
{
|
||||
private long started;
|
||||
private bool begun;
|
||||
private bool ended;
|
||||
private bool prefetching;
|
||||
private bool preloadAll;
|
||||
|
||||
public object Current => inner.Current;
|
||||
|
||||
public bool MoveNext()
|
||||
{
|
||||
if (!begun)
|
||||
{
|
||||
begun = true;
|
||||
Begin();
|
||||
}
|
||||
bool more;
|
||||
try
|
||||
{
|
||||
more = inner.MoveNext();
|
||||
}
|
||||
catch
|
||||
{
|
||||
End();
|
||||
throw;
|
||||
}
|
||||
if (!more)
|
||||
{
|
||||
End();
|
||||
}
|
||||
return more;
|
||||
}
|
||||
|
||||
public void Reset() => inner.Reset();
|
||||
|
||||
private void Begin()
|
||||
{
|
||||
started = Stopwatch.GetTimestamp();
|
||||
bool fromWatcher = api.WatcherChangesDetected;
|
||||
preloadAll = api.PreloadAllMods;
|
||||
LoadStats.Reset();
|
||||
FolderStep.ScanTicks = 0;
|
||||
if (!AccelSettings.Enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
LoadingProgress.Begin(api.ModsDirectoryPath, fromWatcher);
|
||||
if (fromWatcher)
|
||||
{
|
||||
SceneCache.Clear();
|
||||
}
|
||||
else if (preloadAll)
|
||||
{
|
||||
prefetching = true;
|
||||
PreloadSession.Start(api.ModsDirectoryPath);
|
||||
}
|
||||
}
|
||||
|
||||
private void End()
|
||||
{
|
||||
if (ended)
|
||||
{
|
||||
return;
|
||||
}
|
||||
ended = true;
|
||||
long total = Stopwatch.GetTimestamp() - started;
|
||||
if (prefetching)
|
||||
{
|
||||
PreloadSession.Stop();
|
||||
}
|
||||
BufferPool.Trim();
|
||||
string mode = preloadAll ? "preload all" : "on demand";
|
||||
string head = FormattableString.Invariant($"Mod scan ({mode}, acceleration {(AccelSettings.Enabled ? "on" : "off")}) finished: folder scan {LoadStats.Milliseconds(FolderStep.ScanTicks)} ms, total {LoadStats.Milliseconds(total)} ms");
|
||||
Plugin.Log.LogInfo(AccelSettings.Enabled && preloadAll ? head + "; " + LoadStats.Summary() : head);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wraps each CheckModFolders step. The root step times the folder scan; with acceleration on, every step reports its
|
||||
/// folder to the loading dialog and yields a frame once the current frame has spent 100 ms loading, so the dialog keeps rendering.
|
||||
/// </summary>
|
||||
private sealed class FolderStep(IEnumerator inner, string folder, int depth) : IEnumerator
|
||||
{
|
||||
private static int frame = -1;
|
||||
private static float frameStarted;
|
||||
private bool entered;
|
||||
private bool yielded;
|
||||
private long started;
|
||||
|
||||
internal static bool ScanActive { get; private set; }
|
||||
internal static long ScanTicks { get; set; }
|
||||
|
||||
public object Current => yielded ? null : inner.Current;
|
||||
|
||||
public bool MoveNext()
|
||||
{
|
||||
if (!entered)
|
||||
{
|
||||
entered = true;
|
||||
if (depth == 0)
|
||||
{
|
||||
ScanActive = true;
|
||||
started = Stopwatch.GetTimestamp();
|
||||
LoadingProgress.ScanStarted();
|
||||
}
|
||||
else
|
||||
{
|
||||
LoadingProgress.Enter(folder);
|
||||
}
|
||||
if (AccelSettings.Enabled && FrameBudgetSpent())
|
||||
{
|
||||
yielded = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
yielded = false;
|
||||
bool more;
|
||||
try
|
||||
{
|
||||
more = inner.MoveNext();
|
||||
}
|
||||
catch
|
||||
{
|
||||
Finish();
|
||||
throw;
|
||||
}
|
||||
if (!more)
|
||||
{
|
||||
Finish();
|
||||
}
|
||||
return more;
|
||||
}
|
||||
|
||||
public void Reset() => inner.Reset();
|
||||
|
||||
private void Finish()
|
||||
{
|
||||
if (depth == 0 && ScanActive)
|
||||
{
|
||||
ScanActive = false;
|
||||
LoadingProgress.ScanFinished();
|
||||
ScanTicks += Stopwatch.GetTimestamp() - started;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool FrameBudgetSpent()
|
||||
{
|
||||
float now = Time.realtimeSinceStartup;
|
||||
if (Time.frameCount != frame)
|
||||
{
|
||||
frame = Time.frameCount;
|
||||
frameStarted = now;
|
||||
return false;
|
||||
}
|
||||
return now - frameStarted > 0.1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts a call to a hook in front of a BrownDustX method: <c>if (Hook(args..., out var r)) return (TReturn)r;</c>.
|
||||
/// Used instead of a plain Harmony prefix because the return types are BrownDustX classes and UniTask<PreparedRuntime>.
|
||||
/// </summary>
|
||||
internal static class PrefixInjector
|
||||
{
|
||||
private static readonly Dictionary<RuntimeMethodHandle, MethodInfo> Hooks = [];
|
||||
private static readonly FieldInfo LabelsField = AccessTools.Field(typeof(CodeInstruction), "labels");
|
||||
|
||||
internal static void Inject(Harmony harmony, MethodInfo target, string hookName)
|
||||
{
|
||||
MethodInfo hook = AccessTools.Method(typeof(ModLoader), hookName) ?? throw new MissingMethodException(nameof(ModLoader), hookName);
|
||||
if (hook.GetParameters().Length != target.GetParameters().Length + 1)
|
||||
{
|
||||
throw new MissingMethodException(target.DeclaringType?.FullName, target.Name);
|
||||
}
|
||||
Hooks[target.MethodHandle] = hook;
|
||||
harmony.Patch(target, transpiler: new HarmonyMethod(typeof(PrefixInjector), nameof(Transpile)));
|
||||
}
|
||||
|
||||
private static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase original)
|
||||
{
|
||||
var method = (MethodInfo)original;
|
||||
MethodInfo hook = Hooks[method.MethodHandle];
|
||||
LocalBuilder result = generator.DeclareLocal(typeof(object));
|
||||
Label resume = generator.DefineLabel();
|
||||
int arguments = method.GetParameters().Length + (method.IsStatic ? 0 : 1);
|
||||
for (int i = 0; i < arguments; i++)
|
||||
{
|
||||
yield return i switch
|
||||
{
|
||||
0 => new CodeInstruction(OpCodes.Ldarg_0),
|
||||
1 => new CodeInstruction(OpCodes.Ldarg_1),
|
||||
2 => new CodeInstruction(OpCodes.Ldarg_2),
|
||||
3 => new CodeInstruction(OpCodes.Ldarg_3),
|
||||
_ => new CodeInstruction(OpCodes.Ldarg_S, (byte)i),
|
||||
};
|
||||
}
|
||||
yield return new CodeInstruction(OpCodes.Ldloca_S, result);
|
||||
yield return new CodeInstruction(OpCodes.Call, hook);
|
||||
yield return new CodeInstruction(OpCodes.Brfalse, resume);
|
||||
yield return new CodeInstruction(OpCodes.Ldloc, result);
|
||||
yield return new CodeInstruction(OpCodes.Unbox_Any, method.ReturnType);
|
||||
yield return new CodeInstruction(OpCodes.Ret);
|
||||
var entry = new CodeInstruction(OpCodes.Nop);
|
||||
// CodeInstruction.labels is typed against mscorlib's Label, which the netstandard facade cannot name.
|
||||
((IList)LabelsField.GetValue(entry)).Add(resume);
|
||||
yield return entry;
|
||||
foreach (CodeInstruction instruction in instructions)
|
||||
{
|
||||
yield return instruction;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using Spine.Unity;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
/// <summary>
|
||||
/// Replacements for BrownDustX's character mod loading. Each hook returns false to fall through to the original
|
||||
/// method (non-character mods, acceleration off); otherwise it reproduces the original result and error messages.
|
||||
/// </summary>
|
||||
internal static class ModLoader
|
||||
{
|
||||
private static readonly ConditionalWeakTable<object, DeferredSkeleton> DeferredSkeletons = [];
|
||||
private static readonly ConditionalWeakTable<object, LazyWork> PreparedWork = [];
|
||||
private static MethodInfo prepareRuntimeMethod;
|
||||
|
||||
internal static BrownDustXApi Api { get; set; }
|
||||
|
||||
/// <summary>ModManager.LoadModData(string, Modfile, List<string>): startup preload ("Preload all Mods" = Yes).</summary>
|
||||
internal static bool LoadModDataByName(string modname, object modfile, List<string> invalidMods, out object result)
|
||||
{
|
||||
result = null;
|
||||
if (!ModNames.IsCharacter(modname))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
long started = Stopwatch.GetTimestamp();
|
||||
ModPrefetch prefetch = null;
|
||||
try
|
||||
{
|
||||
string folder = Api.ModfileFolder(modfile);
|
||||
if (string.IsNullOrEmpty(folder))
|
||||
{
|
||||
throw new ModLoadException(modname + " <color=#FF4C4C>(Unknown Error)</color>");
|
||||
}
|
||||
if (Api.SpineShader == null)
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(folder) + " <color=#FF4C4C>(Couldn't initialize Shader)</color>");
|
||||
}
|
||||
prefetch = PreloadSession.Current?.Take(folder);
|
||||
TextAsset skeleton = null;
|
||||
string json = Directory.GetFiles(folder, "*.json").FirstOrDefault();
|
||||
if (json != null)
|
||||
{
|
||||
if (Path.GetFileNameWithoutExtension(json).Contains(".skel", StringComparison.Ordinal))
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(folder) + " <color=#FF4C4C>(Invalid .json file)</color>");
|
||||
}
|
||||
skeleton = new TextAsset(prefetch?.TakeSkeleton(json)?.Text ?? File.ReadAllText(json)) { name = Path.GetFileName(json) };
|
||||
}
|
||||
else
|
||||
{
|
||||
string skel = Directory.GetFiles(folder, "*.skel").FirstOrDefault();
|
||||
if (skel != null)
|
||||
{
|
||||
if (Path.GetFileNameWithoutExtension(skel).Contains(".json", StringComparison.Ordinal))
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(folder) + " <color=#FF4C4C>(Invalid .skel file)</color>");
|
||||
}
|
||||
skeleton = BinarySkeleton(folder, skel, prefetch?.TakeSkeleton(skel)?.Bytes);
|
||||
}
|
||||
}
|
||||
SpineAtlasAsset atlas = null;
|
||||
string atlasPath = Directory.GetFiles(folder, "*.atlas").FirstOrDefault();
|
||||
if (atlasPath == null)
|
||||
{
|
||||
if (Directory.EnumerateFiles(folder, modname + "*.png").Any())
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(folder) + " <color=#4CFF4C>(Missing .atlas file)</color>");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
string atlasText = prefetch?.TakeAtlasText(atlasPath) ?? File.ReadAllText(atlasPath);
|
||||
List<string> pages = AtlasPages.Parse(atlasText);
|
||||
if (pages.Count > 0)
|
||||
{
|
||||
string[] paths = pages.Select(page => Path.Combine(folder, page + ".png")).ToArray();
|
||||
DecodeJob[] jobs = prefetch?.TakePageJobs(atlasPath, pages);
|
||||
if (jobs != null)
|
||||
{
|
||||
LoadStats.PrefetchedPages += jobs.Length;
|
||||
}
|
||||
jobs ??= StartPages(paths, true);
|
||||
atlas = ModAssets.BuildAtlas(Api, folder, atlasText, [.. pages], jobs, paths, true, Api.ShouldCompressTextures, []);
|
||||
}
|
||||
}
|
||||
LoadStats.Mods++;
|
||||
if (skeleton == null && atlas == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
result = Api.NewModData(skeleton, atlas);
|
||||
return true;
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
invalidMods?.Add(error.Message ?? "");
|
||||
result = null;
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
prefetch?.Cancel();
|
||||
if (AccelSettings.VerboseTiming)
|
||||
{
|
||||
Plugin.Log.LogInfo(FormattableString.Invariant($"Preloaded {modname} in {LoadStats.Milliseconds(Stopwatch.GetTimestamp() - started)} ms"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>ModManager.PrepareModForLoading: on-demand mode registration; the skeleton is read only when the mod is first shown.</summary>
|
||||
internal static bool PrepareModForLoading(string modname, object modfile, List<string> invalidMods, out object result)
|
||||
{
|
||||
result = null;
|
||||
if (!ModNames.IsCharacter(modname))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
string folder = Api.ModfileFolder(modfile);
|
||||
if (string.IsNullOrEmpty(folder))
|
||||
{
|
||||
throw new ModLoadException(modname + " <color=#FF4C4C>(Unknown Error)</color>");
|
||||
}
|
||||
if (Api.SpineShader == null)
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(folder) + " <color=#FF4C4C>(Couldn't initialize Shader)</color>");
|
||||
}
|
||||
string atlas = Directory.GetFiles(folder, "*.atlas").FirstOrDefault();
|
||||
string[] textures = null;
|
||||
if (atlas == null)
|
||||
{
|
||||
if (Directory.EnumerateFiles(folder, modname + "*.png").Any())
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(folder) + " <color=#4CFF4C>(Missing .atlas file)</color>");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
List<string> pages = AtlasPages.Parse(File.ReadAllText(atlas));
|
||||
if (pages.Count <= 0)
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(folder) + " <color=#4CFF4C>(Invalid .atlas file)</color>");
|
||||
}
|
||||
textures = new string[pages.Count];
|
||||
for (int i = 0; i < pages.Count; i++)
|
||||
{
|
||||
textures[i] = Path.Combine(folder, pages[i] + ".png");
|
||||
if (!File.Exists(textures[i]))
|
||||
{
|
||||
throw ModLoadException.MissingTextures(Api, folder);
|
||||
}
|
||||
}
|
||||
}
|
||||
DeferredSkeleton skeleton = null;
|
||||
string json = Directory.GetFiles(folder, "*.json").FirstOrDefault();
|
||||
if (json != null)
|
||||
{
|
||||
if (Path.GetFileNameWithoutExtension(json).Contains(".skel", StringComparison.Ordinal))
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(folder) + " <color=#FF4C4C>(Invalid .json file)</color>");
|
||||
}
|
||||
skeleton = new DeferredSkeleton(json, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
string skel = Directory.GetFiles(folder, "*.skel").FirstOrDefault();
|
||||
if (skel != null)
|
||||
{
|
||||
if (Path.GetFileNameWithoutExtension(skel).Contains(".json", StringComparison.Ordinal))
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(folder) + " <color=#FF4C4C>(Invalid .skel file)</color>");
|
||||
}
|
||||
skeleton = new DeferredSkeleton(skel, false);
|
||||
}
|
||||
}
|
||||
if (skeleton == null && atlas == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
result = Api.NewPreload(modname, modfile, atlas, textures);
|
||||
if (skeleton != null)
|
||||
{
|
||||
DeferredSkeletons.Add(result, skeleton);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
invalidMods?.Add(error.Message ?? "");
|
||||
result = null;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>ModManager.LoadModData(PreloadModData): synchronous on-demand load (Spine Initialize hooks, intro UI).</summary>
|
||||
internal static bool LoadModDataPreloaded(object preload, out object result)
|
||||
{
|
||||
result = null;
|
||||
if (preload == null || !ModNames.IsCharacter(Api.PreloadName(preload)) || Api.PreloadModfile(preload) == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
result = SceneCache.TryGet(preload) ?? Finish(StartLazy(preload), true);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>SpineReplacer.PrepareRuntimeAsync: decodes every page in parallel off the main thread.</summary>
|
||||
internal static bool PrepareRuntimeAsync(object preload, out object result)
|
||||
{
|
||||
result = null;
|
||||
if (preload == null || !ModNames.IsCharacter(Api.PreloadName(preload)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
prepareRuntimeMethod ??= typeof(ModLoader).GetMethod(nameof(PrepareRuntime), BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(Api.PreparedRuntime);
|
||||
result = prepareRuntimeMethod.Invoke(null, [preload]);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>SpineReplacer.BuildModDataFromPrepared: uploads the pages decoded by <see cref="PrepareRuntimeAsync"/>.</summary>
|
||||
internal static bool BuildModDataFromPrepared(object prepared, out object result)
|
||||
{
|
||||
result = null;
|
||||
if (prepared == null || !PreparedWork.TryGetValue(prepared, out LazyWork work))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
PreparedWork.Remove(prepared);
|
||||
result = work.Cached ?? Finish(work, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Generic body of the PrepareRuntimeAsync replacement, closed over SpineReplacer.PreparedRuntime via reflection.</summary>
|
||||
internal static UniTask<T> PrepareRuntime<T>(object preload) where T : class
|
||||
{
|
||||
var prepared = (T)Activator.CreateInstance(typeof(T));
|
||||
object modfile = Api.PreloadModfile(preload);
|
||||
Api.FillPrepared(prepared, modfile == null ? null : Api.ModfileFolder(modfile), Api.PreloadSkeleton(preload), null, Api.PreloadAtlasTextures(preload));
|
||||
object cached = SceneCache.TryGet(preload);
|
||||
if (cached != null)
|
||||
{
|
||||
PreparedWork.Add(prepared, new LazyWork { Preload = preload, Cached = cached });
|
||||
return UniTask.FromResult(prepared);
|
||||
}
|
||||
return UniTask.RunOnThreadPool(() =>
|
||||
{
|
||||
LazyWork work = StartLazy(preload);
|
||||
work.Skeleton?.Complete();
|
||||
foreach (DecodeJob job in work.Pages ?? [])
|
||||
{
|
||||
job.Complete();
|
||||
}
|
||||
PreparedWork.Add(prepared, work);
|
||||
return prepared;
|
||||
}, true, CancellationToken.None);
|
||||
}
|
||||
|
||||
private static LazyWork StartLazy(object preload)
|
||||
{
|
||||
object modfile = Api.PreloadModfile(preload);
|
||||
string folder = modfile == null ? null : Api.ModfileFolder(modfile);
|
||||
if (string.IsNullOrEmpty(folder))
|
||||
{
|
||||
throw new ModLoadException(Api.PreloadName(preload) + " <color=#FF4C4C>(Unknown Error)</color>");
|
||||
}
|
||||
var work = new LazyWork { Preload = preload, Name = Api.PreloadName(preload), Folder = folder, Started = Stopwatch.GetTimestamp() };
|
||||
if (Api.PreloadSkeleton(preload) == null && DeferredSkeletons.TryGetValue(preload, out DeferredSkeleton skeleton))
|
||||
{
|
||||
work.SkeletonSource = skeleton;
|
||||
work.Skeleton = new DecodeJob(SkeletonResult.Work(skeleton.Path, skeleton.Json, null, 0));
|
||||
DecodeScheduler.Enqueue(work.Skeleton, true);
|
||||
}
|
||||
string atlas = Api.PreloadAtlasFile(preload);
|
||||
if (atlas != null)
|
||||
{
|
||||
work.AtlasText = File.ReadAllText(atlas);
|
||||
work.Paths = Api.PreloadAtlasTextures(preload);
|
||||
work.Pages = StartPages(work.Paths, false);
|
||||
}
|
||||
return work;
|
||||
}
|
||||
|
||||
private static object Finish(LazyWork work, bool nullWhenEmpty)
|
||||
{
|
||||
if (Api.SpineShader == null)
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(work.Folder) + " <color=#FF4C4C>(Couldn't initialize Shader)</color>");
|
||||
}
|
||||
long mainStarted = Stopwatch.GetTimestamp();
|
||||
TextAsset skeleton = Api.PreloadSkeleton(work.Preload);
|
||||
if (skeleton == null && work.Skeleton != null)
|
||||
{
|
||||
DeferredSkeleton source = work.SkeletonSource;
|
||||
var read = (SkeletonResult)work.Skeleton.Wait();
|
||||
string name = Path.GetFileName(source.Path);
|
||||
skeleton = source.Json
|
||||
? new TextAsset(read?.Text ?? File.ReadAllText(source.Path)) { name = name }
|
||||
: BinarySkeleton(work.Folder, source.Path, read?.Bytes);
|
||||
Api.SetPreloadSkeleton(work.Preload, skeleton);
|
||||
}
|
||||
SpineAtlasAsset atlas = null;
|
||||
var textures = new List<Texture2D>();
|
||||
if (work.AtlasText != null)
|
||||
{
|
||||
string[] names = work.Paths.Select(Path.GetFileNameWithoutExtension).ToArray();
|
||||
atlas = ModAssets.BuildAtlas(Api, work.Folder, work.AtlasText, names, work.Pages, work.Paths, false, false, textures);
|
||||
}
|
||||
if (nullWhenEmpty && skeleton == null && atlas == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
object data = Api.NewModData(skeleton, atlas);
|
||||
if (textures.Count > 0)
|
||||
{
|
||||
SceneCache.Add(work.Preload, data, textures);
|
||||
}
|
||||
long finished = Stopwatch.GetTimestamp();
|
||||
Plugin.Log.LogInfo(FormattableString.Invariant(
|
||||
$"On-demand load {work.Name}: {textures.Count} pages in {LoadStats.Milliseconds(finished - work.Started)} ms, main thread {LoadStats.Milliseconds(finished - mainStarted)} ms"));
|
||||
return data;
|
||||
}
|
||||
|
||||
private static DecodeJob[] StartPages(string[] paths, bool mipmaps)
|
||||
{
|
||||
DecodeJob[] jobs = paths.Select(path => new DecodeJob(PageResult.Work(path, mipmaps, null, 0))).ToArray();
|
||||
foreach (DecodeJob job in jobs.Skip(1))
|
||||
{
|
||||
DecodeScheduler.Enqueue(job, true);
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
private static TextAsset BinarySkeleton(string folder, string path, byte[] prefetched)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ModAssets.SkeletonFromBytes(prefetched ?? File.ReadAllBytes(path), Path.GetFileName(path));
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
throw new ModLoadException(Api.ShortPath(folder) + " <color=#FF4C4C>" + error.Message + "</color>", error);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class DeferredSkeleton(string path, bool json)
|
||||
{
|
||||
internal string Path { get; } = path;
|
||||
internal bool Json { get; } = json;
|
||||
}
|
||||
|
||||
private sealed class LazyWork
|
||||
{
|
||||
internal object Preload { get; set; }
|
||||
internal object Cached { get; set; }
|
||||
internal string Name { get; set; }
|
||||
internal string Folder { get; set; }
|
||||
internal long Started { get; set; }
|
||||
internal DeferredSkeleton SkeletonSource { get; set; }
|
||||
internal DecodeJob Skeleton { get; set; }
|
||||
internal string AtlasText { get; set; }
|
||||
internal string[] Paths { get; set; }
|
||||
internal DecodeJob[] Pages { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using BepInEx;
|
||||
using BepInEx.Logging;
|
||||
using HarmonyLib;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
[BepInPlugin(PluginId, Name, Version)]
|
||||
[BepInDependency(BrownDustXApi.PluginId, BepInDependency.DependencyFlags.SoftDependency)]
|
||||
public sealed class Plugin : BaseUnityPlugin
|
||||
{
|
||||
public const string PluginId = "bd2.browndustx.accel";
|
||||
public const string Name = "BD2 BrownDustX Accel";
|
||||
public const string Version = "0.1.0";
|
||||
internal static ManualLogSource Log;
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0051", Justification = "Unity invokes this instance lifecycle callback.")]
|
||||
private void Awake()
|
||||
{
|
||||
Log = Logger;
|
||||
AccelSettings.Bind(Config);
|
||||
System.Reflection.Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == BrownDustXApi.AssemblyName);
|
||||
if (assembly == null)
|
||||
{
|
||||
Logger.LogInfo("BrownDustX is not loaded; character mod acceleration is idle");
|
||||
return;
|
||||
}
|
||||
// Harmony.Dispose removes its patches; these hooks live until process exit.
|
||||
#pragma warning disable CA2000
|
||||
var harmony = new Harmony(PluginId);
|
||||
#pragma warning restore CA2000
|
||||
try
|
||||
{
|
||||
var api = BrownDustXApi.Bind(assembly);
|
||||
ModLoadPatches.Install(harmony, api);
|
||||
Logger.LogInfo(AccelSettings.Enabled
|
||||
? FormattableString.Invariant($"Attached to BrownDustX {assembly.GetName().Version}: character mod acceleration on, {DecodeScheduler.WorkerCount} decode threads")
|
||||
: FormattableString.Invariant($"Attached to BrownDustX {assembly.GetName().Version}: acceleration off, timing only"));
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
harmony.UnpatchSelf();
|
||||
Logger.LogError("BrownDustX acceleration disabled, original loading kept: " + error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Threading;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
/// <summary>RGBA32 pixels laid out the way Texture2D expects: bottom row first, mip levels back to back.</summary>
|
||||
internal sealed class DecodedImage(int width, int height, int mipCount, byte[] pixels, int length)
|
||||
{
|
||||
internal int Width { get; } = width;
|
||||
internal int Height { get; } = height;
|
||||
internal int MipCount { get; } = mipCount;
|
||||
internal byte[] Pixels { get; } = pixels;
|
||||
internal int Length { get; } = length;
|
||||
|
||||
internal int MipOffset(int level) => MipOffset(Width, Height, level);
|
||||
|
||||
internal static int MipOffset(int width, int height, int level)
|
||||
{
|
||||
int offset = 0;
|
||||
for (int i = 0; i < level; i++)
|
||||
{
|
||||
offset += MipWidth(width, i) * MipWidth(height, i) * 4;
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
|
||||
internal static int MipWidth(int size, int level) => Math.Max(1, size >> level);
|
||||
}
|
||||
|
||||
/// <summary>Pooled scratch buffers; the pool is replaced after each load burst so idle memory is returned to the GC.</summary>
|
||||
internal static class BufferPool
|
||||
{
|
||||
private const int MaxPooledLength = 1 << 28;
|
||||
private static ArrayPool<byte> pool = Create();
|
||||
|
||||
internal static byte[] Rent(int length) => length > MaxPooledLength ? new byte[length] : Volatile.Read(ref pool).Rent(length);
|
||||
|
||||
internal static void Return(byte[] buffer)
|
||||
{
|
||||
if (buffer != null && buffer.Length <= MaxPooledLength)
|
||||
{
|
||||
Volatile.Read(ref pool).Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Trim() => Volatile.Write(ref pool, Create());
|
||||
|
||||
private static ArrayPool<byte> Create() => ArrayPool<byte>.Create(MaxPooledLength, DecodeScheduler.WorkerCount + 2);
|
||||
}
|
||||
|
||||
/// <summary>Thread-safe PNG decoder for the formats Spine exports; anything else is left to ImageConversion.LoadImage.</summary>
|
||||
internal static unsafe class PngDecoder
|
||||
{
|
||||
private const uint ChunkIhdr = 0x49484452;
|
||||
private const uint ChunkPlte = 0x504C5445;
|
||||
private const uint ChunkTrns = 0x74524E53;
|
||||
private const uint ChunkIdat = 0x49444154;
|
||||
private const uint ChunkIend = 0x49454E44;
|
||||
private static readonly byte[] Signature = [137, 80, 78, 71, 13, 10, 26, 10];
|
||||
private static volatile bool unavailable;
|
||||
|
||||
/// <summary>Bytes the decoded image will occupy, read from IHDR; falls back to the file size when the header is unusable.</summary>
|
||||
internal static long EstimateBytes(byte[] file, int length, bool mipmaps)
|
||||
{
|
||||
if (length < 33 || !HasSignature(file) || ReadUInt(file, 12) != ChunkIhdr)
|
||||
{
|
||||
return length;
|
||||
}
|
||||
long pixels = (long)ReadUInt(file, 16) * ReadUInt(file, 20) * 4;
|
||||
return mipmaps ? pixels * 4 / 3 : pixels;
|
||||
}
|
||||
|
||||
internal static bool TryDecode(byte[] file, int length, bool mipmaps, out DecodedImage image)
|
||||
{
|
||||
image = null;
|
||||
if (unavailable || length < 33 || !HasSignature(file))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
byte[] pixels = null;
|
||||
try
|
||||
{
|
||||
image = Decode(file, length, mipmaps, out pixels);
|
||||
return image != null;
|
||||
}
|
||||
catch (Exception error) when (error is DllNotFoundException or EntryPointNotFoundException or TypeInitializationException)
|
||||
{
|
||||
unavailable = true;
|
||||
Plugin.Log.LogWarning("PNG decoder unavailable, using Unity decoding: " + error.Message);
|
||||
}
|
||||
catch (Exception error) when (error is not OutOfMemoryException and not ThreadAbortException)
|
||||
{
|
||||
// Corrupt or unusual data: ImageConversion.LoadImage handles it exactly as BrownDustX would.
|
||||
}
|
||||
BufferPool.Return(pixels);
|
||||
image = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static DecodedImage Decode(byte[] file, int length, bool mipmaps, out byte[] pixels)
|
||||
{
|
||||
pixels = null;
|
||||
int width = 0, height = 0, bitDepth = 0, colorType = 0, interlace = 0;
|
||||
byte[] palette = null;
|
||||
byte[] paletteAlpha = null;
|
||||
bool colorKey = false;
|
||||
var idat = new List<(int Offset, int Length)>();
|
||||
int position = 8;
|
||||
while (position + 8 <= length)
|
||||
{
|
||||
int chunkLength = (int)ReadUInt(file, position);
|
||||
uint type = ReadUInt(file, position + 4);
|
||||
int body = position + 8;
|
||||
if (chunkLength < 0 || body + chunkLength > length)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
switch (type)
|
||||
{
|
||||
case ChunkIhdr:
|
||||
width = (int)ReadUInt(file, body);
|
||||
height = (int)ReadUInt(file, body + 4);
|
||||
bitDepth = file[body + 8];
|
||||
colorType = file[body + 9];
|
||||
if (file[body + 10] != 0 || file[body + 11] != 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
interlace = file[body + 12];
|
||||
break;
|
||||
case ChunkPlte:
|
||||
palette = new byte[chunkLength];
|
||||
Buffer.BlockCopy(file, body, palette, 0, chunkLength);
|
||||
break;
|
||||
case ChunkTrns:
|
||||
if (colorType == 3)
|
||||
{
|
||||
paletteAlpha = new byte[chunkLength];
|
||||
Buffer.BlockCopy(file, body, paletteAlpha, 0, chunkLength);
|
||||
}
|
||||
else
|
||||
{
|
||||
colorKey = true;
|
||||
}
|
||||
break;
|
||||
case ChunkIdat:
|
||||
idat.Add((body, chunkLength));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (type == ChunkIend)
|
||||
{
|
||||
break;
|
||||
}
|
||||
position = body + chunkLength + 4;
|
||||
}
|
||||
int channels = colorType switch { 0 => 1, 2 => 3, 3 => 1, 4 => 2, 6 => 4, _ => 0 };
|
||||
bool supportedDepth = colorType == 3 ? bitDepth is 1 or 2 or 4 or 8 : bitDepth == 8;
|
||||
if (width <= 0 || height <= 0 || interlace != 0 || idat.Count == 0 || channels == 0 || !supportedDepth || colorKey
|
||||
|| (colorType == 3 && palette == null) || width > 16384 || height > 16384)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
int mipCount = mipmaps ? MipCount(width, height) : 1;
|
||||
long total = 0;
|
||||
for (int level = 0; level < mipCount; level++)
|
||||
{
|
||||
total += (long)DecodedImage.MipWidth(width, level) * DecodedImage.MipWidth(height, level) * 4;
|
||||
}
|
||||
if (total > int.MaxValue)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
int bitsPerPixel = channels * bitDepth;
|
||||
int filterStride = Math.Max(1, bitsPerPixel / 8);
|
||||
int rowBytes = (int)(((long)width * bitsPerPixel + 7) / 8);
|
||||
pixels = BufferPool.Rent((int)total);
|
||||
byte[] current = BufferPool.Rent(rowBytes);
|
||||
byte[] previous = BufferPool.Rent(rowBytes);
|
||||
try
|
||||
{
|
||||
Array.Clear(previous, 0, rowBytes);
|
||||
using var inflater = new DeflateStream(new IdatStream(file, idat), CompressionMode.Decompress);
|
||||
byte[] filter = new byte[1];
|
||||
int destinationStride = width * 4;
|
||||
fixed (byte* output = pixels)
|
||||
{
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
ReadExactly(inflater, filter, 1);
|
||||
ReadExactly(inflater, current, rowBytes);
|
||||
fixed (byte* cur = current, prev = previous)
|
||||
{
|
||||
Unfilter(cur, prev, rowBytes, filterStride, filter[0]);
|
||||
byte* row = output + (long)(height - 1 - y) * destinationStride;
|
||||
ConvertRow(cur, row, width, colorType, bitDepth, palette, paletteAlpha);
|
||||
}
|
||||
(current, previous) = (previous, current);
|
||||
}
|
||||
for (int level = 1; level < mipCount; level++)
|
||||
{
|
||||
int sourceWidth = DecodedImage.MipWidth(width, level - 1), sourceHeight = DecodedImage.MipWidth(height, level - 1);
|
||||
Downsample(output + DecodedImage.MipOffset(width, height, level - 1), sourceWidth, sourceHeight,
|
||||
output + DecodedImage.MipOffset(width, height, level), DecodedImage.MipWidth(width, level), DecodedImage.MipWidth(height, level));
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
BufferPool.Return(current);
|
||||
BufferPool.Return(previous);
|
||||
}
|
||||
return new DecodedImage(width, height, mipCount, pixels, (int)total);
|
||||
}
|
||||
|
||||
/// <summary>Matches Unity's full mip chain length for a texture of this size.</summary>
|
||||
internal static int MipCount(int width, int height)
|
||||
{
|
||||
int count = 1;
|
||||
for (int size = Math.Max(width, height); size > 1; size >>= 1)
|
||||
{
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void Unfilter(byte* cur, byte* prev, int length, int stride, int filter)
|
||||
{
|
||||
switch (filter)
|
||||
{
|
||||
case 0:
|
||||
return;
|
||||
case 1:
|
||||
for (int i = stride; i < length; i++)
|
||||
{
|
||||
cur[i] = (byte)(cur[i] + cur[i - stride]);
|
||||
}
|
||||
return;
|
||||
case 2:
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
cur[i] = (byte)(cur[i] + prev[i]);
|
||||
}
|
||||
return;
|
||||
case 3:
|
||||
for (int i = 0; i < stride; i++)
|
||||
{
|
||||
cur[i] = (byte)(cur[i] + (prev[i] >> 1));
|
||||
}
|
||||
for (int i = stride; i < length; i++)
|
||||
{
|
||||
cur[i] = (byte)(cur[i] + ((cur[i - stride] + prev[i]) >> 1));
|
||||
}
|
||||
return;
|
||||
case 4:
|
||||
for (int i = 0; i < stride; i++)
|
||||
{
|
||||
cur[i] = (byte)(cur[i] + prev[i]);
|
||||
}
|
||||
for (int i = stride; i < length; i++)
|
||||
{
|
||||
int a = cur[i - stride], b = prev[i], c = prev[i - stride];
|
||||
int p = b - c, q = a - c;
|
||||
int pa = p < 0 ? -p : p, pb = q < 0 ? -q : q, pc = p + q < 0 ? -(p + q) : p + q;
|
||||
cur[i] = (byte)(cur[i] + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c));
|
||||
}
|
||||
return;
|
||||
default:
|
||||
throw new InvalidDataException("Unknown PNG filter");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConvertRow(byte* source, byte* destination, int width, int colorType, int bitDepth, byte[] palette, byte[] paletteAlpha)
|
||||
{
|
||||
switch (colorType)
|
||||
{
|
||||
case 6:
|
||||
Buffer.MemoryCopy(source, destination, width * 4L, width * 4L);
|
||||
return;
|
||||
case 2:
|
||||
for (int x = 0; x < width; x++, source += 3, destination += 4)
|
||||
{
|
||||
destination[0] = source[0];
|
||||
destination[1] = source[1];
|
||||
destination[2] = source[2];
|
||||
destination[3] = 255;
|
||||
}
|
||||
return;
|
||||
case 4:
|
||||
for (int x = 0; x < width; x++, source += 2, destination += 4)
|
||||
{
|
||||
destination[0] = destination[1] = destination[2] = source[0];
|
||||
destination[3] = source[1];
|
||||
}
|
||||
return;
|
||||
case 0:
|
||||
for (int x = 0; x < width; x++, destination += 4)
|
||||
{
|
||||
destination[0] = destination[1] = destination[2] = source[x];
|
||||
destination[3] = 255;
|
||||
}
|
||||
return;
|
||||
default:
|
||||
int perByte = 8 / bitDepth, mask = (1 << bitDepth) - 1, colors = palette.Length / 3;
|
||||
for (int x = 0; x < width; x++, destination += 4)
|
||||
{
|
||||
int index = bitDepth == 8 ? source[x] : (source[x / perByte] >> ((perByte - 1 - (x % perByte)) * bitDepth)) & mask;
|
||||
if (index >= colors)
|
||||
{
|
||||
throw new InvalidDataException("PNG palette index out of range");
|
||||
}
|
||||
destination[0] = palette[index * 3];
|
||||
destination[1] = palette[(index * 3) + 1];
|
||||
destination[2] = palette[(index * 3) + 2];
|
||||
destination[3] = paletteAlpha != null && index < paletteAlpha.Length ? paletteAlpha[index] : (byte)255;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Downsample(byte* source, int sourceWidth, int sourceHeight, byte* destination, int width, int height)
|
||||
{
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
byte* row0 = source + ((long)Math.Min(2 * y, sourceHeight - 1) * sourceWidth * 4);
|
||||
byte* row1 = source + ((long)Math.Min((2 * y) + 1, sourceHeight - 1) * sourceWidth * 4);
|
||||
for (int x = 0; x < width; x++, destination += 4)
|
||||
{
|
||||
int x0 = Math.Min(2 * x, sourceWidth - 1) * 4, x1 = Math.Min((2 * x) + 1, sourceWidth - 1) * 4;
|
||||
for (int c = 0; c < 4; c++)
|
||||
{
|
||||
destination[c] = (byte)((row0[x0 + c] + row0[x1 + c] + row1[x0 + c] + row1[x1 + c] + 2) >> 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReadExactly(DeflateStream stream, byte[] buffer, int count)
|
||||
{
|
||||
for (int read = 0; read < count;)
|
||||
{
|
||||
int n = stream.Read(buffer, read, count - read);
|
||||
if (n <= 0)
|
||||
{
|
||||
throw new EndOfStreamException();
|
||||
}
|
||||
read += n;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HasSignature(byte[] file)
|
||||
{
|
||||
for (int i = 0; i < Signature.Length; i++)
|
||||
{
|
||||
if (file[i] != Signature[i])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static uint ReadUInt(byte[] data, int offset) =>
|
||||
((uint)data[offset] << 24) | ((uint)data[offset + 1] << 16) | ((uint)data[offset + 2] << 8) | data[offset + 3];
|
||||
|
||||
/// <summary>Concatenated IDAT payload without the two-byte zlib header, fed to DeflateStream.</summary>
|
||||
private sealed class IdatStream : Stream
|
||||
{
|
||||
private readonly byte[] file;
|
||||
private readonly List<(int Offset, int Length)> segments;
|
||||
private int segment;
|
||||
private int offset;
|
||||
|
||||
internal IdatStream(byte[] file, List<(int Offset, int Length)> segments)
|
||||
{
|
||||
this.file = file;
|
||||
this.segments = segments;
|
||||
(int start, int length) = segments[0];
|
||||
if (length < 2 || (file[start] & 0x0F) != 8 || (file[start + 1] & 0x20) != 0 || ((file[start] << 8) | file[start + 1]) % 31 != 0)
|
||||
{
|
||||
throw new InvalidDataException("Unsupported zlib header");
|
||||
}
|
||||
offset = 2;
|
||||
}
|
||||
|
||||
public override bool CanRead => true;
|
||||
public override bool CanSeek => false;
|
||||
public override bool CanWrite => false;
|
||||
public override long Length => throw new NotSupportedException();
|
||||
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||
|
||||
public override int Read(byte[] buffer, int bufferOffset, int count)
|
||||
{
|
||||
int written = 0;
|
||||
while (written < count && segment < segments.Count)
|
||||
{
|
||||
(int start, int length) = segments[segment];
|
||||
int available = length - offset;
|
||||
if (available <= 0)
|
||||
{
|
||||
segment++;
|
||||
offset = 0;
|
||||
continue;
|
||||
}
|
||||
int n = Math.Min(available, count - written);
|
||||
Buffer.BlockCopy(file, start + offset, buffer, bufferOffset + written, n);
|
||||
offset += n;
|
||||
written += n;
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
/// <summary>
|
||||
/// Walks the mods folder in the same order as BrownDustX's CheckModFolders and queues every character mod's
|
||||
/// skeleton and atlas pages for background decoding, so the main thread only uploads finished textures.
|
||||
/// </summary>
|
||||
internal sealed class PreloadSession
|
||||
{
|
||||
private static readonly Regex SpecialType = new("\"type\"\\s*:\\s*\"special\"", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
private readonly ConcurrentDictionary<string, ModPrefetch> byFolder = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly List<ModPrefetch> ordered = [];
|
||||
private readonly PrefetchBudget budget = new(AccelSettings.PrefetchBudgetBytes);
|
||||
private volatile bool closed;
|
||||
private int releasedUpTo;
|
||||
|
||||
internal static PreloadSession Current { get; private set; }
|
||||
|
||||
internal static void Start(string root)
|
||||
{
|
||||
var session = new PreloadSession();
|
||||
Current = session;
|
||||
new Thread(() => session.Produce(root)) { IsBackground = true, Name = "BrownDustXAccel scan", Priority = ThreadPriority.BelowNormal }.Start();
|
||||
}
|
||||
|
||||
internal static void Stop()
|
||||
{
|
||||
PreloadSession session = Current;
|
||||
Current = null;
|
||||
if (session == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
session.closed = true;
|
||||
session.budget.Close();
|
||||
lock (session.ordered)
|
||||
{
|
||||
foreach (ModPrefetch mod in session.ordered)
|
||||
{
|
||||
mod.Cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Hands a mod's prefetched work to the consumer and drops skipped mods queued before it (conflicts, invalid mods).</summary>
|
||||
internal ModPrefetch Take(string folder)
|
||||
{
|
||||
if (folder == null || !byFolder.TryGetValue(folder, out ModPrefetch mod) || mod.Taken)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
mod.Taken = true;
|
||||
budget.Demand(mod.Sequence);
|
||||
lock (ordered)
|
||||
{
|
||||
for (; releasedUpTo < mod.Sequence; releasedUpTo++)
|
||||
{
|
||||
if (!ordered[releasedUpTo].Taken)
|
||||
{
|
||||
ordered[releasedUpTo].Cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
return mod;
|
||||
}
|
||||
|
||||
private void Produce(string root)
|
||||
{
|
||||
try
|
||||
{
|
||||
Walk(root, 0);
|
||||
}
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Plugin.Log.LogWarning("Character mod prefetch stopped: " + error.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void Walk(string folder, int depth)
|
||||
{
|
||||
if (closed || depth > 5)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (depth != 0)
|
||||
{
|
||||
var modfiles = Directory.EnumerateFiles(folder, "*.modfile")
|
||||
.Where(f => !string.Equals(Path.GetFileName(f), "intro.modfile", StringComparison.OrdinalIgnoreCase)).Take(2).ToList();
|
||||
if (modfiles.Count == 1)
|
||||
{
|
||||
Plan(folder, modfiles[0]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
foreach (string child in Directory.EnumerateDirectories(folder))
|
||||
{
|
||||
Walk(child, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs on the single producer thread, so sequence numbers follow the order mods are added.</summary>
|
||||
private void Plan(string folder, string modfile)
|
||||
{
|
||||
string name = Path.GetFileNameWithoutExtension(modfile);
|
||||
if (!ModNames.IsCharacter(name) || name.Contains("_atlas_", StringComparison.OrdinalIgnoreCase) || SpecialType.IsMatch(File.ReadAllText(modfile)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
var mod = new ModPrefetch { Folder = folder, Sequence = ordered.Count };
|
||||
string json = Directory.GetFiles(folder, "*.json").FirstOrDefault();
|
||||
string skeleton = json ?? Directory.GetFiles(folder, "*.skel").FirstOrDefault();
|
||||
if (skeleton != null)
|
||||
{
|
||||
mod.SkeletonPath = skeleton;
|
||||
mod.SkeletonJob = new DecodeJob(SkeletonResult.Work(skeleton, json != null, budget, mod.Sequence));
|
||||
}
|
||||
string atlas = Directory.GetFiles(folder, "*.atlas").FirstOrDefault();
|
||||
if (atlas != null)
|
||||
{
|
||||
mod.AtlasPath = atlas;
|
||||
mod.AtlasText = File.ReadAllText(atlas);
|
||||
mod.PageNames = AtlasPages.Parse(mod.AtlasText);
|
||||
mod.PageJobs = mod.PageNames
|
||||
.Select(page => new DecodeJob(PageResult.Work(Path.Combine(folder, page + ".png"), true, budget, mod.Sequence)))
|
||||
.ToArray();
|
||||
}
|
||||
lock (ordered)
|
||||
{
|
||||
if (closed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
ordered.Add(mod);
|
||||
}
|
||||
byFolder[folder] = mod;
|
||||
if (mod.SkeletonJob != null)
|
||||
{
|
||||
DecodeScheduler.Enqueue(mod.SkeletonJob, false);
|
||||
}
|
||||
foreach (DecodeJob job in mod.PageJobs ?? [])
|
||||
{
|
||||
DecodeScheduler.Enqueue(job, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class ModPrefetch
|
||||
{
|
||||
internal int Sequence { get; set; }
|
||||
internal string Folder { get; set; }
|
||||
internal bool Taken { get; set; }
|
||||
internal string SkeletonPath { get; set; }
|
||||
internal DecodeJob SkeletonJob { get; set; }
|
||||
internal string AtlasPath { get; set; }
|
||||
internal string AtlasText { get; set; }
|
||||
internal List<string> PageNames { get; set; }
|
||||
internal DecodeJob[] PageJobs { get; set; }
|
||||
|
||||
internal SkeletonResult TakeSkeleton(string path)
|
||||
{
|
||||
if (SkeletonJob == null || !string.Equals(SkeletonPath, path, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
var result = (SkeletonResult)SkeletonJob.Wait();
|
||||
result?.Release();
|
||||
return result;
|
||||
}
|
||||
|
||||
internal string TakeAtlasText(string path) =>
|
||||
string.Equals(AtlasPath, path, StringComparison.OrdinalIgnoreCase) ? AtlasText : null;
|
||||
|
||||
internal DecodeJob[] TakePageJobs(string path, List<string> pages) =>
|
||||
PageJobs != null && string.Equals(AtlasPath, path, StringComparison.OrdinalIgnoreCase) && PageNames.SequenceEqual(pages) ? PageJobs : null;
|
||||
|
||||
internal void Cancel()
|
||||
{
|
||||
SkeletonJob?.Cancel();
|
||||
foreach (DecodeJob job in PageJobs ?? [])
|
||||
{
|
||||
job.Cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
# BD2 BrownDustX Accel
|
||||
|
||||
给第三方插件 BrownDustX(`lynesth.bd2.browndustx` 2.36.7.1)加速角色模组加载的独立插件。BrownDustX 的原始文件不做任何修改,本插件在运行时用 Harmony 接管它加载角色 Spine 模组(名称以 `char`、`npc`、`cutscene`、`illust`、`specialillust`、`storypack` 开头)的几个函数。intro、volume、sprite-atlas 等其他模组仍由 BrownDustX 自己加载。
|
||||
|
||||
没装 BrownDustX 时插件什么也不做。如果绑定 BrownDustX 内部成员失败(例如 BrownDustX 版本更新导致签名变化),插件会撤销全部补丁,恢复原逻辑,并在日志里报错。
|
||||
|
||||
## 原版的瓶颈(以实际运行的 DLL 为准,SHA-256 `c3da43eb…2403301`)
|
||||
|
||||
| 位置 | 问题 |
|
||||
|---|---|
|
||||
| `ModManager.GetMods` → `CheckModFolders` → `AddModFolder` → `LoadModData(string, Modfile, List)` | “Preload all Mods = Yes”(内存 ≥ 12 GB 时的默认值)下,所有模组在**一个协程帧内、主线程上串行**加载:每张 atlas 页都要 `File.ReadAllBytes` + `ImageConversion.LoadImage`(单线程 PNG 解码并生成 mipmap),模组多达几 GB 时游戏会卡住很久 |
|
||||
| 同上,`Conf.ShouldCompressTextures` 为真时 | 每加载一个模组就 `yield BrownDustX.Cleanup()`:两次 `GC.Collect`、一次 `WaitForPendingFinalizers`,在 Splash 场景还会调用 `Resources.UnloadUnusedAssets()`,开销随模组数线性叠加;`ResizeToNearestMultipleOf4` 换出的原贴图也没有销毁 |
|
||||
| `ModManager.PrepareModForLoading` | “Preload = No”时,启动阶段会在主线程同步读取**所有**模组的 `.skel`/`.json`,并且一直留在内存里,包括从没显示过的模组 |
|
||||
| `SpineReplacer.PrepareRuntimeAsync` / `BuildModDataFromPrepared` | 后台线程只负责读取 PNG 字节,PNG 解码 `LoadImage` 仍在主线程逐页执行 |
|
||||
| `ModManager.LoadModData(PreloadModData)`(`SkeletonGraphic/SkeletonMecanim.Initialize` 前缀、Intro) | 读文件和解码全部在主线程上同步完成 |
|
||||
| `BrownDustX.OnSceneLoaded` | “Preload = No”时每次切场景都会清空 `LoadedModsData`,同一个角色再次出现时要从磁盘重新读取并解码 |
|
||||
|
||||
## 优化内容与预期效果
|
||||
|
||||
1. **多线程 PNG 解码,主线程只上传贴图**:自带 PNG 解码器,支持 8 位 RGBA/RGB/灰度/灰度+α,以及 1/2/4/8 位调色板(含 tRNS)。它在后台线程把文件解码成 Unity RGBA32 的原始布局(行序上下翻转,mip 链连续排列),主线程只调用 `SetPixelData` + `Apply` 上传。隔行扫描、16 位、色键 tRNS、损坏的文件会自动退回 `LoadImage`,结果与原版一致。用 Pillow 对比了 65 种格式和尺寸,解码结果(含 mip 链)逐字节一致。
|
||||
- 预期效果:每张页在主线程上的耗时从“解码 + 生成 mip”(4096² 通常 200–400 ms)降到一次内存拷贝加 GPU 上传(几十 ms),解码负载分摊到 `DecodeThreads` 个后台线程。
|
||||
2. **启动预取流水线**(Preload = Yes):`GetMods` 一开始就在后台线程按照与 `CheckModFolders` 完全相同的规则和顺序扫描模组目录。它利用原版固定等待的 1 秒,提前把各模组的 skel/json 和 atlas 页排进解码队列。主线程处理到某个模组时,直接取用已经解码好的数据。冲突或无效的模组排过之后会立即释放。已解码、未上传的数据总量受 `PrefetchBudgetMB` 限制,正在处理的模组永远不受这个限制,因此不会死锁。
|
||||
- 预期效果:启动总耗时从“所有页的解码时间之和”降到大约 max(磁盘读取, 解码时间 ÷ 线程数) + 上传时间。几 GB 模组、8 核 CPU 时,预计是原来的 1/3 到 1/6(取决于 CPU 核数和磁盘)。
|
||||
3. **加载期间不再卡死界面,并显示进度**:每处理一个模组目录时检查当前帧的耗时,超过 100 ms 就让出一帧,加载对话框能持续刷新,Windows 也不会提示“未响应”。BrownDustX 的“正在加载 Mod”对话框下方会多出两样东西:
|
||||
- 正在加载的模组目录(相对 `mods/` 的路径);
|
||||
- 一条进度条,标出“已加载 / 总数(百分比)”。总数在 `GetMods` 开始时由后台线程按 `CheckModFolders` 的相同规则统计。热重载(文件监听触发)时只处理改动过的目录,所以只显示已处理数量,进度条以循环动画表示还在加载。
|
||||
|
||||
每个模组加载完成后才会刷新一次画面,所以单个特别大的模组加载期间进度条会停在原处。关闭加速(`Enabled = false`)时不显示进度条,因为原版加载过程中不会刷新画面。
|
||||
4. **去掉逐模组 Cleanup**:扫描期间,压缩模式下每个模组后的 `Cleanup()`(GC ×2 + UnloadUnusedAssets)改为空操作,只保留扫描结束时那一次。缩放前的临时贴图会主动 `Destroy`。
|
||||
5. **按需模式(Preload = No)**:
|
||||
- 启动时只做文件校验(atlas、贴图是否存在,json/skel 命名是否合法),skel/json 推迟到模组第一次显示时再读。启动 IO 减少,未使用的模组也不再常驻内存。报错信息与原版一致。
|
||||
- `PrepareRuntimeAsync` 把所有页并行解码放在后台,`BuildModDataFromPrepared` 只负责上传。同步路径 `LoadModData(PreloadModData)` 由主线程和后台线程一起并行解码。
|
||||
- 场景 LRU 缓存(`SceneCacheMB`,默认 512 MB 贴图内存):切场景后再次出现的角色直接复用已经上传的贴图,耗时接近 0。缓存中的贴图如果已被 Unity 卸载会自动失效,监听到模组目录变化重载时会清空。
|
||||
6. **解码缓冲池**:文件读取缓冲和像素缓冲用 `ArrayPool` 复用,每轮加载结束后整体丢弃,避免几 GB 的大对象反复分配,给 Mono Boehm GC 带来压力。
|
||||
|
||||
## 配置
|
||||
|
||||
`BepInEx/config/bd2.browndustx.accel.cfg`,修改后需要重启游戏:
|
||||
|
||||
| 键 | 默认值 | 说明 |
|
||||
|---|---|---|
|
||||
| `General.Enabled` | `true` | `false` 时不加速,只输出耗时日志,用于对比 |
|
||||
| `Performance.DecodeThreads` | `0` | 0 表示 CPU 核数 − 1,最多 8 |
|
||||
| `Performance.PrefetchBudgetMB` | `1024` | 启动预取时,已解码但尚未上传的数据上限 |
|
||||
| `Performance.SceneCacheMB` | `512` | 按需模式下跨场景保留的贴图内存,0 表示关闭 |
|
||||
| `Logging.VerboseTiming` | `false` | 启动预加载时逐个模组输出耗时 |
|
||||
|
||||
## 在游戏里验证
|
||||
|
||||
1. 构建:`dotnet build plugins/BrownDustXAccel/BrownDustXAccel.csproj -c Release`,把 `bin/Release/netstandard2.1/BD2BrownDustXAccel.dll` 复制到游戏的 `BepInEx/plugins/` 下。
|
||||
2. 启动后,在 `BepInEx/LogOutput.log` 里查找 `BD2 BrownDustX Accel`:
|
||||
- `Attached to BrownDustX 2.36.7.1: character mod acceleration on, N decode threads`:补丁安装成功。
|
||||
- 模组加载完成后会输出一行,例如:
|
||||
`Mod scan (preload all, acceleration on) finished: folder scan 9840 ms, total 10870 ms; 182 character mods, 534 pages (11200 MB pixels, 534 prefetched, 0 Unity-decoded); main thread upload 2310 ms, waiting 4100 ms; decode CPU 61200 ms on 7 threads`
|
||||
- `folder scan` 是 BrownDustX 遍历并加载全部模组的耗时,`total` 还包括它固定的 1 秒等待和最后一次清理。
|
||||
- `waiting` 是主线程等待后台解码的时间,数值大说明瓶颈在解码线程或磁盘,可以调大 `DecodeThreads`。
|
||||
- `Unity-decoded` 是退回 `LoadImage` 解码的页数,正常应为 0。
|
||||
- 按需模式下,每次加载一个角色会输出:`On-demand load char000101: 4 pages in 180 ms, main thread 25 ms`。切场景后再次出现的同一角色走缓存,不会再出现这行日志。
|
||||
3. 对比原版:把 `General.Enabled` 设为 `false` 后重启,得到同一格式的 `Mod scan (…, acceleration off) finished: folder scan … ms, total … ms`,对比两次的 `folder scan` 即可。
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Bd2BrownDustXAccel;
|
||||
|
||||
/// <summary>
|
||||
/// LRU of on-demand character mods. BrownDustX drops its loaded mods on every scene change; keeping recent ones
|
||||
/// alive (up to a texture budget) turns a re-decode into a dictionary hit. Main thread only.
|
||||
/// </summary>
|
||||
internal static class SceneCache
|
||||
{
|
||||
private static readonly Dictionary<object, LinkedListNode<Entry>> Entries = new(ReferenceComparer.Instance);
|
||||
private static readonly LinkedList<Entry> Recent = new();
|
||||
private static long total;
|
||||
|
||||
internal static object TryGet(object preload)
|
||||
{
|
||||
if (!Entries.TryGetValue(preload, out LinkedListNode<Entry> node))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
foreach (Texture2D texture in node.Value.Textures)
|
||||
{
|
||||
if (texture == null)
|
||||
{
|
||||
Remove(node);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Recent.Remove(node);
|
||||
Recent.AddFirst(node);
|
||||
return node.Value.ModData;
|
||||
}
|
||||
|
||||
internal static void Add(object preload, object modData, List<Texture2D> textures)
|
||||
{
|
||||
long bytes = 0;
|
||||
foreach (Texture2D texture in textures)
|
||||
{
|
||||
bytes += ModAssets.TextureBytes(texture);
|
||||
}
|
||||
if (bytes > AccelSettings.SceneCacheBytes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (Entries.TryGetValue(preload, out LinkedListNode<Entry> existing))
|
||||
{
|
||||
Remove(existing);
|
||||
}
|
||||
LinkedListNode<Entry> node = Recent.AddFirst(new Entry(preload, modData, [.. textures], bytes));
|
||||
Entries[preload] = node;
|
||||
total += bytes;
|
||||
while (total > AccelSettings.SceneCacheBytes && Recent.Last != null)
|
||||
{
|
||||
Remove(Recent.Last);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Clear()
|
||||
{
|
||||
Entries.Clear();
|
||||
Recent.Clear();
|
||||
total = 0;
|
||||
}
|
||||
|
||||
private static void Remove(LinkedListNode<Entry> node)
|
||||
{
|
||||
Entries.Remove(node.Value.Preload);
|
||||
Recent.Remove(node);
|
||||
total -= node.Value.Bytes;
|
||||
}
|
||||
|
||||
private sealed class Entry(object preload, object modData, Texture2D[] textures, long bytes)
|
||||
{
|
||||
internal object Preload { get; } = preload;
|
||||
internal object ModData { get; } = modData;
|
||||
internal Texture2D[] Textures { get; } = textures;
|
||||
internal long Bytes { get; } = bytes;
|
||||
}
|
||||
|
||||
private sealed class ReferenceComparer : IEqualityComparer<object>
|
||||
{
|
||||
internal static readonly ReferenceComparer Instance = new();
|
||||
|
||||
public new bool Equals(object x, object y) => ReferenceEquals(x, y);
|
||||
|
||||
public int GetHashCode(object obj) => RuntimeHelpers.GetHashCode(obj);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
<Nullable>disable</Nullable>
|
||||
<AssemblyName>BD2CaptureEnvironment</AssemblyName>
|
||||
<RootNamespace>Bd2CaptureEnvironment</RootNamespace>
|
||||
<BD2UsesGameSdk>true</BD2UsesGameSdk>
|
||||
<BD2PluginVersionKey>capture_environment</BD2PluginVersionKey>
|
||||
<BD2GameVersion>2.36.7</BD2GameVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
<Nullable>disable</Nullable>
|
||||
<AssemblyName>BD2CashShop</AssemblyName>
|
||||
<RootNamespace>Bd2CashShop</RootNamespace>
|
||||
<BD2UsesGameSdk>true</BD2UsesGameSdk>
|
||||
<BD2PluginVersionKey>cash_shop</BD2PluginVersionKey>
|
||||
<BD2GameVersion>2.36.7</BD2GameVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
<Project DefaultTargets="Build">
|
||||
<ItemGroup>
|
||||
<ClientPlugin Include="LocalIdentity/LocalIdentity.csproj;LoginUI/LoginUI.csproj;CashShop/CashShop.csproj;FChat/FChat.csproj" />
|
||||
</ItemGroup>
|
||||
<Target Name="Restore">
|
||||
<MSBuild Projects="@(ClientPlugin)" Targets="Restore" BuildInParallel="true" />
|
||||
</Target>
|
||||
<Target Name="Build">
|
||||
<MSBuild Projects="@(ClientPlugin)" Targets="Build" BuildInParallel="true" />
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -1,9 +1,12 @@
|
||||
<Project>
|
||||
<Import Project="$(BD2PluginRegistryProps)" Condition="'$(BD2PluginRegistryProps)' != ''" />
|
||||
<!-- Framework/configuration/output paths are available only after the project. -->
|
||||
<PropertyGroup Condition="'$(BD2PluginVersionKey)' != ''">
|
||||
<PropertyGroup Condition="'$(BD2UsesGameSdk)' == 'true'">
|
||||
<BD2SdkDir Condition="'$(BD2SdkDir)' == ''">$([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)/$(IntermediateOutputPath)$(BD2SdkIntermediateFolder)'))</BD2SdkDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(BD2PluginVersionKey)' != ''">
|
||||
<BD2GeneratedVersionSource Condition="'$(BD2GeneratedVersionSource)' == ''">$([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)/$(IntermediateOutputPath)Bd2Versions.g.cs'))</BD2GeneratedVersionSource>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(BD2PluginsDir)VersionSource.targets" Condition="'$(BD2PluginVersionKey)' != ''" />
|
||||
<Import Project="$(BD2PluginsDir)GameSdk.targets" Condition="'$(BD2PluginVersionKey)' != ''" />
|
||||
<Import Project="$(BD2PluginsDir)GameSdk.targets" Condition="'$(BD2UsesGameSdk)' == 'true'" />
|
||||
</Project>
|
||||
@@ -5,6 +5,7 @@
|
||||
<Nullable>disable</Nullable>
|
||||
<AssemblyName>BD2FChat</AssemblyName>
|
||||
<RootNamespace>Bd2FChat</RootNamespace>
|
||||
<BD2UsesGameSdk>true</BD2UsesGameSdk>
|
||||
<BD2PluginVersionKey>fchat</BD2PluginVersionKey>
|
||||
<BD2GameVersion>2.36.7</BD2GameVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
<Nullable>disable</Nullable>
|
||||
<AssemblyName>BD2LocalIdentity</AssemblyName>
|
||||
<RootNamespace>Bd2LocalIdentity</RootNamespace>
|
||||
<BD2UsesGameSdk>true</BD2UsesGameSdk>
|
||||
<BD2PluginVersionKey>local_identity</BD2PluginVersionKey>
|
||||
<BD2GameVersion>2.36.7</BD2GameVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
<Nullable>disable</Nullable>
|
||||
<AssemblyName>BD2LoginUI</AssemblyName>
|
||||
<RootNamespace>Bd2LoginUI</RootNamespace>
|
||||
<BD2UsesGameSdk>true</BD2UsesGameSdk>
|
||||
<BD2PluginVersionKey>login_ui</BD2PluginVersionKey>
|
||||
<BD2GameVersion>2.36.7</BD2GameVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Reflection;
|
||||
using BD2.GameNames;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
using static Bd2LoginUI.LoginRuntime;
|
||||
using static Bd2LoginUI.SessionRecovery;
|
||||
|
||||
namespace Bd2LoginUI;
|
||||
|
||||
internal static class StoryBattleRecovery
|
||||
{
|
||||
private const BindingFlags InstanceFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
||||
private static readonly FieldInfo Replay = typeof(TimelineSignalManager).GetGameField("_isReplayTimeline", InstanceFlags);
|
||||
private static readonly FieldInfo PlayType = typeof(TimelineSignalManager).GetGameField("_timelinePlayType", InstanceFlags);
|
||||
private static readonly FieldInfo Monster = typeof(TimelineSignalManager).GetGameField("_battleMonsterId", InstanceFlags);
|
||||
private static readonly FieldInfo EndCallback = typeof(TimelineSignalManager).GetGameField("_callbackTimelineEnd", InstanceFlags);
|
||||
private static readonly FieldInfo Director = typeof(TimelineSignalManager).GetGameField("_playableDirector", InstanceFlags);
|
||||
private static readonly FieldInfo Balloon = typeof(TimelineSignalManager).GetGameField("_balloonUI", InstanceFlags);
|
||||
private static readonly FieldInfo Selection = typeof(TimelineSignalManager).GetGameField("_cinemaSelectUI", InstanceFlags);
|
||||
private static readonly FieldInfo Skip = typeof(TimelineSignalManager).GetGameField("_skipUI", InstanceFlags);
|
||||
private static readonly MethodInfo EndProcess = typeof(TimelineSignalManager).GetGameMethod("EndTimelineProcess", InstanceFlags);
|
||||
private static readonly MethodInfo CheckEntry = typeof(GameFieldManager).GetGameMethod("CheckEnterPackQuest", InstanceFlags);
|
||||
private static TimelineSignalManager Recovering;
|
||||
private static bool ReturningToInn;
|
||||
|
||||
internal static void Install(Harmony harmony)
|
||||
{
|
||||
if (Replay == null || PlayType == null || Monster == null || EndCallback == null || Director == null || Balloon == null ||
|
||||
Selection == null || Skip == null || EndProcess == null || CheckEntry == null)
|
||||
throw new MissingMemberException("Story battle recovery members are unavailable");
|
||||
harmony.Patch(Game.Method<TimelineSignalManager>(signal => signal.EndTimeline()),
|
||||
prefix: new HarmonyMethod(typeof(StoryBattleRecovery), nameof(BeforeEnd)) { priority = Priority.First });
|
||||
harmony.Patch(CheckEntry,
|
||||
prefix: new HarmonyMethod(typeof(StoryBattleRecovery), nameof(BeforeEntry)) { priority = Priority.First });
|
||||
harmony.Patch(typeof(AppManager).GetGameMethod("AppReStart", InstanceFlags, null, Type.EmptyTypes, null),
|
||||
prefix: new HarmonyMethod(typeof(StoryBattleRecovery), nameof(Reset)));
|
||||
}
|
||||
|
||||
private static void Reset()
|
||||
{
|
||||
Recovering = null;
|
||||
ReturningToInn = false;
|
||||
}
|
||||
|
||||
private static bool BeforeEntry() => !ReturningToInn;
|
||||
|
||||
private static bool BeforeEnd(TimelineSignalManager __instance)
|
||||
{
|
||||
if (ReferenceEquals(Recovering, __instance)) return false;
|
||||
if (ServerRoot == null || !EstablishedGameSession || __instance.IsEndTimeline ||
|
||||
(bool)Replay.GetValue(__instance) || (ETimelinePlayType)PlayType.GetValue(__instance) != ETimelinePlayType.Quest ||
|
||||
!BDNetwork.CommonPacket.IsAllDeadCharactersInDeck)
|
||||
return true;
|
||||
if (__instance.MapMoveData != null && !string.IsNullOrEmpty(__instance.MapMoveData.sceneName)) return true;
|
||||
PackManager pack = FindUnitySingleton<PackManager>();
|
||||
if (pack == null || pack.EnterPackDTO == null ||
|
||||
pack.EnterPackDTO.PackType != (int)Proto.Net.Define_PackType.PackStory &&
|
||||
pack.EnterPackDTO.PackType != (int)Proto.Net.Define_PackType.PackTutorial)
|
||||
return true;
|
||||
GameFieldManager field = FindUnitySingleton<GameFieldManager>();
|
||||
if (field == null || field.GetFieldMonsterObject((int)Monster.GetValue(__instance)) == null) return true;
|
||||
Recovering = __instance;
|
||||
StartStoryCoroutine(Recover(__instance, field));
|
||||
return false;
|
||||
}
|
||||
|
||||
private static IEnumerator Recover(TimelineSignalManager timeline, GameFieldManager field)
|
||||
{
|
||||
Log?.LogInfo("Story battle waiting for exhausted combat party recovery");
|
||||
bool received = false;
|
||||
BDNetwork.CommonPacket.SendDeckCharAutoReviveRequest(BDNetwork.CommonPacket.UserInfo.AutoReviveCastingCharInvenIndex,
|
||||
_ => received = true);
|
||||
float deadline = Time.realtimeSinceStartup + 45f;
|
||||
while (!received && ReferenceEquals(Recovering, timeline) && !ApplicationQuitting && timeline != null)
|
||||
{
|
||||
if (Time.realtimeSinceStartup >= deadline)
|
||||
{
|
||||
Recovering = null;
|
||||
ShowStoryFailure("combat party recovery was not acknowledged within 45 seconds");
|
||||
yield break;
|
||||
}
|
||||
yield return null;
|
||||
}
|
||||
if (!ReferenceEquals(Recovering, timeline) || ApplicationQuitting || timeline == null || field == null) yield break;
|
||||
if (!BDNetwork.CommonPacket.IsAllDeadCharactersInDeck)
|
||||
{
|
||||
Recovering = null;
|
||||
timeline.EndTimeline();
|
||||
yield break;
|
||||
}
|
||||
|
||||
Log?.LogInfo("Story battle deferred until native inn recovery completes");
|
||||
ReturningToInn = true;
|
||||
StoryCheckpoint.ResetSession();
|
||||
// Abandon this presentation without acknowledging its persisted checkpoint.
|
||||
EndCallback.SetValue(timeline, null);
|
||||
timeline.OnClickAutoTimeline(false, EStoryAutoState.auto);
|
||||
((TimelineBalloonUI)Balloon.GetValue(timeline))?.SetActive(false);
|
||||
((CinemaSelectUI)Selection.GetValue(timeline))?.SetActive(false);
|
||||
((StorySkipUI)Skip.GetValue(timeline))?.SetActive(false);
|
||||
object director = Director.GetValue(timeline);
|
||||
director?.GetType().GetMethod("Pause", Type.EmptyTypes)?.Invoke(director, null);
|
||||
yield return (IEnumerator)EndProcess.Invoke(timeline, null);
|
||||
if (!ReferenceEquals(Recovering, timeline) || ApplicationQuitting || field == null) yield break;
|
||||
yield return field.MoveMotelByFieldAllDied();
|
||||
if (!ReferenceEquals(Recovering, timeline) || ApplicationQuitting) yield break;
|
||||
ReturningToInn = false;
|
||||
Recovering = null;
|
||||
if (field != null && EstablishedGameSession && !BDNetwork.CommonPacket.IsAllDeadCharactersInDeck)
|
||||
CheckEntry.Invoke(field, null);
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,7 @@ internal static class StoryCheckpoint
|
||||
postfix: new HarmonyMethod(typeof(StoryCheckpoint), nameof(InitializeTimelinePostfix)));
|
||||
harmony.Patch(typeof(AppManager).GetGameMethod("AppReStart", InstanceFlags, null, Type.EmptyTypes, null),
|
||||
prefix: new HarmonyMethod(typeof(StoryCheckpoint), nameof(ResetSession)));
|
||||
StoryBattleRecovery.Install(harmony);
|
||||
}
|
||||
|
||||
internal static void ResetSession()
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"game_version": "2.36.7",
|
||||
"client_version": "2.36.7+client.0.2.3",
|
||||
"client_version": "2.36.7+client.0.2.4",
|
||||
"server_version": "2.36.7+server.0.2.0",
|
||||
"game_data_version": "20261012190548",
|
||||
"bundle_version": "20261007175947",
|
||||
|
||||
Reference in new issue
Block a user