Compare commits

...
37 Commits
Author SHA1 Message Date
armonica f50976a6c0 最適化: ラベル表示状態のキャッシュ永続化および実在検証の超高速化
- UnifiedGameCacheEntryにIsModded等のラベル状態を保持し、起動直後の0秒時点から全ラベルを即時表示
- フォルダ更新日時(LastWriteTime)比較により、不変ゲームの重いディスクI/O検証を完全スキップ
- 実在検証完了後に一覧およびステータスラベルの最新描画リフレッシュを追加
2026-10-20 15:11:37 +09:00
armonica b0fdea2411 最適化: NTFS MFT走査およびディスク読み取りの並列化と限界高速化
- 複数ドライブ(C:, Z:等)のMFTスキャンを完全並列実行するように改善
- MFTのI/Oバッファを2MBに拡張しシステムコールを削減
- ターゲット外ファイルの無駄な文字列化・オブジェクト生成を完全スキップする2パス抽出アルゴリズムを導入
- 既存ゲーム実在検証処理(VerifyAndEnrichGamesAsync)をParallel.ForEachで並列化
- 新規フォルダ走査の並列度引き上げと複数ドライブ同時走査に対応
2026-10-20 15:02:14 +09:00
armonica dd00c96e20 機能改善: 高速スキャン連携とインメモリプレフィルタによるゲーム検出処理の統合
Everything -> NTFS MFT -> 通常走査の順でフォールバックするパイプラインを構築し、インメモリプレフィルタにより無関係なフォルダのディスクI/Oを排除してゲーム検出を劇的に高速化しました。UIログにも適用エンジンを表示します。
2026-10-20 11:30:13 +09:00
armonica 4c94cf814f 機能追加: NTFS MFT (USN Journal) 直接読み取りによる高速ファイル走査サービスを追加
低レベルボリュームハンドルから FSCTL_ENUM_USN_DATA を呼び出し、ドライブ全体の MFT/USN レコードを直接メモリへ読み出して対象フォルダ配下のインデックスを秒速生成する NtfsMftScanService を実装しました。
2026-10-20 11:30:07 +09:00
armonica 2c02e10dd1 機能追加: Everything IPC を利用した超高速フォルダ走査サービスを追加
Everything が起動しているかを判定し、WM_COPYDATA 通信によって指定フォルダ配下の全ファイル・サブディレクトリを一括取得する EverythingSearchService を実装しました。
2026-10-20 11:29:58 +09:00
armonica b65122537d 機能追加: メモリ上でのディレクトリ・ファイル高速判定用スナップショットクラスを追加
Everything や NTFS MFT から取得したファイルツリーをインメモリで保持し、ディスクI/Oを行わずにファイル存在確認や一覧取得を可能にする FastDirectorySnapshot クラスを実装しました。
2026-10-20 11:29:53 +09:00
armonica ee9eeb3118 設定: アプリ起動時に常に管理者権限を要求するマニフェストを追加
app.manifest を新規作成して requestedExecutionLevel に requireAdministrator を指定し、GameLauncher.csproj にマニフェストを組み込みました。
2026-10-20 11:29:47 +09:00
armonica dc03f5284a feat(scanner): 起動時フリーズ解消(完全非同期化)とステータスバー最下部プログレスバー連携 2026-10-20 10:56:42 +09:00
armonica 6447fc2635 feat(perf): サムネイルキャッシュの即時ロードおよびデコード負荷極小化の実装 2026-10-20 10:55:34 +09:00
armonica ec4d718311 feat(ui): 右側詳細パネルのシンプル化とスクリプト改造不可時の項目非表示化 2026-10-20 10:54:53 +09:00
armonica c03cc97af1 feat(ui): ゲーム一覧の仮想スクロール最適化(Recycling・Pixel単位スクロール)の実装 2026-10-20 10:54:04 +09:00
armonica ae86b53147 スタイル: コーディング規約に準拠したコードフォーマットの適用(this.の明示、空白スタイルの統一)
- 自インスタンスメンバーアクセスへの this. 付与(28ファイル)
- .editorconfig に準拠したインデント・波括弧・空白スタイルの適用
- UTF-8 (BOMあり)、CRLF改行コード、行末空白除去の整合性検証
2026-10-20 10:14:26 +09:00
armonica 2fa40c950f feat(ui): GameItemBase への仮想プロパティ追加とメイン画面バッジ表示バインディングの堅牢化 2026-10-14 17:02:23 +09:00
armonica 7ead7386f6 feat(evb): Enigma Virtual Box (EVB) のVFSシグネチャ検証による誤検出防止とスキャナ同期の強化 2026-10-14 17:01:33 +09:00
armonica ee7b37323c docs(codecs): セーブデータコーデック基盤へのXMLドキュメントコメント付与および実装スタイルの整理 2026-10-14 17:01:02 +09:00
armonica 922f669191 style: .editorconfig の追加および全ファイルのエンコーディング(UTF-8 BOM)・CRLF・行末空白の統一 2026-10-14 17:00:27 +09:00
armonica 751e382adc feat(ui): ログ出力のバッチフラッシュ化・全体プログレス表示およびUI連携の改善
- ログ出力を ConcurrentQueue によるキューイングとタイマーによるバッチフラッシュ方式へ移行し、大量ログ出力時のUIフリーズを防止
- ログテキストボックスの文字数制限(10万文字超過時のトリム)を導入しメモリ肥大化を抑制
- ステータスバーに全体処理用プログレスバー(pbGlobalProgress)を追加
- EVB要解凍バッジおよびその他エンジンバッジのXAMLバインディング連携を整理
- セーブエディタ・ウディタ・SRPG Studio等の各種操作後に SaveBookmarks を呼び出すよう保存処理を補完
2026-10-14 09:59:11 +09:00
armonica cfdba6806a feat(scanner): アイコンサムネイルキャッシュ・深層exe探索・ブックマーク永続化に対応
- 抽出したアイコンを PNG 形式で Thumbnails フォルダにキャッシュし再スキャンを高速化
- サブディレクトリ内のゲーム実行ファイル(.exe)を最大深さまで再帰探索するロジックを追加
- キャッシュ再構築時でもお気に入りを保持する bookmarks.json 独立永続化機能を追加
- EngineLogicVersion によるエンジン判定ロジック更新時のキャッシュ自動無効化・再スキャンを導入
- EVB・スタンドアロン・その他エンジンの消失復旧および判定ロジックを強化
2026-10-14 09:58:33 +09:00
armonica 45bff52198 feat(engine): その他エンジン種別の追加およびラベル・サムネイル基盤の拡張
- エンジン区分に Other(その他)を追加し、該当バッジおよびフィルターに対応
- GameItemBase に EngineLabelText, EngineLabelBackground, OtherBadgeVisibility を追加
- TkoolGameItem および UnityGameItem で各エンジンのラベル表示ロジックを実装
- AppPathHelper にサムネイル保存用ディレクトリ取得メソッドを追加
- Converters に文字列非空時可視化コンバーター(StringNotEmptyToVisibilityConverter)を追加
- TkoolGameItem の EVB「要解凍」バッジ表示テキスト連携を実装
2026-10-14 09:58:14 +09:00
armonica 4398f80aa4 feat(tkool): リソース修復サービスおよび文字化け・URLエンコード救済プラグインを追加
- ツクールMV/MZの日本語ファイル名・URLエンコード・丸数字表記揺れを並列修復する TkoolResourceRepairService を追加
- ゲーム起動時に読み込み不整合を動的に解決する必須救済プラグイン ResourceLoaderFix.js を追加
- TkoolModService にて ResourceLoaderFix を最優先で適用するよう対応
2026-10-14 09:57:54 +09:00
armonica 908dc443eb fix(evb): PEセクションによるEVB判定の厳格化と誤検知の防止
- 誤検知の要因となっていたバイナリ文字列探索(ContainsEvbContentMarker)を廃止
- PEセクションテーブル(.enigma1, .enigma2)の検出のみで確実に判定するよう見直し
2026-10-14 09:57:33 +09:00
armonica 8f67ab1864 docs: UI文字列の日本語統一および変更時チェックリストを更新
- UI文字列追加・変更時の日本語表記遵守規則を明記
- 変更時チェックリストに日本語出力確認項目を追加
2026-10-14 09:57:11 +09:00
armonica 6f98860892 refactor(plugins): プラグイン管理UIのグループ化表示および特定ゲーム専用プラグインの分離に対応
- ModPluginDefinition に IsGameSpecific, TargetGameKey, GroupName, DefaultEnabled を追加
- プリンセスシナジー専用プラグイン(AlwaysMaxHp/AlwaysMaxMp)を一般ゲーム一覧から除外し対象ゲーム限定で表示
- TkoolGameItem のプラグイン一覧を CommonPluginOptions と SpecificPluginOptions に分離
- プラグイン設定Expander内に「共通プラグイン」と「固有ゲーム専用プラグイン」のグループ分けUIを実装
- 右側詳細パネルのレイアウトを改善し、起動ボタンを上部固定したまま下部設定のみを開閉可能に変更
- 不要な旧プラグイン GameLauncher_Mod.js の削除および読み込み除外処理を徹底
2026-10-09 10:48:20 +09:00
armonica c0989362a9 feat(bookmark): ゲームのお気に入り(ブックマーク)登録機能および優先ソート・フィルターを追加
- GameItemBase に IsBookmarked プロパティおよび関連バインディング項目を追加
- 一覧カード内星アイコン、詳細ヘッダーボタン、右クリックコンテキストメニューからブックマーク切替可能に
- ソート順に「★ ブックマーク優先」を追加し、サブフィルターに「★ ブックマークのみ」絞り込みを追加
- キャッシュ保存(UnifiedGameCacheEntry)にブックマーク状態を永続化し次回起動時も保持
- ステータスバーにブックマーク登録件数の集計表示を追加
2026-10-09 10:41:57 +09:00
armonica 59519208f3 feat(nwjs): NW.js汎用ゲームの自動検出・専用タブおよびバッジ表示機能を追加
- package.jsonを起点とする汎用NW.jsゲームの検出ロジック(NwjsDetector)を新規実装
- メインナビゲーションタブに「NW.js」タブを追加し、エンジン別フィルタリングに対応
- 一覧カードおよび詳細パネルヘッダーにNW.jsバッジを追加
- キャッシュ復元およびステータスバー集計にNW.jsエンジン分類を反映
2026-10-09 10:36:57 +09:00
armonica 90584379b7 feat(ui): EVB解凍済みバッジの表示および実効exeによる起動処理に対応
- TkoolGameItem に EVB解凍済みバッジ用の可視性プロパティ(EvbExtractedVisibility)を追加
- ResolveLaunchExecutable にて解凍先ディレクトリからの実効exe解決フォールバックを強化
- MainWindow.xaml に緑色の「解凍済み」バッジを追加し、UI上で状態を一目で確認可能に改善
- MainWindow.xaml.cs の LaunchGameAsync で TkoolGameItem の実効起動exeパスを解決して起動するように修正
2026-10-08 14:12:48 +09:00
armonica 5433371a77 feat(scanner): 解凍済みEVBゲームの起動パス・Mod対象解決と状態永続化に対応
- 解凍済みEVBゲームに対して、解凍先ディレクトリ内の実効exeを起動対象として解決
- 退避バックアップファイル(.glbak)の検索・解決処理を追加
- 解凍先フォルダ(_evb_extracted)配下の plugins.js をMod適用対象として検出し、MV/MZエンジン種別を判定
- EVBメタデータ(IsEvbPacked, IsEvbExtracted, EvbExtractedDirPathなど)をスキャンキャッシュに永続化
2026-10-08 14:12:17 +09:00
armonica 3550e20891 feat(evb): 解凍完了マーカーに基づくEVBゲーム検出の維持機能を追加
- 元exeが .glbak に退避された解凍後でもEVBゲームとして継続認識できるよう IsExtracted 判定を追加
- 解凍完了マーカー(_evb_extracted)の存在を検証し、後続の起動・アイコン解決の破損を防止
2026-10-08 14:12:07 +09:00
armonica 05e7bdb3c0 chore: bundle evbunpack tool and add EVB control/launch fixes
- Add Enigma Virtual Box (EVB) engine support: detection, badge, unpack/restore UI
- Bundle evbunpack.exe under Engines/Evb/Tools/evbunpack (Apache-2.0, with LICENSE/README)
- Copy Engines\\**\\Tools\\** to build output via csproj (publish already covered by publish.ps1)
- Throttle evbunpack progress reporting and shorten timeout to stop UI freeze
- Rename original packed exe to .glbak and write a completion marker; make Restore reverse it
- Launch the unpacked exe from _evb_extracted so script mods apply
- Replace EVB MessageBox dialogs with readable log summaries
- Remove obsolete boxed/7zip extraction code (NwjsPackageUnpacker, TkoolPackagedExtractionService)
2026-10-07 09:30:09 +09:00
armonica 8cea2a147d refactor: reorganize engine-based structure and add agent rules
- Engines/ 配下へエンジン別に再編 (Common/Rgss/Tkool/Tyrano/Wolf/Unity/Nwjs)
- ゲーム個別処理を Engines/<Engine>/Games/<GameName>/ へ分離し、共通処理から明示呼び出し
- 外部ツールを Engines/<Engine>/Tools/ へ移動し、AppPathHelper 経由で解決
- 旧 Tools/ 直下参照と不要な参照ファイル/バックアップを削除
- エージェント規則 AGENTS.md を追加し、README から参照
- publish.ps1 を Engines/<Engine>/Tools/ の再帰配置に対応
2026-10-07 02:30:49 +09:00
armonica 0d11039ee9 chore(tools): ゲーム補助ツール類(speedhack/アンパッカー/CLI)を追加 2026-10-06 08:11:54 +09:00
armonica 0eb06318ac feat: プリンセスシナジー専用のHP/MP常時MAXプラグインを追加
- plugins/AlwaysMaxHp.js, AlwaysMaxMp.js を新規追加
  本作のカードバトルは Game_BattlerBase/Game_Actor のHP/MP APIを使わず、
  独自の NPlayer[0](= $gameActors._data[1])の _hp/_mp を直接書き換える実装。
  戦闘毎フレーム入口 Game_Interpreter.prototype.update をフックし、
  主人公 NPlayer[0] の _hp/_mp を毎フレーム mhp/mmp へクランプする。
- TkoolGameItem に PrincessAlwaysMaxHp / PrincessAlwaysMaxMp を追加し、
  PluginSettings(AlwaysMaxHp/AlwaysMaxMp)へ直接マッピング。
- GameItemBase に IsPrincessSynergy(virtual)を追加し、
  TkoolGameItem でタイトル判定("プリンセスシナジー")を実装。
  該当ゲーム選択時のみ右パネルに専用チェックを表示し、他ゲームへは非表示。
- MainWindow.xaml にプリンセスシナジー専用のHP/MP常時MAXチェックUIを追加。
- GameLauncher.csproj を更新。
2026-10-06 02:57:54 +09:00
armonica 6cea9fa91b chore: 右パネルの不要なウディタデバッグUI(効果のないチェック項目)と関連する死にコードを削除 2026-10-06 01:23:15 +09:00
armonica 01ee04b4cc feat: エンジン種別タブ(WOLF/SRPG)追加、Backupsパス統一、Shift_JIS有効化、スキャナ改善 2026-10-06 01:19:07 +09:00
armonica a1430bbdbc feat: SRPG Studio対応(data.dts解凍・改造、プロキシDLL倍速) 2026-10-06 01:19:04 +09:00
armonica 0befb0a972 feat: WOLF RPGエディター対応(Data.wolf解凍・改造・セーブ編集、プロキシDLL倍速) 2026-10-06 01:19:01 +09:00
armonica bc5ba43ce7 feat: ツクールVX/VX Ace改造対応、Backupsフォルダ統一、全エンジンの種類別一覧表示タブの実装 2026-10-04 19:28:36 +09:00
80 changed files with 15004 additions and 1406 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
root = true
[*]
charset = utf-8-bom
end_of_line = crlf
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
[*.cs]
# this. の明示
dotnet_style_qualification_for_field = true:suggestion
dotnet_style_qualification_for_property = true:suggestion
dotnet_style_qualification_for_method = true:suggestion
dotnet_style_qualification_for_event = true:suggestion
# 改行・波括弧スタイル
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
# 空白スタイル
csharp_space_after_cast = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
+12 -1
View File
@@ -1,4 +1,4 @@
## Visual Studio 2026 / .NET .gitignore ## Visual Studio 2026 / .NET .gitignore
[Bb]in/ [Bb]in/
[Oo]bj/ [Oo]bj/
[Ll]og/ [Ll]og/
@@ -8,3 +8,14 @@
*.suo *.suo
*.userosscache *.userosscache
*.sln.docstates *.sln.docstates
# Runtime data
Backups/
Profiles/
config.json
games_cache.json
# Temporary reverse-engineering / analysis reference artifacts
WolfDec_*.json
WolfDec_main.cpp
*_ref.h
+67
View File
@@ -0,0 +1,67 @@
# AGENTS.md — GameLauncher エージェント規則
このファイルは **GameLauncher プロジェクトの AI エージェント向け規則** である。
本プロジェクトでのすべての変更(コード追加・修正・削除・発行)は、必ず以下の規則に従って実施すること。
> 注意: 本規則は今後も追加・変更され得る。作業を開始する前に必ず本ファイルを確認し、
> 最新の規則に従うこと。
---
## 1. フォルダ構成の原則(エンジン別集約)
- エンジン別の処理は `Engines/<Engine>/` に集約する。
- 例: `Engines/Rgss/`, `Engines/Tkool/`, `Engines/Tyrano/`, `Engines/Wolf/`, `Engines/Unity/`, `Engines/Nwjs/`
- エンジン共通の基盤は `Engines/Common/`(例: `IEngineModule.cs`, `EngineDetectionHelper.cs`)。
- エンジン別クラスの名前空間は `GameLauncher.Engines.<Engine>` とする。
- 例: `GameLauncher.Engines.Rgss`, `GameLauncher.Engines.Wolf`
- エンジンに依存しない共通処理のみ `Services/` / `Models/` / `Helpers/` に置く。
- 例: `Services/GameScannerService.cs`, `Models/GameItemBase.cs`, `Helpers/AppPathHelper.cs`
## 2. ゲーム個別対応の規則(他ゲームへ影響させない)
- 特定ゲーム専用の処理は `Engines/<Engine>/Games/<GameName>/` に作成する。
- 名前空間は `GameLauncher.Engines.<Engine>.Games.<GameName>` とする。
- 例: `Engines/Rgss/Games/IiniTitleRepair/GameIniTitleRepair.cs`
→ `namespace GameLauncher.Engines.Rgss.Games.IiniTitleRepair`
- ゲーム個別処理は共通処理から **明示的に呼び出す** こと(暗黙のグローバル副作用を持たせない)。
- **特定ゲーム専用の改造が他ゲームへ影響を与えてはならない(必須要件)。**
- 可能な限りバックアップからの復元手段を用意し、後で元に戻せるようにする。
- プラグインで対応できない場合は、バックアップ・復元可能な直接ファイル変更を許容する。
## 3. 外部ツール・外部ファイルの規則(エンジン単位で参照)
- エンジン専用の外部ツール/ファイルは `Engines/<Engine>/Tools/` に配置する。
- 例: `Engines/Rgss/Tools/SRPG_Unpacker.exe`, `Engines/Wolf/Tools/UberWolfCli.exe`
- パス解決には共通ヘルパーを使用する。
- `AppPathHelper.ResolveEngineTool(string engineName, string toolFileName)`
- `AppPathHelper.GetEngineToolsDirectory(string engineName)`
- **エンジン間でツールを共有しない。旧 `Tools/` 直下を参照するコードを新規に書かない。**
- 外部ツールの配置は `publish.ps1` が `Engines/<Engine>/Tools/` を再帰的に発行先へコピーする。
## 4. ビルド・発行の規則
- 変更後は **必ずビルドを成功させる**(`build_solution` を使用)。
- 発行は `publish.ps1` で行い、`Z:\自作ソフト\GameLauncher` へ配置して起動確認まで行う。
- 単一ファイル発行(`PublishSingleFile`)の設定を維持する。
## 5. コメント・表記の規則
- コードコメントは既存コードに合わせて日本語/英語を適切に使い分ける。
- 新規ファイルには冒頭に説明コメントを付ける。
- ファイル名・シンボル参照はバッククォートで囲む。
- UI 文字列を追加・変更する場合は、既存の日本語表記に合わせる。
> 注: ユーザーから見える出力の言語(日本語)については、グローバルのユーザー記憶
> (`/memories/preferences.md`)で規定する。重複を避けるため本ファイルでは規定しない。
---
## 6. 変更時のチェックリスト
1. 本ファイル(`AGENTS.md`)の最新規則を確認したか。
2. エンジン別の処理は `Engines/<Engine>/` 配下に置いたか。
3. ゲーム個別処理は `Engines/<Engine>/Games/<GameName>/` に分離し、他ゲームへ影響しないか。
4. 外部ツールは `Engines/<Engine>/Tools/` にあり、`AppPathHelper` 経由で参照しているか。
5. ビルドが成功し、`publish.ps1` で発行できるか。
6. ユーザーから見える出力が日本語になっているか(判定基準は `/memories/preferences.md`)。
+1 -1
View File
@@ -1,4 +1,4 @@
<Window x:Class="GameLauncher.AddKeyDialog" <Window x:Class="GameLauncher.AddKeyDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+13 -12
View File
@@ -1,6 +1,7 @@
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using GameLauncher.Models; using GameLauncher.Models;
using GameLauncher.Engines.Unity;
namespace GameLauncher namespace GameLauncher
{ {
@@ -15,37 +16,37 @@ namespace GameLauncher
public AddKeyDialog() public AddKeyDialog()
{ {
InitializeComponent(); this.InitializeComponent();
txtKeyName.Focus(); this.txtKeyName.Focus();
} }
private void btnOk_Click(object sender, RoutedEventArgs e) private void btnOk_Click(object sender, RoutedEventArgs e)
{ {
var keyName = txtKeyName.Text.Trim(); var keyName = this.txtKeyName.Text.Trim();
if (string.IsNullOrWhiteSpace(keyName)) if (string.IsNullOrWhiteSpace(keyName))
{ {
MessageBox.Show("キー名を入力してください。", "入力エラー", MessageBoxButton.OK, MessageBoxImage.Warning); MessageBox.Show("キー名を入力してください。", "入力エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
return; return;
} }
KeyName = keyName; this.KeyName = keyName;
var selectedTag = (cmbKeyType.SelectedItem as ComboBoxItem)?.Tag?.ToString(); var selectedTag = (this.cmbKeyType.SelectedItem as ComboBoxItem)?.Tag?.ToString();
KeyType = selectedTag switch this.KeyType = selectedTag switch
{ {
"Float" => PlayerPrefsType.Float, "Float" => PlayerPrefsType.Float,
"String" => PlayerPrefsType.String, "String" => PlayerPrefsType.String,
_ => PlayerPrefsType.Int _ => PlayerPrefsType.Int
}; };
KeyValue = txtKeyValue.Text; this.KeyValue = this.txtKeyValue.Text;
DialogResult = true; this.DialogResult = true;
Close(); this.Close();
} }
private void btnCancel_Click(object sender, RoutedEventArgs e) private void btnCancel_Click(object sender, RoutedEventArgs e)
{ {
DialogResult = false; this.DialogResult = false;
Close(); this.Close();
} }
} }
} }
+1 -1
View File
@@ -1,4 +1,4 @@
<Application x:Class="GameLauncher.App" <Application x:Class="GameLauncher.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GameLauncher" xmlns:local="clr-namespace:GameLauncher"
+4 -1
View File
@@ -1,4 +1,4 @@
using System; using System;
using System.IO; using System.IO;
using System.Windows; using System.Windows;
using GameLauncher.Helpers; using GameLauncher.Helpers;
@@ -14,6 +14,9 @@ namespace GameLauncher
{ {
base.OnStartup(e); base.OnStartup(e);
// Shift_JIS等のコードページを有効化
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// 作業ディレクトリを exe のあるフォルダに確実に設定 // 作業ディレクトリを exe のあるフォルダに確実に設定
AppPathHelper.SetCurrentDirectoryToExeDirectory(); AppPathHelper.SetCurrentDirectoryToExeDirectory();
+1 -1
View File
@@ -1,4 +1,4 @@
//ティラノビルダーによる自動ビルド  //ティラノビルダーによる自動ビルド
;debugMenu.visible=false ;debugMenu.visible=false
;configSave=file ;configSave=file
;global.config_version=5.00 ;global.config_version=5.00
+176
View File
@@ -0,0 +1,176 @@
<Window x:Class="GameLauncher.ConfigDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="アプリケーション設定"
Height="420" Width="640"
WindowStartupLocation="CenterOwner"
Background="#181824"
Foreground="#E0E0E6"
ResizeMode="NoResize"
FontFamily="Segoe UI, Meiryo UI, Yu Gothic UI">
<Window.Resources>
<SolidColorBrush x:Key="AccentPrimary" Color="#6C5CE7"/>
<SolidColorBrush x:Key="AccentHover" Color="#7D6DF8"/>
<SolidColorBrush x:Key="BorderColor" Color="#38384C"/>
<SolidColorBrush x:Key="TextSecondary" Color="#9E9EB4"/>
<Style x:Key="ModernButton" TargetType="Button">
<Setter Property="Background" Value="#2E2E3E"/>
<Setter Property="Foreground" Value="#E0E0E6"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="#44445A"/>
<Setter Property="Padding" Value="14,7"/>
<Setter Property="FontSize" Value="12"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="6"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#3D3D52"/>
<Setter Property="BorderBrush" Value="{StaticResource AccentPrimary}"/>
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="PrimaryButton" TargetType="Button" BasedOn="{StaticResource ModernButton}">
<Setter Property="Background" Value="{StaticResource AccentPrimary}"/>
<Setter Property="Foreground" Value="#FFFFFF"/>
<Setter Property="BorderThickness" Value="0"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource AccentHover}"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid Margin="24">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- ヘッダー -->
<StackPanel Grid.Row="0" Margin="0,0,0,18">
<TextBlock Text="⚙ 設定 (Configuration)" FontSize="18" FontWeight="Bold" Foreground="#FFFFFF"/>
<TextBlock Text="ツクールVX改造用外部ツール設定およびバックアップ設定を管理します。" FontSize="11" Foreground="{StaticResource TextSecondary}" Margin="0,3,0,0"/>
</StackPanel>
<!-- 設定項目エリア -->
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<StackPanel>
<!-- 1. RGSS Extractor パス設定 -->
<Border Background="#20202E" BorderBrush="{StaticResource BorderColor}" BorderThickness="1" CornerRadius="8" Padding="14" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="📦 RGSS Extractor のパス (ツクールVX / VX Ace用)" FontSize="13" FontWeight="Bold" Foreground="#A29BFE"/>
<TextBlock Text="ツクールVXおよびVX Aceの暗号化アーカイブ (*.rgss3a / *.rgss2a) の解凍・抽出に使用する外部ツールのパスを設定します。"
FontSize="11" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="0,3,0,10"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtRgssExtractorPath" Grid.Column="0" Background="#14141C" Foreground="#FFFFFF"
BorderBrush="{StaticResource BorderColor}" BorderThickness="1" Padding="8,6" FontSize="12"/>
<Button Grid.Column="2" Style="{StaticResource ModernButton}" Content="📁 参照..." Click="btnBrowseExtractor_Click"/>
</Grid>
</StackPanel>
</Border>
<!-- 1.5. Wolf RPG 解凍ツール パス設定 -->
<Border Background="#20202E" BorderBrush="{StaticResource BorderColor}" BorderThickness="1" CornerRadius="8" Padding="14" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="🐺 Wolf RPG アーカイブ解凍ツールのパス (Data.wolf 解凍用)" FontSize="13" FontWeight="Bold" Foreground="#3B3B98"/>
<TextBlock Text="WOLF RPGエディターの暗号化アーカイブ (*.wolf) の解凍・抽出に使用するツールのパスを設定します(未指定時は内蔵ツール Tools\UberWolfCli.exe が自動使用されます)。"
FontSize="11" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="0,3,0,10"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtWolfExtractorPath" Grid.Column="0" Background="#14141C" Foreground="#FFFFFF"
BorderBrush="{StaticResource BorderColor}" BorderThickness="1" Padding="8,6" FontSize="12"/>
<Button Grid.Column="2" Style="{StaticResource ModernButton}" Content="📁 参照..." Click="btnBrowseWolfExtractor_Click"/>
</Grid>
</StackPanel>
</Border>
<!-- 1.7. ウィンドウ拡大外部ツール パス設定 -->
<Border Background="#20202E" BorderBrush="{StaticResource BorderColor}" BorderThickness="1" CornerRadius="8" Padding="14" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="🖥 ウィンドウ拡大用 外部ツールのパス (ツクールVX / VX Ace用)" FontSize="13" FontWeight="Bold" Foreground="#FDCB6E"/>
<TextBlock Text="ゲームウィンドウを拡大する外部ツール(Sizer等)の実行ファイルパスを設定します。未指定の場合、ランチャー内蔵のWin32 API方式で拡大します。"
FontSize="11" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="0,3,0,10"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtWindowResizeToolPath" Grid.Column="0" Background="#14141C" Foreground="#FFFFFF"
BorderBrush="{StaticResource BorderColor}" BorderThickness="1" Padding="8,6" FontSize="12"/>
<Button Grid.Column="2" Style="{StaticResource ModernButton}" Content="📁 参照..." Click="btnBrowseWindowResizeTool_Click"/>
</Grid>
</StackPanel>
</Border>
<!-- 2. バックアップ保存先フォルダ -->
<Border Background="#20202E" BorderBrush="{StaticResource BorderColor}" BorderThickness="1" CornerRadius="8" Padding="14" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="📦 バックアップ統一保存先" FontSize="13" FontWeight="Bold" Foreground="#00B894"/>
<TextBlock Text="ツクールMV/MZ・ティラノ・ツクールVX/VX Ace・Unityのすべてのバックアップは、exe直下のBackupsフォルダ(Z:\自作ソフト\GameLauncher\Backups)に集約されます。"
FontSize="11" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="0,3,0,10"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtBackupsPath" Grid.Column="0" Background="#14141C" Foreground="#81ECEC"
BorderBrush="{StaticResource BorderColor}" BorderThickness="1" Padding="8,6" FontSize="12" IsReadOnly="True"/>
<Button Grid.Column="2" Style="{StaticResource ModernButton}" Content="📂 フォルダを開く" Click="btnOpenBackupsDir_Click"/>
</Grid>
</StackPanel>
</Border>
<!-- 3. デフォルト起動時改造適用 -->
<Border Background="#20202E" BorderBrush="{StaticResource BorderColor}" BorderThickness="1" CornerRadius="8" Padding="14">
<StackPanel>
<CheckBox x:Name="chkDefaultApplyMod" Content="一度も変更していないゲームにおける「起動時に改造を適用する」の初期値をONにする"
FontSize="12" FontWeight="SemiBold" Foreground="#FFFFFF"/>
<TextBlock Text="新規検出されたゲームにおいて、初期状態でスクリプト改造を有効にするかどうかを設定します。"
FontSize="11" Foreground="{StaticResource TextSecondary}" Margin="24,4,0,0"/>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
<!-- ボタンバー -->
<Border Grid.Row="2" Margin="0,18,0,0" Padding="0,12,0,0" BorderBrush="{StaticResource BorderColor}" BorderThickness="0,1,0,0">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button Style="{StaticResource PrimaryButton}" Content="✔ 保存して閉じる" Width="140" Margin="0,0,10,0" Click="btnSave_Click"/>
<Button Style="{StaticResource ModernButton}" Content="キャンセル" Width="90" Click="btnCancel_Click"/>
</StackPanel>
</Border>
</Grid>
</Window>
+129
View File
@@ -0,0 +1,129 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using Microsoft.Win32;
using GameLauncher.Helpers;
using GameLauncher.Models;
namespace GameLauncher
{
/// <summary>
/// 設定ダイアログのロジック
/// </summary>
public partial class ConfigDialog : Window
{
private readonly LauncherConfig _config;
public bool IsSaved { get; private set; }
public ConfigDialog(LauncherConfig config)
{
this.InitializeComponent();
this._config = config;
this.txtRgssExtractorPath.Text = this._config.RgssExtractorPath ?? @"C:\Soft\RGSS-Extractor-v1.0\RGSS Extractor.exe";
this.txtWolfExtractorPath.Text = this._config.WolfExtractorPath ?? string.Empty;
this.txtWindowResizeToolPath.Text = this._config.WindowResizeToolPath ?? string.Empty;
this.txtBackupsPath.Text = AppPathHelper.GetBackupsDirectory();
this.chkDefaultApplyMod.IsChecked = this._config.DefaultApplyMod;
}
private void btnBrowseExtractor_Click(object sender, RoutedEventArgs e)
{
var ofd = new OpenFileDialog
{
Title = "RGSS Extractor の実行ファイルを選択してください",
Filter = "実行ファイル (*.exe)|*.exe|すべてのファイル (*.*)|*.*",
FileName = "RGSS Extractor.exe"
};
var currentDir = Path.GetDirectoryName(this.txtRgssExtractorPath.Text);
if (!string.IsNullOrEmpty(currentDir) && Directory.Exists(currentDir))
{
ofd.InitialDirectory = currentDir;
}
if (ofd.ShowDialog() == true)
{
this.txtRgssExtractorPath.Text = ofd.FileName;
}
}
private void btnBrowseWolfExtractor_Click(object sender, RoutedEventArgs e)
{
var ofd = new OpenFileDialog
{
Title = "Wolf RPG 解凍ツール (UberWolfCli.exe / WolfDec.exe) を選択してください",
Filter = "実行ファイル (*.exe)|*.exe|すべてのファイル (*.*)|*.*",
FileName = "UberWolfCli.exe"
};
var currentDir = Path.GetDirectoryName(this.txtWolfExtractorPath.Text);
if (!string.IsNullOrEmpty(currentDir) && Directory.Exists(currentDir))
{
ofd.InitialDirectory = currentDir;
}
if (ofd.ShowDialog() == true)
{
this.txtWolfExtractorPath.Text = ofd.FileName;
}
}
private void btnBrowseWindowResizeTool_Click(object sender, RoutedEventArgs e)
{
var ofd = new OpenFileDialog
{
Title = "ウィンドウ拡大用の外部ツール(Sizer等)を選択してください",
Filter = "実行ファイル (*.exe)|*.exe|すべてのファイル (*.*)|*.*",
FileName = "Sizer.exe"
};
var currentDir = Path.GetDirectoryName(this.txtWindowResizeToolPath.Text);
if (!string.IsNullOrEmpty(currentDir) && Directory.Exists(currentDir))
{
ofd.InitialDirectory = currentDir;
}
if (ofd.ShowDialog() == true)
{
this.txtWindowResizeToolPath.Text = ofd.FileName;
}
}
private void btnOpenBackupsDir_Click(object sender, RoutedEventArgs e)
{
try
{
var dir = AppPathHelper.GetBackupsDirectory();
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
Process.Start(new ProcessStartInfo { FileName = dir, UseShellExecute = true });
}
catch (Exception ex)
{
MessageBox.Show($"バックアップフォルダを開けませんでした:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
this._config.RgssExtractorPath = this.txtRgssExtractorPath.Text.Trim();
this._config.WolfExtractorPath = this.txtWolfExtractorPath.Text.Trim();
this._config.WindowResizeToolPath = this.txtWindowResizeToolPath.Text.Trim();
this._config.DefaultApplyMod = this.chkDefaultApplyMod.IsChecked == true;
this.IsSaved = true;
this.DialogResult = true;
this.Close();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
this.Close();
}
}
}
+208
View File
@@ -0,0 +1,208 @@
using System;
using System.IO;
namespace GameLauncher.Engines.Common
{
/// <summary>
/// Shared helpers for engine detection and misdetection repair logic,
/// consolidated from the duplicated branches previously spread across
/// GameScannerService. This is the single source of truth for engine names
/// and for re-validating a detected engine against the game directory content.
/// </summary>
public static class EngineDetectionHelper
{
/// <summary>Canonical engine name for RPG Maker (RGSS based) games.</summary>
public const string EngineRgss = "Rgss";
/// <summary>Canonical engine name for RPG Maker MV/MZ (NW.js based) games.</summary>
public const string EngineTkool = "Tkool";
/// <summary>Canonical engine name for tyrano scripts games.</summary>
public const string EngineTyrano = "Tyrano";
/// <summary>Canonical engine name for Wolf RPG games.</summary>
public const string EngineWolf = "Wolf";
/// <summary>Canonical engine name for Unity games.</summary>
public const string EngineUnity = "Unity";
/// <summary>Canonical engine name for generic NW.js packaged games.</summary>
public const string EngineNwjs = "Nwjs";
/// <summary>Canonical engine name for Enigma Virtual Box packed applications.</summary>
public const string EngineEvb = "Evb";
/// <summary>Canonical engine name used when detection fails.</summary>
public const string EngineUnknown = "Unknown";
/// <summary>Resolves the canonical engine name from a raw detection string.</summary>
/// <remarks>
/// Handles case differences and common aliases (e.g. "RPGMaker", "RGSS3",
/// "MV", "MZ", "WolfRPG", "NW.js") so callers always compare canonical names.
/// </remarks>
public static string NormalizeEngineName(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
{
return EngineUnknown;
}
var value = raw.Trim();
// Case-insensitive comparison without allocating a lowercase copy each time.
if (Matches(value, "Rgss", "RGSS", "RPGMaker", "RPGMakerVX", "VX", "VXAce", "XP"))
{
return EngineRgss;
}
if (Matches(value, "Tkool", "RPGMakerMV", "RPGMakerMZ", "MV", "MZ"))
{
return EngineTkool;
}
if (Matches(value, "Tyrano", "Tyranoscript", "KAG", "TJS"))
{
return EngineTyrano;
}
if (Matches(value, "Wolf", "WolfRPG"))
{
return EngineWolf;
}
if (Matches(value, "Unity"))
{
return EngineUnity;
}
if (Matches(value, "Nwjs", "NWjs", "NW.js", "NWJS"))
{
return EngineNwjs;
}
if (Matches(value, "Evb", "Enigma", "EnigmaVB", "EnigmaVirtualBox"))
{
return EngineEvb;
}
return EngineUnknown;
}
/// <summary>Re-validates and repairs engine misdetection for a scanned game.</summary>
/// <remarks>
/// A single detection signal (extension or file layout) can be wrong, so the
/// canonical engine is re-checked against the game directory content. When the
/// detected engine contradicts the on-disk evidence, the evidence-based engine
/// is returned; otherwise the normalized detection is kept.
/// </remarks>
public static string RepairMisdetection(string gameDirectory, string detectedEngine)
{
var normalized = NormalizeEngineName(detectedEngine);
if (string.IsNullOrWhiteSpace(gameDirectory) || !Directory.Exists(gameDirectory))
{
return normalized;
}
var evidence = DetectFromDirectory(gameDirectory);
// Directory evidence has priority when it clearly identifies an engine.
if (evidence != EngineUnknown && evidence != normalized)
{
return evidence;
}
return normalized;
}
/// <summary>
/// Infers the engine purely from the game directory layout.
/// Returns <see cref="EngineUnknown"/> when no decisive evidence is found.
/// </summary>
private static string DetectFromDirectory(string gameDirectory)
{
// Enigma Virtual Box (EVB): a packed executable hides the real engine, so it
// must be detected before any other layout-based check. Detection uses the
// PE section signature only (see EvbDetectionHelper.IsEvbPacked).
if (Engines.Evb.EvbDetectionHelper.FindEvbPackedExecutable(gameDirectory) != null)
{
return EngineEvb;
}
// RPG Maker MV/MZ: www/ folder or a Game.exe next to nw.js package files.
var wwwDir = Path.Combine(gameDirectory, "www");
if (Directory.Exists(wwwDir))
{
return EngineTkool;
}
if (Engines.Nwjs.NwjsDetector.IsNwjsGame(gameDirectory))
{
return EngineNwjs;
}
// Wolf RPG: Data folder with a .wolf project file in the root.
if (Directory.Exists(Path.Combine(gameDirectory, "Data")))
{
var wolfProjects = Directory.GetFiles(gameDirectory, "*.wolf", SearchOption.TopDirectoryOnly);
if (wolfProjects.Length > 0)
{
return EngineWolf;
}
}
// RPG Maker RGSS: Game.ini or a Data folder containing .rvdata2/.rvdata files.
var gameIni = Path.Combine(gameDirectory, "Game.ini");
if (File.Exists(gameIni))
{
return EngineRgss;
}
var dataDir = Path.Combine(gameDirectory, "Data");
if (Directory.Exists(dataDir) &&
(Directory.GetFiles(dataDir, "*.rvdata2").Length > 0 ||
Directory.GetFiles(dataDir, "*.rvdata").Length > 0))
{
return EngineRgss;
}
// tyrano: a tyrano/ subfolder or a .tjs config in the root.
if (Directory.Exists(Path.Combine(gameDirectory, "tyrano")))
{
return EngineTyrano;
}
if (Directory.GetFiles(gameDirectory, "*.tjs", SearchOption.TopDirectoryOnly).Length > 0)
{
return EngineTyrano;
}
// Unity: an *_Data folder next to the executable (typical Unity layout).
foreach (var dir in Directory.GetDirectories(gameDirectory))
{
var name = Path.GetFileName(dir);
if (name.EndsWith("_Data", StringComparison.OrdinalIgnoreCase) &&
File.Exists(Path.Combine(dir, "globalgamemanagers")))
{
return EngineUnity;
}
}
return EngineUnknown;
}
/// <summary>Case-insensitive equality against any of the provided aliases.</summary>
private static bool Matches(string value, params string[] aliases)
{
foreach (var alias in aliases)
{
if (string.Equals(value, alias, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
}
+28
View File
@@ -0,0 +1,28 @@
using GameLauncher.Models;
namespace GameLauncher.Engines.Common
{
/// <summary>
/// Common contract for engine-specific detection, mod application,
/// and external tool path resolution.
/// Implemented once per supported game engine so that engine handling
/// is unified and any single engine's hacks cannot affect another engine.
/// </summary>
public interface IEngineModule
{
/// <summary>Engine identifier (e.g. "Rgss", "Wolf", "Unity").</summary>
string EngineName { get; }
/// <summary>Determines whether the given game directory belongs to this engine.</summary>
bool Detect(string gameDirectory);
/// <summary>Applies the mod for this engine to the specified game.</summary>
bool ApplyMod(string gameDirectory, ModPluginDefinition plugin);
/// <summary>Returns whether the mod has already been applied.</summary>
bool IsModApplied(string gameDirectory);
/// <summary>Returns the absolute path of an engine-specific external tool.</summary>
string ResolveToolPath(string toolFileName);
}
}
+284
View File
@@ -0,0 +1,284 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// Detects Enigma Virtual Box (EVB) packed executables that are actually compressed
/// with EVB and unpackable by <c>evbunpack</c>.
///
/// Detection strategy:
/// 1. Parse the PE header and inspect the section table for the packer's
/// <c>.enigma1</c> section (required by <c>evbunpack</c> to restore the PE).
/// 2. Verify the presence of the EVB virtual filesystem pack header signature
/// (<c>"EVB\0"</c> / <c>0x45, 0x56, 0x42, 0x00</c>) inside the Enigma section
/// data or PE overlay (required by <c>evbunpack</c> to extract the VFS, and
/// distinguishes Enigma Virtual Box from commercial Enigma Protector DRM which
/// cannot be unpacked).
///
/// This class is engine-local and has no side effects.
/// </summary>
public static class EvbDetectionHelper
{
/// <summary>Primary section name required by evbunpack.</summary>
private const string EnigmaPrimarySection = ".enigma1";
/// <summary>Secondary section name produced by the packer.</summary>
private const string EnigmaSecondarySection = ".enigma2";
/// <summary>EVB virtual filesystem header magic ("EVB\0").</summary>
private static readonly byte[] EvbMagic = [0x45, 0x56, 0x42, 0x00];
/// <summary>Returns true when the given executable is packed with EVB and can be unpacked.</summary>
/// <remarks>
/// Reads the PE section table for <c>.enigma1</c> and verifies the <c>EVB\0</c>
/// virtual filesystem header. Any IO/format error yields false.
/// </remarks>
public static bool IsEvbPacked(string exePath)
{
if (string.IsNullOrWhiteSpace(exePath) || !File.Exists(exePath))
{
return false;
}
try
{
return HasExtractableEnigmaPackage(exePath);
}
catch
{
// Unparseable executable -> never claim EVB.
return false;
}
}
/// <summary>
/// Scans a game directory for an EVB packed executable.
/// Returns the first decisive match, or null when none is found.
/// </summary>
public static string? FindEvbPackedExecutable(string gameDirectory)
{
if (string.IsNullOrWhiteSpace(gameDirectory) || !Directory.Exists(gameDirectory))
{
return null;
}
try
{
var exes = Directory.GetFiles(gameDirectory, "*.exe", SearchOption.TopDirectoryOnly)
.Where(f => !IsExcludedUtilityExe(Path.GetFileName(f)))
.OrderBy(f => string.Equals(Path.GetFileName(f), "Game.exe", StringComparison.OrdinalIgnoreCase) ? 0 : 1);
return exes.FirstOrDefault(IsEvbPacked);
}
catch
{
return null;
}
}
private static bool IsExcludedUtilityExe(string fileName)
{
if (string.IsNullOrEmpty(fileName)) return true;
return fileName.StartsWith("unins", StringComparison.OrdinalIgnoreCase) ||
fileName.StartsWith("UnityCrashHandler", StringComparison.OrdinalIgnoreCase) ||
fileName.Equals("notification_helper.exe", StringComparison.OrdinalIgnoreCase) ||
fileName.Equals("crashpad_handler.exe", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Returns true when the game directory already holds a completed EVB extraction.
///
/// Once a game is unpacked, the original packed exe is renamed to "*.glbak" and the
/// unpacked files (including the real exe) live inside the game-local "_evb_extracted"
/// folder. At that point <see cref="FindEvbPackedExecutable"/> can no longer find a
/// top-level "*.exe", so this extra signal is required to keep recognizing the folder
/// as an EVB game (otherwise launch and icon resolution break after unpacking).
///
/// Only a completed extraction (completion marker present) is accepted, so a normal
/// unpacked game without any EVB artifacts is never misclassified.
/// </summary>
public static bool IsExtracted(string gameDirectory)
{
if (string.IsNullOrWhiteSpace(gameDirectory) || !Directory.Exists(gameDirectory))
{
return false;
}
try
{
return EvbUnpackService.IsExtractionComplete(gameDirectory, out _);
}
catch
{
return false;
}
}
/// <summary>
/// Parses the PE section table, verifies the <c>.enigma1</c> section, and checks
/// for the <c>EVB\0</c> virtual filesystem header required by <c>evbunpack</c>.
/// </summary>
private static bool HasExtractableEnigmaPackage(string exePath)
{
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new BinaryReader(fs);
if (fs.Length < 0x40)
{
return false;
}
// DOS header: check the "MZ" signature and locate the PE header offset.
if (reader.ReadUInt16() != 0x5A4D)
{
return false;
}
fs.Seek(0x3C, SeekOrigin.Begin);
int peOffset = reader.ReadInt32();
if (peOffset <= 0 || peOffset + 24 > fs.Length)
{
return false;
}
fs.Seek(peOffset, SeekOrigin.Begin);
if (reader.ReadUInt32() != 0x00004550) // "PE\0\0"
{
return false;
}
// COFF header: number of sections is at offset 6 from PE signature (peOffset + 6).
fs.Seek(peOffset + 6, SeekOrigin.Begin);
ushort sectionCount = reader.ReadUInt16();
if (sectionCount == 0 || sectionCount > 96)
{
return false;
}
// Optional header size is at offset 20 in the COFF header.
fs.Seek(peOffset + 20, SeekOrigin.Begin);
ushort optionalHeaderSize = reader.ReadUInt16();
// Section table starts right after the optional header.
long sectionTable = peOffset + 24 + optionalHeaderSize;
bool hasEnigma1 = false;
var enigmaRanges = new List<(long Offset, long Size)>();
long maxSectionEnd = 0;
// Each section header is 40 bytes.
for (int i = 0; i < sectionCount; i++)
{
long offset = sectionTable + (long)i * 40;
if (offset + 40 > fs.Length)
{
break;
}
fs.Seek(offset, SeekOrigin.Begin);
var nameBytes = reader.ReadBytes(8);
var name = System.Text.Encoding.ASCII.GetString(nameBytes).TrimEnd('\0').Trim();
fs.Seek(offset + 16, SeekOrigin.Begin);
uint rawSize = reader.ReadUInt32();
uint rawPtr = reader.ReadUInt32();
if (rawPtr > 0 && rawSize > 0)
{
long end = (long)rawPtr + rawSize;
if (end > maxSectionEnd && end <= fs.Length)
{
maxSectionEnd = end;
}
}
if (string.Equals(name, EnigmaPrimarySection, StringComparison.OrdinalIgnoreCase))
{
hasEnigma1 = true;
if (rawPtr > 0 && rawSize > 0 && rawPtr < fs.Length)
{
enigmaRanges.Insert(0, (rawPtr, Math.Min((long)rawSize, fs.Length - rawPtr)));
}
}
else if (string.Equals(name, EnigmaSecondarySection, StringComparison.OrdinalIgnoreCase))
{
if (rawPtr > 0 && rawSize > 0 && rawPtr < fs.Length)
{
enigmaRanges.Add((rawPtr, Math.Min((long)rawSize, fs.Length - rawPtr)));
}
}
}
// evbunpack requires the .enigma1 section to unpack and rebuild the executable.
if (!hasEnigma1)
{
return false;
}
// Also include PE overlay if any bytes exist after the last section.
if (maxSectionEnd > 0 && maxSectionEnd + 64 <= fs.Length)
{
enigmaRanges.Add((maxSectionEnd, fs.Length - maxSectionEnd));
}
// Verify that the EVB virtual filesystem signature ("EVB\0") exists in the
// Enigma sections or overlay so that Enigma Protector DRM executables (which
// have .enigma1/.enigma2 but no unpackable EVB VFS) are not misclassified.
foreach (var (rangeOffset, rangeSize) in enigmaRanges)
{
if (ContainsEvbMagicInRange(fs, rangeOffset, rangeSize))
{
return true;
}
}
return false;
}
/// <summary>
/// Searches for the "EVB\0" pack header signature within the given file range
/// (scanning up to the first 16 MB of the range in 64 KB chunks).
/// </summary>
private static bool ContainsEvbMagicInRange(FileStream fs, long startOffset, long length)
{
const int chunkSize = 64 * 1024;
long maxScan = Math.Min(length, 16L * 1024 * 1024);
if (maxScan < EvbMagic.Length)
{
return false;
}
var buffer = new byte[chunkSize + EvbMagic.Length];
long scanned = 0;
while (scanned < maxScan)
{
long readPos = startOffset + scanned;
int toRead = (int)Math.Min(buffer.Length, (startOffset + maxScan) - readPos);
if (toRead < EvbMagic.Length)
{
break;
}
fs.Seek(readPos, SeekOrigin.Begin);
int read = fs.Read(buffer, 0, toRead);
if (read < EvbMagic.Length)
{
break;
}
if (buffer.AsSpan(0, read).IndexOf(EvbMagic) >= 0)
{
return true;
}
scanned += chunkSize;
}
return false;
}
}
}
+62
View File
@@ -0,0 +1,62 @@
using System;
using System.IO;
using GameLauncher.Engines.Common;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// Backwards-compatible facade over <see cref="EvbDetectionHelper"/>.
///
/// The plan names the detection primitive <see cref="EvbDetectionHelper"/>, but
/// several callers (the engine module, the unpack service and the game scanner)
/// were written against the shorter <c>EvbDetector</c> API. This facade keeps those
/// call sites stable while the authoritative PE-signature logic lives in
/// <see cref="EvbDetectionHelper"/>.
///
/// This class is engine-local and has no side effects.
/// </summary>
public static class EvbDetector
{
/// <summary>
/// Returns true when the game directory holds an EVB packed executable
/// that can actually be unpacked (or a completed extraction of one).
///
/// Accepts only the following decisive signals:
/// 1. A top-level executable carrying both a decisive EVB PE section (.enigma1)
/// and the EVB virtual filesystem signature ("EVB\0"), so it is unpackable.
/// 2. An already-unpacked game (game-local "_evb_extracted" with a completion
/// marker). This is required because unpacking renames the original packed exe
/// to "*.glbak", after which the signature check alone would no longer detect
/// the game and its launch / icon resolution would break.
/// </summary>
public static bool IsEvbGame(string gameDirectory)
{
if (string.IsNullOrWhiteSpace(gameDirectory) || !Directory.Exists(gameDirectory))
{
return false;
}
// A completed extraction keeps the game recognized even without the packed exe.
if (EvbDetectionHelper.IsExtracted(gameDirectory))
{
return true;
}
return EvbDetectionHelper.FindEvbPackedExecutable(gameDirectory) != null;
}
/// <summary>
/// Resolves the executable that should be passed to the unpacker: the first
/// <c>.exe</c> in the folder that carries a decisive EVB signature, or null.
/// </summary>
public static string? FindPackedExecutable(string gameDirectory)
=> EvbDetectionHelper.FindEvbPackedExecutable(gameDirectory);
/// <summary>Returns true when the given executable is packed with EVB.</summary>
public static bool ContainsEvbSignature(string exePath)
=> EvbDetectionHelper.IsEvbPacked(exePath);
/// <summary>Re-exposes the engine name constant for callers that only reference this helper.</summary>
public static string EngineName => EngineDetectionHelper.EngineEvb;
}
}
+51
View File
@@ -0,0 +1,51 @@
using System;
using GameLauncher.Engines.Common;
using GameLauncher.Models;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// Engine module for Enigma Virtual Box (EVB) packed applications.
///
/// EVB is a generic packer: it can wrap a game built on any engine (RGSS, NW.js,
/// Wolf, Unity, ...). This module therefore acts as a *pre-stage* — it detects an
/// EVB-packed executable, unpacks it via the bundled evbunpack tool, and then lets
/// the caller re-detect the underlying engine from the unpacked content.
///
/// Per-game hacks never live here; they belong under
/// `Engines/Evb/Games/&lt;GameName&gt;/` and must not affect other games.
/// </summary>
public sealed class EvbEngineModule : IEngineModule
{
/// <inheritdoc />
public string EngineName => EngineDetectionHelper.EngineEvb;
/// <inheritdoc />
public bool Detect(string gameDirectory) => EvbDetector.IsEvbGame(gameDirectory);
/// <summary>
/// EVB is a packaging layer, not a game engine, so it has no script mod of its own.
/// Mods are applied by the underlying engine after unpacking.
/// </summary>
public bool ApplyMod(string gameDirectory, ModPluginDefinition plugin) => false;
/// <summary>EVB has no standalone mod state; nothing is ever "applied".</summary>
public bool IsModApplied(string gameDirectory) => false;
/// <inheritdoc />
public string ResolveToolPath(string toolFileName)
=> AppPathHelperBridge.Resolve(this.EngineName, toolFileName);
}
/// <summary>
/// Thin indirection so that <see cref="EvbEngineModule"/> can resolve engine tools
/// without taking a hard dependency on the concrete helper type in this file.
/// </summary>
internal static class AppPathHelperBridge
{
public static string Resolve(string engineName, string toolFileName)
=> Helpers.AppPathHelper.ResolveEngineTool(engineName, toolFileName)
?? throw new InvalidOperationException(
$"External tool '{toolFileName}' for engine '{engineName}' was not found.");
}
}
+438
View File
@@ -0,0 +1,438 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using GameLauncher.Engines.Common;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// Orchestrates detection and unpacking of Enigma Virtual Box (EVB) packed games,
/// then re-detects the real engine from the unpacked content.
///
/// Design (per AGENTS.md):
/// - Everything engine-local lives under `Engines/Evb/`.
/// - The original packed exe is backed up (`.glbak`) before being replaced, so the
/// operation can always be restored (Enigma recovery / manual restore).
/// - Unpacked output is written into a game-local `_evb_extracted` folder, so no
/// other game is ever affected.
/// - The bundled evbunpack tool (see <see cref="EvbUnpackerToolProvider"/>) does the work;
/// if it is missing the operation degrades gracefully (returns a failed result).
/// </summary>
public sealed class EvbUnpackService
{
/// <summary>Game-local folder that receives the unpacked files.</summary>
public const string ExtractedDirName = "_evb_extracted";
/// <summary>Marker file written last when an extraction finished successfully.</summary>
public const string CompleteMarkerName = ".evb_complete";
/// <summary>Backup suffix applied to the original packed executable.</summary>
public const string ExeBackupSuffix = ".glbak";
/// <summary>Result of an unpack attempt.</summary>
public sealed class UnpackResult
{
/// <summary>True when unpacking produced usable output.</summary>
public bool Success { get; init; }
/// <summary>Folder that contains the unpacked files (null on failure).</summary>
public string? OutputDirectory { get; init; }
/// <summary>Absolute path of the original packed executable (null when not found).</summary>
public string? SourceExePath { get; init; }
/// <summary>Absolute path of the backed-up original executable (null when no backup was made).</summary>
public string? BackupExePath { get; init; }
/// <summary>Engine name re-detected from the unpacked content (canonical name).</summary>
public string UnderlyingEngine { get; init; } = EngineDetectionHelper.EngineUnknown;
/// <summary>Human-readable message describing the outcome.</summary>
public string Message { get; init; } = string.Empty;
/// <summary>True when output was already present and re-used (idempotent skip).</summary>
public bool ReusedExisting { get; init; }
}
/// <summary>Game-local extraction folder for the given game root.</summary>
public static string GetExtractedDir(string gameRootDir)
=> Path.Combine(gameRootDir, ExtractedDirName);
/// <summary>Marker file path inside the extraction folder.</summary>
public static string GetCompleteMarkerPath(string outputDirectory)
=> Path.Combine(outputDirectory, CompleteMarkerName);
/// <summary>
/// Resolves the executable to launch from an unpacked output folder.
/// Prefers a well-known game exe name, then the first `.exe` found (top level first,
/// then one level deep). Returns null when nothing usable is found.
/// </summary>
public static string? FindLaunchExecutable(string? outputDirectory)
{
if (string.IsNullOrWhiteSpace(outputDirectory) || !Directory.Exists(outputDirectory))
{
return null;
}
try
{
// Preferred names commonly used by NW.js / RPG Maker / Tyrano bundles.
string[] preferred = ["Game.exe", "game.exe", "nw.exe", "Game_boxed.exe"];
foreach (var name in preferred)
{
var direct = Path.Combine(outputDirectory, name);
if (File.Exists(direct))
{
return direct;
}
}
// First exe at the top level, then one level deeper.
var top = Directory.GetFiles(outputDirectory, "*.exe", SearchOption.TopDirectoryOnly);
if (top.Length > 0)
{
return top[0];
}
foreach (var sub in Directory.GetDirectories(outputDirectory))
{
var nested = Directory.GetFiles(sub, "*.exe", SearchOption.TopDirectoryOnly);
if (nested.Length > 0)
{
return nested[0];
}
}
}
catch
{
// Ignore IO errors and fall back to no result.
}
return null;
}
/// <summary>
/// True when the game folder already holds a completed EVB extraction.
/// A non-empty output folder is NOT enough: the run may have been interrupted,
/// so the presence of the completion marker is required.
/// </summary>
public static bool IsExtractionComplete(string gameRootDir, out string? outputDirectory)
{
outputDirectory = GetExtractedDir(gameRootDir);
try
{
return Directory.Exists(outputDirectory) &&
File.Exists(GetCompleteMarkerPath(outputDirectory));
}
catch
{
return false;
}
}
/// <summary>
/// Unpacks the EVB-packed executable in the game folder and re-detects the
/// underlying engine. Idempotent: a completed prior extraction is re-used.
/// </summary>
/// <param name="gameRootDir">Game root folder containing the packed exe.</param>
/// <param name="progress">Optional progress sink.</param>
public UnpackResult Unpack(
string gameRootDir,
IProgress<string>? progress = null,
bool legacyFileSystem = false,
string? peVariant = null)
{
if (string.IsNullOrWhiteSpace(gameRootDir) || !Directory.Exists(gameRootDir))
{
return new UnpackResult { Success = false, Message = "ゲームフォルダが見つかりません。" };
}
// Idempotent: reuse a previous successful extraction.
if (IsExtractionComplete(gameRootDir, out var existingDir) && existingDir != null)
{
var reusedEngine = EngineDetectionHelper.RepairMisdetection(
existingDir, EngineDetectionHelper.EngineUnknown);
return new UnpackResult
{
Success = true,
OutputDirectory = existingDir,
UnderlyingEngine = reusedEngine,
ReusedExisting = true,
Message = $"既に解凍済みです({ExtractedDirName} を再利用)。",
};
}
var sourceExe = EvbDetectionHelper.FindEvbPackedExecutable(gameRootDir);
if (sourceExe == null)
{
return new UnpackResult
{
Success = false,
Message = "EVB パック済みの実行ファイルが見つかりませんでした。",
};
}
var toolPath = EvbUnpackerToolProvider.GetToolPath();
if (toolPath == null)
{
return new UnpackResult
{
Success = false,
SourceExePath = sourceExe,
Message = "解凍ツール (evbunpack) が見つかりません。Engines\\Evb\\Tools\\evbunpack\\ に配置してください。",
};
}
var outputDir = GetExtractedDir(gameRootDir);
try
{
// Start clean so partial output never mixes with a fresh run.
if (Directory.Exists(outputDir))
{
Directory.Delete(outputDir, recursive: true);
}
Directory.CreateDirectory(outputDir);
progress?.Report($"EVB 解凍を開始します: {Path.GetFileName(sourceExe)}");
var args = EvbUnpackerToolProvider.BuildArguments(sourceExe, outputDir, legacyFileSystem, peVariant);
if (!RunTool(toolPath, args, gameRootDir, progress, out var exitCode))
{
return new UnpackResult
{
Success = false,
SourceExePath = sourceExe,
OutputDirectory = outputDir,
Message = $"evbunpack の実行に失敗しました (exit code={exitCode})。",
};
}
if (!Directory.EnumerateFileSystemEntries(outputDir).Any())
{
return new UnpackResult
{
Success = false,
SourceExePath = sourceExe,
OutputDirectory = outputDir,
Message = "解凍は実行されましたが出力が空でした。PE バリアント (-pe 10_70 / 7_80) を変えて再試行してください。",
};
}
// Move the original packed exe out of the way so it is no longer recognized
// as an executable by the scanner (`.glbak` is not scanned as `*.exe`).
string? backupPath = null;
try
{
backupPath = sourceExe + ExeBackupSuffix;
if (File.Exists(backupPath))
{
// A previous backup exists; remove it so the move can succeed.
File.Delete(backupPath);
}
File.Move(sourceExe, backupPath);
progress?.Report($"元の実行ファイルを退避しました: {Path.GetFileName(backupPath)}");
}
catch (Exception ex)
{
progress?.Report($"バックアップに失敗しました(解凍自体は成功): {ex.Message}");
}
// Completion marker is written last, so an interrupted run is detectable.
File.WriteAllText(GetCompleteMarkerPath(outputDir), DateTime.UtcNow.ToString("o"));
// Re-detect the real engine from the unpacked content.
var underlying = ReDetectUnderlyingEngine(outputDir);
progress?.Report($"解凍後のエンジン再判定: {underlying}");
return new UnpackResult
{
Success = true,
OutputDirectory = outputDir,
SourceExePath = sourceExe,
BackupExePath = backupPath,
UnderlyingEngine = underlying,
Message = $"EVB 解凍が完了しました(再判定エンジン: {underlying})。",
};
}
catch (Exception ex)
{
return new UnpackResult
{
Success = false,
SourceExePath = sourceExe,
OutputDirectory = outputDir,
Message = $"EVB 解凍中にエラーが発生しました: {ex.Message}",
};
}
}
/// <summary>
/// Restores a previously unpacked game by removing the extraction output and
/// the backup copy is kept intact for the user. Returns true when something
/// was restored.
/// </summary>
public static bool Restore(string gameRootDir, IProgress<string>? progress = null)
{
if (string.IsNullOrWhiteSpace(gameRootDir) || !Directory.Exists(gameRootDir))
{
return false;
}
var restored = false;
var outputDir = GetExtractedDir(gameRootDir);
try
{
if (Directory.Exists(outputDir))
{
Directory.Delete(outputDir, recursive: true);
progress?.Report($"解凍フォルダを削除しました: {ExtractedDirName}");
restored = true;
}
}
catch (Exception ex)
{
progress?.Report($"解凍フォルダの削除に失敗しました: {ex.Message}");
}
// Restore the renamed backup back to its original `.exe` name.
try
{
foreach (var backup in Directory.GetFiles(gameRootDir, "*" + ExeBackupSuffix))
{
var original = backup[..^ExeBackupSuffix.Length];
if (!File.Exists(original))
{
File.Move(backup, original);
progress?.Report($"元の実行ファイルを復元しました: {Path.GetFileName(original)}");
restored = true;
}
}
}
catch (Exception ex)
{
progress?.Report($"元の実行ファイルの復元に失敗しました: {ex.Message}");
}
return restored;
}
/// <summary>
/// Runs the detection helper against the unpacked folder to determine the real engine.
/// </summary>
private static string ReDetectUnderlyingEngine(string outputDir)
{
var engine = EngineDetectionHelper.RepairMisdetection(
outputDir, EngineDetectionHelper.EngineUnknown);
// If the flat output still hides the engine, probe its immediate subfolders
// (evbunpack may keep the original layout one level down).
if (engine == EngineDetectionHelper.EngineUnknown)
{
try
{
foreach (var sub in Directory.GetDirectories(outputDir))
{
var candidate = EngineDetectionHelper.RepairMisdetection(
sub, EngineDetectionHelper.EngineUnknown);
if (candidate != EngineDetectionHelper.EngineUnknown)
{
return candidate;
}
}
}
catch { }
}
return engine;
}
/// <summary>Runs evbunpack with ArgumentList (no manual quoting) and waits for exit.</summary>
private static bool RunTool(
string toolPath,
System.Collections.Generic.IReadOnlyList<string> args,
string workingDir,
IProgress<string>? progress,
out int exitCode)
{
exitCode = -1;
try
{
var psi = new ProcessStartInfo
{
FileName = toolPath,
WorkingDirectory = workingDir,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach (var arg in args)
{
psi.ArgumentList.Add(arg);
}
// Throttle progress reporting: evbunpack emits thousands of lines on large
// bundles, and every Report() is marshalled onto the UI thread. Reporting
// each line saturates the UI and makes the window appear frozen, so only the
// latest line is reported at most a few times per second.
var throttle = Stopwatch.StartNew();
var lastReportUtc = DateTime.MinValue;
var lastLine = string.Empty;
void ReportThrottled(string? data)
{
if (string.IsNullOrWhiteSpace(data))
{
return;
}
lastLine = data!;
var now = DateTime.UtcNow;
if (now - lastReportUtc >= TimeSpan.FromMilliseconds(400))
{
lastReportUtc = now;
progress?.Report(data!);
}
}
using var proc = Process.Start(psi);
if (proc == null)
{
return false;
}
proc.OutputDataReceived += (_, e) => ReportThrottled(e.Data);
proc.ErrorDataReceived += (_, e) => ReportThrottled(e.Data);
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
// evbunpack can take a while on large bundles, but a shorter bound keeps the
// operation from looking hung if the tool never terminates.
if (!proc.WaitForExit(10 * 60 * 1000))
{
try { proc.Kill(entireProcessTree: true); } catch { }
progress?.Report("evbunpack がタイムアウトしました(10分)。処理を中断しました。");
exitCode = -1;
return false;
}
// Flush the final line that throttling may have skipped.
if (!string.IsNullOrWhiteSpace(lastLine))
{
progress?.Report(lastLine);
}
exitCode = proc.ExitCode;
return exitCode == 0;
}
catch (Exception ex)
{
progress?.Report($"evbunpack の起動に失敗しました: {ex.Message}");
return false;
}
}
}
}
+122
View File
@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GameLauncher.Helpers;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// Resolves the bundled evbunpack executable used to unpack Enigma Virtual Box (EVB)
/// packed applications.
///
/// Design notes (durable / reusable):
/// - The tool is bundled under `Engines\Evb\Tools\evbunpack\` (per-engine tools folder).
/// - Path resolution goes through <see cref="AppPathHelper"/> so that deployed, production
/// and source-tree layouts are all supported without hard-coding this machine's paths.
/// - CLI argument construction is kept in one place so callers never duplicate the
/// evbunpack invocation contract.
///
/// The evbunpack CLI contract:
/// evbunpack [-pe {10_70,9_70,7_80}] [--legacy-fs] &lt;input exe&gt; &lt;output folder&gt;
/// It restores both the packed virtual file system and the original PE executable.
/// </summary>
public static class EvbUnpackerToolProvider
{
/// <summary>Engine identifier passed to <see cref="AppPathHelper.GetEngineToolsDirectory"/>.</summary>
public const string EngineName = "Evb";
/// <summary>Bundled unpacker executable name.</summary>
public const string DefaultToolExeName = "evbunpack.exe";
/// <summary>Relative subfolder under Engines/Evb/Tools that holds the tool.</summary>
public const string ToolSubDirectory = "evbunpack";
/// <summary>
/// Default PE rebuild variant used when the caller does not specify one.
/// 9_70 works for Enigma Virtual Box 9.70 and 10.70/11.00 in most cases;
/// callers may override via <see cref="BuildArguments"/>.
/// </summary>
public const string DefaultPeVariant = "9_70";
/// <summary>Gets the engine tools directory (Engines/Evb/Tools).</summary>
public static string GetToolsDirectory()
{
return AppPathHelper.GetEngineToolsDirectory(EngineName);
}
/// <summary>Gets the bundled tool subfolder (Engines/Evb/Tools/evbunpack).</summary>
public static string GetToolDirectory()
{
return Path.Combine(GetToolsDirectory(), ToolSubDirectory);
}
/// <summary>
/// Resolves the evbunpack.exe path, or null when the tool is missing.
/// Prefers the bundled subfolder, then falls back to a flat layout inside the
/// engine tools folder (and the shared <see cref="AppPathHelper.ResolveEngineTool"/> probe).
/// </summary>
public static string? GetToolPath()
{
try
{
var candidates = new[]
{
Path.Combine(GetToolDirectory(), DefaultToolExeName),
Path.Combine(GetToolsDirectory(), DefaultToolExeName),
};
var found = candidates.FirstOrDefault(File.Exists);
if (found != null)
{
return found;
}
// Fall back to the shared per-engine resolver (checks deployed + dev layouts).
return AppPathHelper.ResolveEngineTool(
EngineName,
Path.Combine(ToolSubDirectory, DefaultToolExeName));
}
catch
{
return null;
}
}
/// <summary>True when the unpacker executable exists and is usable.</summary>
public static bool IsAvailable() => GetToolPath() != null;
/// <summary>
/// Builds the argument list for the unpacker CLI.
/// Emits the PE variant first, then the optional legacy switch, then the
/// input executable and the output folder. Values are raw (no quoting); callers
/// pass them through <c>ProcessStartInfo.ArgumentList</c> which handles escaping.
/// </summary>
/// <param name="inputExePath">Path to the EVB-packed executable.</param>
/// <param name="outputDirectory">Folder that receives the unpacked files.</param>
/// <param name="legacyFileSystem">When true, adds <c>--legacy-fs</c> for packer version 7.80.</param>
/// <param name="peVariant">PE rebuild variant (10_70/9_70/7_80); defaults to <see cref="DefaultPeVariant"/>.</param>
public static IReadOnlyList<string> BuildArguments(
string inputExePath,
string outputDirectory,
bool legacyFileSystem = false,
string? peVariant = null)
{
var args = new List<string>();
if (legacyFileSystem)
{
args.Add("--legacy-fs");
}
var variant = string.IsNullOrWhiteSpace(peVariant) ? DefaultPeVariant : peVariant.Trim();
args.Add("-pe");
args.Add(variant);
args.Add(inputExePath);
args.Add(outputDirectory);
return args;
}
}
}
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+62
View File
@@ -0,0 +1,62 @@
# evbunpack (bundled tool)
`evbunpack.exe` is a bundled, third-party unpacker used by the **Evb** engine module to
unpack applications protected with **Enigma Virtual Box**.
## Provenance
- Upstream project: https://github.com/mos9527/evbunpack
- Description: Enigma Virtual Box Unpacker / 解包・脱壳工具
- License: Apache-2.0 (see `LICENSE` in this folder for the full text)
- Repository status: **archived (read-only) by the owner on 2026-02-06**
- Version / release: bundled from the upstream Windows builds
(see the "For Windows Users: Builds are available here" link in the upstream README,
which points to the project's GitHub Releases page).
> **NOTE**: The binary in this folder is not committed as part of the normal source
> tree review flow. Place the upstream-release `evbunpack.exe` here before publishing.
> If the file is absent, the `Evb` engine module reports the tool as unavailable and
> skips unpacking instead of throwing (callers degrade gracefully).
## CLI usage
```
evbunpack [-h] [--log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [-l]
[--ignore-fs] [--ignore-pe] [--legacy-fs]
[-pe {10_70,9_70,7_80}] [--out-pe OUT_PE]
file output
```
- `file` : the packed `.exe` (input)
- `output` : the folder that receives the unpacked files (created if missing)
The tool restores **both** the virtual file system contents **and** the original PE
executable, in a single invocation.
### PE variant selection
| Packer version | Unpack with flags |
|----------------|------------------------------|
| 11.00 | `-pe 10_70` |
| 10.70 | `-pe 10_70` |
| 9.70 | `-pe 9_70` |
| 7.80 | `-pe 7_80 --legacy-fs` |
`EvbUnpackerToolProvider.BuildArguments` defaults to `-pe 9_70` and can be overridden
per call.
## Alternatives (when re-bundling is not possible)
- Install via PyPI: `pip install evbunpack` and run `python -m evbunpack ...`
(requires a Python runtime on the target machine).
- Build from source with `setup.py` / `pyinstaller` following the upstream README.
## Where it is used
- `Engines/Evb/EvbUnpackerToolProvider.cs` — resolves the executable and builds CLI arguments.
- `Engines/Evb/EvbUnpackService.cs` — orchestrates detection, unpacking and re-detection.
Resolution order (see `EvbUnpackerToolProvider.GetToolPath`):
1. `Engines/Evb/Tools/evbunpack/evbunpack.exe` (bundled layout, this folder)
2. `Engines/Evb/Tools/evbunpack.exe` (flat layout)
3. `AppPathHelper.ResolveEngineTool("Evb", "evbunpack/evbunpack.exe")` fallback probe.
Binary file not shown.
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using System.Text;
@@ -7,8 +7,10 @@ using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using GameLauncher.Models; using GameLauncher.Models;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Unity;
namespace GameLauncher.Services namespace GameLauncher.Engines.Nwjs
{ {
/// <summary> /// <summary>
/// ASAR アーカイブ内のファイルエントリ情報 /// ASAR アーカイブ内のファイルエントリ情報
@@ -168,7 +170,7 @@ namespace GameLauncher.Services
long packageJsonOffset = -1; long packageJsonOffset = -1;
long packageJsonSize = -1; long packageJsonSize = -1;
TraverseFiles(filesRoot, "", dataOffset, fs.Length, result, includeFileList, this.TraverseFiles(filesRoot, "", dataOffset, fs.Length, result, includeFileList,
ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize, ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize,
ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize); ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize);
@@ -272,7 +274,7 @@ namespace GameLauncher.Services
if (val.TryGetProperty("files", out var subFiles)) if (val.TryGetProperty("files", out var subFiles))
{ {
TraverseFiles(subFiles, path, dataOffset, fileLength, result, includeFileList, this.TraverseFiles(subFiles, path, dataOffset, fileLength, result, includeFileList,
ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize, ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize,
ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize); ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize);
} }
@@ -393,7 +395,7 @@ namespace GameLauncher.Services
// UNC パス (例: \\server\share\...) の場合 // UNC パス (例: \\server\share\...) の場合
if (normalized.StartsWith(@"\\", StringComparison.Ordinal)) if (normalized.StartsWith(@"\\", StringComparison.Ordinal))
{ {
return @"\\?\UNC\" + normalized.Substring(2); return @"\\?\UNC\" + normalized[2..];
} }
// 相対パスの場合は安全に絶対パスを取得してからプレフィックスを付与 // 相対パスの場合は安全に絶対パスを取得してからプレフィックスを付与
@@ -406,7 +408,7 @@ namespace GameLauncher.Services
} }
if (full.StartsWith(@"\\", StringComparison.Ordinal)) if (full.StartsWith(@"\\", StringComparison.Ordinal))
{ {
return @"\\?\UNC\" + full.Substring(2); return @"\\?\UNC\" + full[2..];
} }
return @"\\?\" + full; return @"\\?\" + full;
} }
@@ -445,7 +447,7 @@ namespace GameLauncher.Services
} }
// ヘッダ詳細解析 // ヘッダ詳細解析
var inspect = InspectAsar(targetAsar, includeFileList: true); var inspect = this.InspectAsar(targetAsar, includeFileList: true);
if (!inspect.IsValid || inspect.FileEntries.Count == 0) if (!inspect.IsValid || inspect.FileEntries.Count == 0)
{ {
return (false, "asar ファイルのヘッダ解析に失敗したか、ファイルが含まれていません。"); return (false, "asar ファイルのヘッダ解析に失敗したか、ファイルが含まれていません。");
@@ -501,8 +503,7 @@ namespace GameLauncher.Services
fs.Seek(dataOffset + entry.Offset, SeekOrigin.Begin); fs.Seek(dataOffset + entry.Offset, SeekOrigin.Begin);
long remaining = entry.Size; long remaining = entry.Size;
using (var outFs = new FileStream(destFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) using var outFs = new FileStream(destFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
{
while (remaining > 0) while (remaining > 0)
{ {
int toRead = (int)Math.Min(remaining, buffer.Length); int toRead = (int)Math.Min(remaining, buffer.Length);
@@ -516,7 +517,6 @@ namespace GameLauncher.Services
progress?.Report((extractedBytes, totalBytes, i + 1, totalFiles, Path.GetFileName(entry.RelativePath))); progress?.Report((extractedBytes, totalBytes, i + 1, totalFiles, Path.GetFileName(entry.RelativePath)));
} }
} }
}
catch (Exception fileEx) catch (Exception fileEx)
{ {
// 予約文字や排他ロック等の例外が発生した場合、解凍全体を止めずに警告として記録 // 予約文字や排他ロック等の例外が発生した場合、解凍全体を止めずに警告として記録
@@ -571,7 +571,7 @@ namespace GameLauncher.Services
: asarPath + AsarBackupSuffix; : asarPath + AsarBackupSuffix;
var originalAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase) var originalAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase)
? asarPath.Substring(0, asarPath.Length - AsarBackupSuffix.Length) ? asarPath[..^AsarBackupSuffix.Length]
: asarPath; : asarPath;
string extExtractedDir = ToExtendedPath(extractedDir); string extExtractedDir = ToExtendedPath(extractedDir);
+332
View File
@@ -0,0 +1,332 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Windows.Media;
using GameLauncher.Engines.Common;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Unity;
using GameLauncher.Models;
namespace GameLauncher.Engines.Nwjs
{
/// <summary>
/// 汎用 NW.js (Node-Webkit) アプリケーション/ゲームの検出およびアイテム生成を行うヘルパークラス
/// </summary>
public static class NwjsDetector
{
private static readonly HashSet<string> ExcludedExeNames = new(StringComparer.OrdinalIgnoreCase)
{
"notification_helper.exe",
"crashpad_handler.exe",
"elevate.exe"
};
/// <summary>
/// 指定されたディレクトリが汎用 NW.js ゲームであるかを判定します。
/// ツクール(MV/MZ/RGSS)、ティラノスクリプト、ウディタ、SRPG Studio など既存エンジン形式は除外します。
/// </summary>
/// <param name="dirPath">対象ディレクトリパス</param>
/// <returns>NW.js ゲームであれば true</returns>
public static bool IsNwjsGame(string dirPath)
{
try
{
if (string.IsNullOrWhiteSpace(dirPath) || !Directory.Exists(dirPath))
{
return false;
}
var packageJsonPath = Path.Combine(dirPath, "package.json");
if (!File.Exists(packageJsonPath))
{
return false;
}
// 既存の他エンジン判定(ツクール・ティラノ・ウディタ・SRPG)を最優先で除外
if (Directory.Exists(Path.Combine(dirPath, "www")) ||
File.Exists(Path.Combine(dirPath, "data", "System.json")) ||
File.Exists(Path.Combine(dirPath, "Game.ini")) ||
Directory.Exists(Path.Combine(dirPath, "tyrano")) ||
Directory.GetFiles(dirPath, "*.tjs", SearchOption.TopDirectoryOnly).Length > 0 ||
Directory.GetFiles(dirPath, "*.wolf", SearchOption.TopDirectoryOnly).Length > 0 ||
File.Exists(Path.Combine(dirPath, "data.dts")))
{
return false;
}
// NW.js の痕跡を確認
if (File.Exists(Path.Combine(dirPath, "nw.dll")) ||
File.Exists(Path.Combine(dirPath, "nw.exe")) ||
File.Exists(Path.Combine(dirPath, "resources.pak")) ||
File.Exists(Path.Combine(dirPath, "node.dll")) ||
Directory.Exists(Path.Combine(dirPath, "nwjs")))
{
return true;
}
// package.json に main や window 記述があるか確認
if (TryReadPackageJson(dirPath, out _, out _, out var main, out _))
{
if (!string.IsNullOrWhiteSpace(main) && File.Exists(Path.Combine(dirPath, main)))
{
return true;
}
}
}
catch
{
return false;
}
return false;
}
/// <summary>
/// 指定ディレクトリ内の NW.js ゲームを検出し、TkoolGameItem を生成します。
/// </summary>
/// <param name="dirPath">ゲームフォルダの絶対パス</param>
/// <param name="folderName">フォルダ名</param>
/// <param name="folderModified">フォルダ更新日時</param>
/// <param name="iconLoader">アイコン読み込み関数</param>
/// <returns>検出されたゲームアイテム。該当しない場合は null</returns>
public static TkoolGameItem? DetectNwjsGame(
string dirPath,
string folderName,
DateTime? folderModified,
Func<string?, string?, ImageSource?> iconLoader)
{
try
{
if (!IsNwjsGame(dirPath))
{
return null;
}
TryReadPackageJson(dirPath, out var windowTitle, out var packageName, out var mainFile, out var iconRelPath);
// タイトルの決定: window.title > index.html の <title> > package.json の name > フォルダ名
string title = string.Empty;
if (!string.IsNullOrWhiteSpace(windowTitle))
{
title = windowTitle.Trim();
}
if (string.IsNullOrWhiteSpace(title))
{
var htmlPath = !string.IsNullOrWhiteSpace(mainFile)
? Path.Combine(dirPath, mainFile)
: Path.Combine(dirPath, "index.html");
title = ExtractHtmlTitle(htmlPath);
}
if (string.IsNullOrWhiteSpace(title) && !string.IsNullOrWhiteSpace(packageName))
{
title = packageName.Trim();
}
if (string.IsNullOrWhiteSpace(title))
{
title = folderName;
}
// 実行ファイルの探索
var exePath = FindNwjsExecutable(dirPath, title, packageName);
// アイコンの取得
ImageSource? icon = null;
if (iconLoader != null)
{
icon = iconLoader(exePath, dirPath);
}
return new TkoolGameItem
{
Title = title,
FolderName = folderName,
RootDirectory = dirPath,
ExecutablePath = exePath ?? string.Empty,
PluginsJsPath = string.Empty,
PluginsDirPath = string.Empty,
EngineType = TkoolEngineType.Nwjs,
IsModded = false,
ApplyMod = false,
IconImage = icon,
FolderLastModified = folderModified
};
}
catch
{
return null;
}
}
/// <summary>
/// NW.js ゲーム用の実行可能ファイル(.exe)を探索します。
/// notification_helper.exe などの Chromium 内部ユーティリティを除外し、ゲーム本体の exe を特定します。
/// </summary>
/// <param name="dirPath">ディレクトリパス</param>
/// <param name="title">ゲームタイトル</param>
/// <param name="packageName">package.json の name</param>
/// <returns>実行ファイルのパス。見つからない場合は null</returns>
public static string? FindNwjsExecutable(string dirPath, string? title, string? packageName)
{
try
{
var exes = Directory.GetFiles(dirPath, "*.exe", SearchOption.TopDirectoryOnly)
.Where(f =>
{
var fileName = Path.GetFileName(f);
if (fileName.StartsWith("unins", StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (ExcludedExeNames.Contains(fileName))
{
return false;
}
return true;
})
.ToList();
if (exes.Count == 0)
{
return null;
}
if (exes.Count == 1)
{
return exes[0];
}
// 優先度1: タイトル名またはパッケージ名が含まれる実行ファイル
if (!string.IsNullOrWhiteSpace(title))
{
var match = exes.FirstOrDefault(f => Path.GetFileNameWithoutExtension(f).Contains(title, StringComparison.OrdinalIgnoreCase));
if (match != null)
{
return match;
}
}
if (!string.IsNullOrWhiteSpace(packageName))
{
var match = exes.FirstOrDefault(f => Path.GetFileNameWithoutExtension(f).Contains(packageName, StringComparison.OrdinalIgnoreCase));
if (match != null)
{
return match;
}
}
// 優先度2: Game.exe または nw.exe
var gameExe = exes.FirstOrDefault(f => string.Equals(Path.GetFileName(f), "Game.exe", StringComparison.OrdinalIgnoreCase));
if (gameExe != null)
{
return gameExe;
}
var nwExe = exes.FirstOrDefault(f => string.Equals(Path.GetFileName(f), "nw.exe", StringComparison.OrdinalIgnoreCase));
if (nwExe != null)
{
return nwExe;
}
// 優先度3: 候補の先頭
return exes[0];
}
catch
{
return null;
}
}
/// <summary>
/// package.json を読み込み、主要な設定値を抽出します。
/// </summary>
private static bool TryReadPackageJson(
string dirPath,
out string? windowTitle,
out string? name,
out string? main,
out string? iconRelPath)
{
windowTitle = null;
name = null;
main = null;
iconRelPath = null;
try
{
var packageJsonPath = Path.Combine(dirPath, "package.json");
if (!File.Exists(packageJsonPath))
{
return false;
}
var json = File.ReadAllText(packageJsonPath);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.TryGetProperty("name", out var nameProp) && nameProp.ValueKind == JsonValueKind.String)
{
name = nameProp.GetString();
}
if (root.TryGetProperty("main", out var mainProp) && mainProp.ValueKind == JsonValueKind.String)
{
main = mainProp.GetString();
}
if (root.TryGetProperty("window", out var winProp) && winProp.ValueKind == JsonValueKind.Object)
{
if (winProp.TryGetProperty("title", out var titleProp) && titleProp.ValueKind == JsonValueKind.String)
{
windowTitle = titleProp.GetString();
}
if (winProp.TryGetProperty("icon", out var iconProp) && iconProp.ValueKind == JsonValueKind.String)
{
iconRelPath = iconProp.GetString();
}
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// HTML ファイルから title タグのテキストを抽出します。
/// </summary>
private static string ExtractHtmlTitle(string htmlPath)
{
try
{
if (!File.Exists(htmlPath))
{
return string.Empty;
}
var html = File.ReadAllText(htmlPath);
var match = Regex.Match(html, @"<title[^>]*>(.*?)</title>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (match.Success)
{
var title = match.Groups[1].Value.Trim();
return System.Net.WebUtility.HtmlDecode(title);
}
}
catch
{
}
return string.Empty;
}
}
}
@@ -0,0 +1,115 @@
using System;
using System.IO;
using GameLauncher.Engines.Tkool;
namespace GameLauncher.Engines.Rgss.Games.IiniTitleRepair
{
/// <summary>
/// Game-specific handling for RPG Maker RGSS titles whose cached title was
/// stored corrupted (mojibake). The title is re-read from Game.ini using an
/// encoding-safe reader.
///
/// This logic is isolated per engine/per concern so that it applies only to
/// the RGSS title-repair case and cannot affect any other engine's games.
/// Call sites invoke it explicitly (<see cref="Fix"/>).
/// </summary>
public static class GameIniTitleRepair
{
/// <summary>
/// Repairs a mojibake RGSS title stored in the cache by re-reading the
/// "Title=" entry from Game.ini (direct, or one level down).
/// </summary>
public static void Fix(TkoolGameItem tg)
{
try
{
string? iniPath = null;
var directIni = Path.Combine(tg.RootDirectory, "Game.ini");
if (File.Exists(directIni))
{
iniPath = directIni;
}
else if (Directory.Exists(tg.RootDirectory))
{
foreach (var sub in Directory.GetDirectories(tg.RootDirectory))
{
var subIni = Path.Combine(sub, "Game.ini");
if (File.Exists(subIni))
{
iniPath = subIni;
break;
}
}
}
if (iniPath == null)
{
return;
}
foreach (var line in ReadIniLinesSafe(iniPath))
{
var trim = line.Trim();
if (trim.StartsWith("Title=", StringComparison.OrdinalIgnoreCase))
{
var val = trim[6..].Trim();
if (!string.IsNullOrWhiteSpace(val) && !val.Contains('\uFFFD'))
{
tg.Title = val;
break;
}
}
}
}
catch { }
}
/// <summary>
/// Reads an INI file line-by-line, auto-detecting BOM (UTF-8/UTF-16 LE)
/// and falling back to Shift_JIS (CP932), which is the standard for
/// RPG Maker VX/VX Ace and Wolf RPG.
/// </summary>
public static string[] ReadIniLinesSafe(string filePath)
{
try
{
if (!File.Exists(filePath)) return [];
byte[] bytes = File.ReadAllBytes(filePath);
if (bytes.Length == 0) return [];
// 1. UTF-8 BOM (EF BB BF)
if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)
{
var text = System.Text.Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
return text.Split(["\r\n", "\r", "\n"], StringSplitOptions.None);
}
// 2. UTF-16 LE BOM (FF FE)
if (bytes.Length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE)
{
var text = System.Text.Encoding.Unicode.GetString(bytes, 2, bytes.Length - 2);
return text.Split(["\r\n", "\r", "\n"], StringSplitOptions.None);
}
// 3. Shift_JIS (CP932)
System.Text.Encoding encoding;
try
{
encoding = System.Text.Encoding.GetEncoding(932);
}
catch
{
encoding = System.Text.Encoding.GetEncoding("shift_jis");
}
var decoded = encoding.GetString(bytes);
return decoded.Split(["\r\n", "\r", "\n"], StringSplitOptions.None);
}
catch
{
return [];
}
}
}
}
File diff suppressed because it is too large. Load diff
+321
View File
@@ -0,0 +1,321 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GameLauncher.Helpers;
namespace GameLauncher.Engines.Rgss
{
/// <summary>
/// SRPG Studio の data.dts アーカイブ解凍・抽出および再構築(再パック)サービス
/// 外部ツール Engines/Rgss/Tools/SRPG_Unpacker.exe を利用して安全に展開・再構築を行います。
/// バックアップはすべて Z:\自作ソフト\GameLauncher\Backups に保存されます。
/// </summary>
public class SrpgArchiveService
{
public const string ExtractedDirName = "data_extracted";
public const string ArchiveFileName = "data.dts";
public const string ToolExeName = "SRPG_Unpacker.exe";
/// <summary>
/// SRPG_Unpacker.exe のフルパスを取得します(エンジン別ツールフォルダを優先)。
/// </summary>
public static string? GetToolPath()
{
return AppPathHelper.ResolveEngineTool("Rgss", ToolExeName);
}
/// <summary>
/// data.dts アーカイブが存在するか判定します。
/// </summary>
public static bool HasDataDts(string gameDir)
{
return File.Exists(Path.Combine(gameDir, ArchiveFileName));
}
/// <summary>
/// 解凍済みフォルダ (data_extracted または Script & Plugin) が存在するか判定します。
/// </summary>
public static bool IsExtracted(string gameDir)
{
var extractedDir = Path.Combine(gameDir, ExtractedDirName);
if (Directory.Exists(extractedDir)) return true;
var scriptDir = Path.Combine(gameDir, "Script");
var pluginDir = Path.Combine(gameDir, "Plugin");
return Directory.Exists(scriptDir) && Directory.Exists(pluginDir);
}
/// <summary>
/// 解凍先フォルダパスを取得します。
/// </summary>
public static string GetExtractedDirectory(string gameDir)
{
var extractedDir = Path.Combine(gameDir, ExtractedDirName);
if (Directory.Exists(extractedDir)) return extractedDir;
var scriptDir = Path.Combine(gameDir, "Script");
if (Directory.Exists(scriptDir)) return gameDir;
return extractedDir;
}
/// <summary>
/// data.dts を解凍・抽出します。
/// 実行前に data.dts を Backups フォルダにバックアップします。
/// </summary>
public async Task<(bool Success, string Message)> UnpackDataDtsAsync(string gameDir, IProgress<string>? progress = null)
{
return await Task.Run(() =>
{
try
{
var dtsPath = Path.Combine(gameDir, ArchiveFileName);
if (!File.Exists(dtsPath))
{
return (false, "data.dts が見つかりません。");
}
var tool = GetToolPath();
if (tool == null)
{
return (false, $"解凍ツール ({ToolExeName}) が Tools フォルダに見つかりません。");
}
progress?.Report("data.dts のバックアップを作成中...");
var backupDir = AppPathHelper.GetBackupsDirectory();
var gameFolderName = Path.GetFileName(gameDir.TrimEnd('\\', '/'));
var timeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var targetBackupDir = Path.Combine(backupDir, "SRPGStudio", $"{gameFolderName}_{timeStamp}");
Directory.CreateDirectory(targetBackupDir);
var backupFile = Path.Combine(targetBackupDir, ArchiveFileName);
File.Copy(dtsPath, backupFile, overwrite: true);
var outDir = Path.Combine(gameDir, ExtractedDirName);
if (!Directory.Exists(outDir))
{
Directory.CreateDirectory(outDir);
}
progress?.Report("SRPG_Unpacker でアーカイブを解凍中...");
var psi = new ProcessStartInfo
{
FileName = tool,
Arguments = $"\"{dtsPath}\" -o \"{outDir}\"",
WorkingDirectory = gameDir,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using var proc = Process.Start(psi);
if (proc == null)
{
return (false, "解凍プロセスの起動に失敗しました。");
}
string stdout = proc.StandardOutput.ReadToEnd();
string stderr = proc.StandardError.ReadToEnd();
proc.WaitForExit();
if (proc.ExitCode == 0)
{
progress?.Report("解凍が正常に完了しました。");
return (true, $"data.dts を正常に {ExtractedDirName} フォルダへ展開しました。\n(バックアップ: {backupFile})");
}
else
{
return (false, $"解凍処理でエラーが発生しました。(Code: {proc.ExitCode})\n{stderr}\n{stdout}");
}
}
catch (Exception ex)
{
return (false, $"解凍処理中に例外が発生しました: {ex.Message}");
}
});
}
/// <summary>
/// 解凍されたフォルダから data.dts を再構築(再パック)します。
/// </summary>
public async Task<(bool Success, string Message)> RepackDataDtsAsync(string gameDir, IProgress<string>? progress = null)
{
return await Task.Run(() =>
{
try
{
var extractedDir = GetExtractedDirectory(gameDir);
if (!Directory.Exists(extractedDir))
{
return (false, "展開済みフォルダが見つかりません。先に解凍を行ってください。");
}
var tool = GetToolPath();
if (tool == null)
{
return (false, $"ツール ({ToolExeName}) が見つかりません。");
}
var dtsPath = Path.Combine(gameDir, ArchiveFileName);
var tempOutputDts = Path.Combine(gameDir, "data_temp_repack.dts");
progress?.Report("アーカイブを再構築(再パック)中...");
var psi = new ProcessStartInfo
{
FileName = tool,
Arguments = $"\"{extractedDir}\" -o \"{tempOutputDts}\"",
WorkingDirectory = gameDir,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using var proc = Process.Start(psi);
if (proc == null)
{
return (false, "再パックプロセスの起動に失敗しました。");
}
string stdout = proc.StandardOutput.ReadToEnd();
string stderr = proc.StandardError.ReadToEnd();
proc.WaitForExit();
if (proc.ExitCode == 0 && File.Exists(tempOutputDts))
{
// 既存の data.dts をバックアップした上で置き換え
if (File.Exists(dtsPath))
{
var backupDir = AppPathHelper.GetBackupsDirectory();
var gameFolderName = Path.GetFileName(gameDir.TrimEnd('\\', '/'));
var timeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var targetBackupDir = Path.Combine(backupDir, "SRPGStudio", $"{gameFolderName}_{timeStamp}_repack_prev");
Directory.CreateDirectory(targetBackupDir);
File.Copy(dtsPath, Path.Combine(targetBackupDir, ArchiveFileName), overwrite: true);
File.Delete(dtsPath);
}
File.Move(tempOutputDts, dtsPath);
progress?.Report("再パック完了。data.dts を更新しました。");
return (true, "data.dts の再構築(再パック)が正常に完了しました。");
}
else
{
if (File.Exists(tempOutputDts)) File.Delete(tempOutputDts);
return (false, $"再パック処理でエラーが発生しました。(Code: {proc.ExitCode})\n{stderr}\n{stdout}");
}
}
catch (Exception ex)
{
return (false, $"再パック処理中に例外が発生しました: {ex.Message}");
}
});
}
/// <summary>
/// 最新のバックアップから data.dts を復元します。
/// </summary>
public async Task<(bool Success, string Message)> RevertBackupAsync(string gameDir)
{
return await Task.Run(() =>
{
try
{
var backupDir = AppPathHelper.GetBackupsDirectory();
var gameFolderName = Path.GetFileName(gameDir.TrimEnd('\\', '/'));
var targetBase = Path.Combine(backupDir, "SRPGStudio");
if (!Directory.Exists(targetBase))
{
return (false, "バックアップフォルダが見つかりません。");
}
// gameFolderName で始まるフォルダのうち最も新しいものを検索
var dirs = Directory.GetDirectories(targetBase, $"{gameFolderName}_*")
.OrderByDescending(d => d)
.ToList();
if (dirs.Count == 0)
{
return (false, "該当するバックアップが見つかりません。");
}
foreach (var d in dirs)
{
var bakFile = Path.Combine(d, ArchiveFileName);
if (File.Exists(bakFile))
{
var dstFile = Path.Combine(gameDir, ArchiveFileName);
File.Copy(bakFile, dstFile, overwrite: true);
return (true, $"バックアップ ({Path.GetFileName(d)}) から data.dts を正常に復元しました。");
}
}
return (false, "バックアップファイルが見つかりませんでした。");
}
catch (Exception ex)
{
return (false, $"復元処理中に例外が発生しました: {ex.Message}");
}
});
}
/// <summary>
/// 解凍されたフォルダ (data_extracted) を Backups フォルダへ安全に退避し、
/// ゲームディレクトリ内を元の data.dts のみの状態に復元します。
/// </summary>
public (bool Success, string Message) RestoreExtractedState(string gameDir)
{
try
{
var extractedDir = Path.Combine(gameDir, ExtractedDirName);
if (!Directory.Exists(extractedDir))
{
return (true, "解凍フォルダは存在しません。");
}
var backupDir = AppPathHelper.GetBackupsDirectory();
var gameFolderName = Path.GetFileName(gameDir.TrimEnd('\\', '/'));
var timeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var targetBackupDir = Path.Combine(backupDir, "SRPGStudio", $"{gameFolderName}_{timeStamp}_extracted_evacuated");
Directory.CreateDirectory(targetBackupDir);
var dst = Path.Combine(targetBackupDir, ExtractedDirName);
// ディレクトリ移動(別ドライブ考慮でフォールバック)
try
{
Directory.Move(extractedDir, dst);
}
catch
{
// コピー後に削除
CopyDirectory(extractedDir, dst);
Directory.Delete(extractedDir, true);
}
return (true, $"解凍フォルダ ({ExtractedDirName}) を Backups フォルダへ退避しました。");
}
catch (Exception ex)
{
return (false, $"解凍フォルダ退避中にエラーが発生しました: {ex.Message}");
}
}
private static void CopyDirectory(string sourceDir, string targetDir)
{
Directory.CreateDirectory(targetDir);
foreach (var file in Directory.GetFiles(sourceDir))
{
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)), true);
}
foreach (var subDir in Directory.GetDirectories(sourceDir))
{
CopyDirectory(subDir, Path.Combine(targetDir, Path.GetFileName(subDir)));
}
}
}
}
+755
View File
@@ -0,0 +1,755 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using GameLauncher.Helpers;
using GameLauncher.Models;
using GameLauncher.Engines.Tkool;
namespace GameLauncher.Engines.Rgss
{
/// <summary>
/// SRPG Studio ゲームの機能拡張(プロキシDLL・倍速機能、Modスクリプト注入・再構築)サービス
/// </summary>
public class SrpgModService
{
public const string ProxyDllName = "version.dll";
public const string ConfigFileName = "speedhack_config.json";
public const string ModScriptFileName = "99_AntigravityMod.js";
private readonly SrpgArchiveService _archiveService = new();
/// <summary>
/// プロキシDLL(version.dll)および設定ファイルをゲームディレクトリに配置し、倍速機能を有効化します。
/// </summary>
public bool EnableProxyDll(string gameDir, double speedMultiplier = 3.0)
{
try
{
// エンジン別ツールフォルダ (Engines\Rgss\Tools\speedhack-i686\version.dll) を優先解決
var srcDll = AppPathHelper.ResolveEngineTool("Rgss", Path.Combine("speedhack-i686", ProxyDllName)) ?? string.Empty;
if (!File.Exists(srcDll))
{
return false;
}
var dstDll = Path.Combine(gameDir, ProxyDllName);
File.Copy(srcDll, dstDll, overwrite: true);
var config = new
{
speed = Math.Max(1.0, speedMultiplier),
toggle_key = "F6",
fast_key = "Control",
fast_multiplier = 5.0
};
var json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(Path.Combine(gameDir, ConfigFileName), json, Encoding.UTF8);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// プロキシDLLおよび設定ファイルを削除し、通常動作に戻します。
/// </summary>
public bool DisableProxyDll(string gameDir)
{
try
{
var dstDll = Path.Combine(gameDir, ProxyDllName);
if (File.Exists(dstDll))
{
File.Delete(dstDll);
}
var configFile = Path.Combine(gameDir, ConfigFileName);
if (File.Exists(configFile))
{
File.Delete(configFile);
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// プロキシDLLが適用されているか確認します。
/// </summary>
public static bool IsProxyDllEnabled(string gameDir)
{
return File.Exists(Path.Combine(gameDir, ProxyDllName));
}
/// <summary>
/// プラグイン改造が適用されているか確認します。
/// </summary>
public static bool IsModScriptApplied(string gameDir)
{
var extractedDir = SrpgArchiveService.GetExtractedDirectory(gameDir);
var modJs = Path.Combine(extractedDir, "Plugin", ModScriptFileName);
return File.Exists(modJs);
}
/// <summary>
/// 選択されたModオプションから JavaScript スクリプトコードを生成します。
/// </summary>
public string GenerateModScript(TkoolGameItem item)
{
var sb = new StringBuilder();
sb.AppendLine("/* ========================================================================= */");
sb.AppendLine("/* Antigravity GameLauncher - SRPG Studio 統合拡張プラグイン */");
sb.AppendLine("/* ========================================================================= */");
sb.AppendLine("(function() {");
sb.AppendLine(" 'use strict';");
sb.AppendLine();
// 1. 武器・アイテム耐久度無限
if (item.IsPluginEnabled("SrpgInfDurability"))
{
sb.AppendLine(" // [チート] 武器・アイテム耐久度無限");
sb.AppendLine(" if (typeof ItemControl !== 'undefined') {");
sb.AppendLine(" if (ItemControl.decreaseLimit) {");
sb.AppendLine(" var _orig_decreaseLimit = ItemControl.decreaseLimit;");
sb.AppendLine(" ItemControl.decreaseLimit = function(unit, item) {");
sb.AppendLine(" if (unit && unit.getUnitType && unit.getUnitType() === UnitType.PLAYER) {");
sb.AppendLine(" return; // 味方ユニットの耐久度は消費しない");
sb.AppendLine(" }");
sb.AppendLine(" return _orig_decreaseLimit.call(this, unit, item);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (ItemControl.isItemBroken) {");
sb.AppendLine(" ItemControl.isItemBroken = function(item) {");
sb.AppendLine(" return false; // 武器破損を防止");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" if (typeof DataConfig !== 'undefined' && DataConfig.isWeaponInfinity) {");
sb.AppendLine(" DataConfig.isWeaponInfinity = function() { return true; };");
sb.AppendLine(" }");
sb.AppendLine();
}
// 2. 獲得経験値最大化(即レベルアップ / 100Exp固定)
if (item.IsPluginEnabled("SrpgExpBoost"))
{
sb.AppendLine(" // [チート] 獲得経験値最大化 (戦闘・アイテム使用時即レベルアップ)");
sb.AppendLine(" if (typeof ExperienceCalculator !== 'undefined') {");
sb.AppendLine(" if (ExperienceCalculator.calculateExperience) {");
sb.AppendLine(" ExperienceCalculator.calculateExperience = function(data) {");
sb.AppendLine(" return 100;");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (ExperienceCalculator.getBestExperience) {");
sb.AppendLine(" ExperienceCalculator.getBestExperience = function(unit, exp) {");
sb.AppendLine(" return 100;");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
}
// 共通ユーティリティ: 味方ユニット判定関数
sb.AppendLine(" // [共通] 味方ユニット判定 (敵以外はすべて味方・自軍として扱う)");
sb.AppendLine(" function __antigravity_isPlayerSide(unit) {");
sb.AppendLine(" if (!unit) return false;");
sb.AppendLine(" try {");
sb.AppendLine(" var ut = (typeof unit.getUnitType === 'function') ? unit.getUnitType() : -1;");
sb.AppendLine(" // 敵 (1 = UnitType.ENEMY) 以外は味方/自軍とみなす");
sb.AppendLine(" if (ut === 1) return false;");
sb.AppendLine(" return true;");
sb.AppendLine(" } catch (e) { return true; }");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" // [共通] 移動力ブースト対象判定 (敵以外 = 自軍・同盟軍。敵は除外)");
sb.AppendLine(" function __antigravity_isMovTarget(unit) {");
sb.AppendLine(" if (!unit) return false;");
sb.AppendLine(" try {");
sb.AppendLine(" return (typeof unit.getUnitType === 'function') && unit.getUnitType() !== 1;");
sb.AppendLine(" } catch (e) { return false; }");
sb.AppendLine(" }");
sb.AppendLine();
// 3. 所持金最大化 & ターン開始時全回復
bool hasMaxGold = item.IsPluginEnabled("SrpgMaxGold");
bool hasRecoverHp = item.IsPluginEnabled("SrpgTurnRecoverHp");
if (hasMaxGold || hasRecoverHp)
{
sb.AppendLine(" // [チート] 味方全回復関数 & 所持金最大化関数");
if (hasRecoverHp)
{
sb.AppendLine(" function __antigravity_healAllUnits() {");
sb.AppendLine(" try {");
sb.AppendLine(" var processedUnits = [];");
sb.AppendLine(" var unitList = [];");
sb.AppendLine();
sb.AppendLine(" // 1. 各種リストから自軍ユニットを収集");
sb.AppendLine(" if (typeof PlayerList !== 'undefined') {");
sb.AppendLine(" if (typeof PlayerList.getSortieList === 'function') {");
sb.AppendLine(" var sList = PlayerList.getSortieList();");
sb.AppendLine(" if (sList && sList.getCount) { for (var i = 0; i < sList.getCount(); i++) unitList.push(sList.getData(i)); }");
sb.AppendLine(" }");
sb.AppendLine(" if (typeof PlayerList.getAliveList === 'function') {");
sb.AppendLine(" var aList = PlayerList.getAliveList();");
sb.AppendLine(" if (aList && aList.getCount) { for (var i = 0; i < aList.getCount(); i++) unitList.push(aList.getData(i)); }");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine(" if (typeof TurnControl !== 'undefined' && typeof TurnControl.getActorList === 'function') {");
sb.AppendLine(" var tList = TurnControl.getActorList();");
sb.AppendLine(" if (tList && tList.getCount) { for (var i = 0; i < tList.getCount(); i++) unitList.push(tList.getData(i)); }");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" // 2. マップ上の全座標を走査 (ゲスト・NPC・未登録ユニットも100%捕捉)");
sb.AppendLine(" if (typeof CurrentMap !== 'undefined' && typeof PosChecker !== 'undefined') {");
sb.AppendLine(" try {");
sb.AppendLine(" var mapW = CurrentMap.getWidth();");
sb.AppendLine(" var mapH = CurrentMap.getHeight();");
sb.AppendLine(" for (var mx = 0; mx < mapW; mx++) {");
sb.AppendLine(" for (var my = 0; my < mapH; my++) {");
sb.AppendLine(" var mu = PosChecker.getUnitFromPos(mx, my);");
sb.AppendLine(" if (mu) unitList.push(mu);");
sb.AppendLine(" } ");
sb.AppendLine(" }");
sb.AppendLine(" } catch (eScan) {}");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" // 3. 敵以外の全ユニットのHPを最大化");
sb.AppendLine(" for (var j = 0; j < unitList.length; j++) {");
sb.AppendLine(" var u = unitList[j];");
sb.AppendLine(" if (!u || typeof u.setHp !== 'function' || typeof u.getId !== 'function') continue;");
sb.AppendLine(" var uid = u.getId();");
sb.AppendLine(" if (processedUnits.indexOf(uid) !== -1) continue;");
sb.AppendLine(" processedUnits.push(uid);");
sb.AppendLine();
sb.AppendLine(" if (!__antigravity_isPlayerSide(u)) continue;");
sb.AppendLine();
sb.AppendLine(" try {");
sb.AppendLine(" var maxHp = 0;");
sb.AppendLine(" if (typeof ParamBonus !== 'undefined' && typeof ParamBonus.getMhp === 'function') {");
sb.AppendLine(" maxHp = ParamBonus.getMhp(u);");
sb.AppendLine(" }");
sb.AppendLine(" if (maxHp <= 0 && typeof RealBonus !== 'undefined' && typeof RealBonus.getMhp === 'function') {");
sb.AppendLine(" maxHp = RealBonus.getMhp(u);");
sb.AppendLine(" }");
sb.AppendLine(" if (maxHp <= 0) maxHp = 99;");
sb.AppendLine(" u.setHp(maxHp);");
sb.AppendLine(" } catch (e2) {}");
sb.AppendLine(" }");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" }");
sb.AppendLine();
}
if (hasMaxGold)
{
sb.AppendLine(" function __antigravity_maxGold() {");
sb.AppendLine(" try {");
sb.AppendLine(" if (typeof root !== 'undefined' && root.getMetaSession) {");
sb.AppendLine(" var meta = root.getMetaSession();");
sb.AppendLine(" if (meta && meta.setGold) { meta.setGold(999999); }");
sb.AppendLine(" }");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" }");
sb.AppendLine();
}
if (hasRecoverHp)
{
sb.AppendLine(" // ターン開始時自動回復フローへの介入 (公式のターン開始回復で確実に最大HP全快)");
sb.AppendLine(" if (typeof RecoveryAllFlowEntry !== 'undefined') {");
sb.AppendLine(" if (RecoveryAllFlowEntry._getRecoveryValue) {");
sb.AppendLine(" var _orig_RecoveryAllFlowEntry_getRecoveryValue = RecoveryAllFlowEntry._getRecoveryValue;");
sb.AppendLine(" RecoveryAllFlowEntry._getRecoveryValue = function(unit) {");
sb.AppendLine(" try {");
sb.AppendLine(" if (__antigravity_isPlayerSide(unit)) {");
sb.AppendLine(" var mhp = (typeof ParamBonus !== 'undefined' && ParamBonus.getMhp) ? ParamBonus.getMhp(unit) : 99;");
sb.AppendLine(" return Math.max(mhp, 999);");
sb.AppendLine(" }");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return _orig_RecoveryAllFlowEntry_getRecoveryValue.call(this, unit);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (RecoveryAllFlowEntry._completeMemberData) {");
sb.AppendLine(" var _orig_RecoveryAllFlowEntry_completeMemberData = RecoveryAllFlowEntry._completeMemberData;");
sb.AppendLine(" RecoveryAllFlowEntry._completeMemberData = function(turnChange) {");
sb.AppendLine(" try { __antigravity_healAllUnits(); } catch (e) {}");
sb.AppendLine(" return _orig_RecoveryAllFlowEntry_completeMemberData.call(this, turnChange);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
}
sb.AppendLine(" // A. プレイヤーターン開始時に実行 (PlayerTurn.openTurnCycle)");
sb.AppendLine(" if (typeof PlayerTurn !== 'undefined' && PlayerTurn.openTurnCycle) {");
sb.AppendLine(" var _orig_PlayerTurn_openTurnCycle = PlayerTurn.openTurnCycle;");
sb.AppendLine(" PlayerTurn.openTurnCycle = function() {");
sb.AppendLine(" var result = _orig_PlayerTurn_openTurnCycle.call(this);");
sb.AppendLine(" try {");
if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();");
if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return result;");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" // A2. プレイヤー行動中サイクル (PlayerTurn.moveTurnCycle - セーブロード直後にも即座に反映)");
sb.AppendLine(" if (typeof PlayerTurn !== 'undefined' && PlayerTurn.moveTurnCycle) {");
sb.AppendLine(" var _orig_PlayerTurn_moveTurnCycle = PlayerTurn.moveTurnCycle;");
sb.AppendLine(" PlayerTurn.moveTurnCycle = function() {");
sb.AppendLine(" try {");
if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();");
if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return _orig_PlayerTurn_moveTurnCycle.call(this);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" // B. ターン切替処理時 (TurnChangeEnd.doLastAction & TurnChangeStart.doLastAction)");
sb.AppendLine(" if (typeof TurnChangeEnd !== 'undefined' && TurnChangeEnd.doLastAction) {");
sb.AppendLine(" var _orig_TurnChangeEnd_doLastAction = TurnChangeEnd.doLastAction;");
sb.AppendLine(" TurnChangeEnd.doLastAction = function() {");
sb.AppendLine(" _orig_TurnChangeEnd_doLastAction.call(this);");
sb.AppendLine(" try {");
if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();");
if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (typeof TurnChangeStart !== 'undefined' && TurnChangeStart.doLastAction) {");
sb.AppendLine(" var _orig_TurnChangeStart_doLastAction = TurnChangeStart.doLastAction;");
sb.AppendLine(" TurnChangeStart.doLastAction = function() {");
sb.AppendLine(" _orig_TurnChangeStart_doLastAction.call(this);");
sb.AppendLine(" try {");
if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();");
if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" // B2. ターンロゴ表示時 (BaseTurnLogoFlowEntry.doMainAction)");
sb.AppendLine(" if (typeof BaseTurnLogoFlowEntry !== 'undefined' && BaseTurnLogoFlowEntry.doMainAction) {");
sb.AppendLine(" var _orig_BaseTurnLogoFlowEntry_doMainAction = BaseTurnLogoFlowEntry.doMainAction;");
sb.AppendLine(" BaseTurnLogoFlowEntry.doMainAction = function(isMusic) {");
sb.AppendLine(" var res = _orig_BaseTurnLogoFlowEntry_doMainAction.call(this, isMusic);");
sb.AppendLine(" try {");
if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();");
if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return res;");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" // C. マップ開始時 (CurrentMap.prepareMap)");
sb.AppendLine(" if (typeof CurrentMap !== 'undefined' && CurrentMap.prepareMap) {");
sb.AppendLine(" var _orig_CurrentMap_prepareMap = CurrentMap.prepareMap;");
sb.AppendLine(" CurrentMap.prepareMap = function() {");
sb.AppendLine(" _orig_CurrentMap_prepareMap.call(this);");
sb.AppendLine(" try {");
if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();");
if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" // D. ユニット移動選択画面開始時 (MapSequenceArea.openSequence)");
sb.AppendLine(" if (typeof MapSequenceArea !== 'undefined' && MapSequenceArea.openSequence) {");
sb.AppendLine(" var _orig_MapSequenceArea_openSequence = MapSequenceArea.openSequence;");
sb.AppendLine(" MapSequenceArea.openSequence = function(parentTurnObject) {");
sb.AppendLine(" try {");
if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();");
if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return _orig_MapSequenceArea_openSequence.call(this, parentTurnObject);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine();
}
// 4. 味方移動力最大化 (マップ全域移動可能: 99固定)
if (item.IsPluginEnabled("SrpgMoveBoost"))
{
sb.AppendLine(" // [チート] 自軍ユニットの移動可能範囲最大化 (移動力99)");
sb.AppendLine(" if (typeof ParamBonus !== 'undefined' && ParamBonus.getMov) {");
sb.AppendLine(" var _orig_ParamBonus_getMov = ParamBonus.getMov;");
sb.AppendLine(" ParamBonus.getMov = function(unit) {");
sb.AppendLine(" try {");
sb.AppendLine(" if (__antigravity_isMovTarget(unit)) return 99;");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return _orig_ParamBonus_getMov.call(this, unit);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (typeof RealBonus !== 'undefined' && RealBonus.getMov) {");
sb.AppendLine(" var _orig_RealBonus_getMov = RealBonus.getMov;");
sb.AppendLine(" RealBonus.getMov = function(unit) {");
sb.AppendLine(" try {");
sb.AppendLine(" if (__antigravity_isMovTarget(unit)) return 99;");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return _orig_RealBonus_getMov.call(this, unit);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (typeof UnitParameter !== 'undefined' && UnitParameter.MOV && UnitParameter.MOV.getUnitValue) {");
sb.AppendLine(" var _orig_UnitParameter_MOV_getUnitValue = UnitParameter.MOV.getUnitValue;");
sb.AppendLine(" UnitParameter.MOV.getUnitValue = function(unit) {");
sb.AppendLine(" try {");
sb.AppendLine(" if (__antigravity_isMovTarget(unit)) return 99;");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return _orig_UnitParameter_MOV_getUnitValue.call(this, unit);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (typeof UnitRangePanel !== 'undefined') {");
sb.AppendLine(" if (UnitRangePanel._getRangeMov) {");
sb.AppendLine(" var _orig_UnitRangePanel_getRangeMov = UnitRangePanel._getRangeMov;");
sb.AppendLine(" UnitRangePanel._getRangeMov = function(unit) {");
sb.AppendLine(" try {");
sb.AppendLine(" if (__antigravity_isMovTarget(unit)) return 99;");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return _orig_UnitRangePanel_getRangeMov.call(this, unit);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (UnitRangePanel.getUnitAttackRange) {");
sb.AppendLine(" var _orig_UnitRangePanel_getUnitAttackRange = UnitRangePanel.getUnitAttackRange;");
sb.AppendLine(" UnitRangePanel.getUnitAttackRange = function(unit) {");
sb.AppendLine(" var obj = _orig_UnitRangePanel_getUnitAttackRange.call(this, unit);");
sb.AppendLine(" try {");
sb.AppendLine(" if (obj && __antigravity_isMovTarget(unit)) {");
sb.AppendLine(" obj.mov = 99;");
sb.AppendLine(" }");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return obj;");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (UnitRangePanel._setRangeData) {");
sb.AppendLine(" var _orig_UnitRangePanel_setRangeData = UnitRangePanel._setRangeData;");
sb.AppendLine(" UnitRangePanel._setRangeData = function() {");
sb.AppendLine(" try {");
sb.AppendLine(" if (this._unit && __antigravity_isMovTarget(this._unit)) {");
sb.AppendLine(" var attackRange = this.getUnitAttackRange(this._unit);");
sb.AppendLine(" var isWeapon = attackRange.endRange !== 0;");
sb.AppendLine(" if (isWeapon) {");
sb.AppendLine(" this._simulator.startSimulationWeapon(this._unit, 99, attackRange.startRange, attackRange.endRange);");
sb.AppendLine(" } else {");
sb.AppendLine(" this._simulator.startSimulation(this._unit, 99);");
sb.AppendLine(" }");
sb.AppendLine(" this._setLight(isWeapon);");
sb.AppendLine(" return;");
sb.AppendLine(" }");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return _orig_UnitRangePanel_setRangeData.call(this);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (UnitRangePanel._setRepeatRangeData) {");
sb.AppendLine(" var _orig_UnitRangePanel_setRepeatRangeData = UnitRangePanel._setRepeatRangeData;");
sb.AppendLine(" UnitRangePanel._setRepeatRangeData = function() {");
sb.AppendLine(" try {");
sb.AppendLine(" if (this._unit && __antigravity_isMovTarget(this._unit)) {");
sb.AppendLine(" var attackRange = this.getUnitAttackRange(this._unit);");
sb.AppendLine(" var isWeapon = attackRange.endRange !== 0;");
sb.AppendLine(" if (isWeapon) {");
sb.AppendLine(" this._simulator.startSimulationWeapon(this._unit, 99, attackRange.startRange, attackRange.endRange);");
sb.AppendLine(" } else {");
sb.AppendLine(" this._simulator.startSimulation(this._unit, 99);");
sb.AppendLine(" }");
sb.AppendLine(" this._setLight(isWeapon);");
sb.AppendLine(" return;");
sb.AppendLine(" }");
sb.AppendLine(" } catch (e) {}");
sb.AppendLine(" return _orig_UnitRangePanel_setRepeatRangeData.call(this);");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
}
// 5. 敵撃破時アイテム100%ドロップ
if (item.IsPluginEnabled("SrpgItemAllDrop"))
{
sb.AppendLine(" // [チート] 敵撃破時アイテム100%ドロップ");
sb.AppendLine(" if (typeof ItemDropControl !== 'undefined' && ItemDropControl.isDropAllowed) {");
sb.AppendLine(" ItemDropControl.isDropAllowed = function(unit) {");
sb.AppendLine(" return true;");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine(" if (typeof DropTrophyControl !== 'undefined' && DropTrophyControl.isDropAllowed) {");
sb.AppendLine(" DropTrophyControl.isDropAllowed = function(unit) {");
sb.AppendLine(" return true;");
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine();
}
sb.AppendLine("})();");
return sb.ToString();
}
public const string ModStartTag = "// >>> ANTIGRAVITY_MOD_START >>>";
public const string ModEndTag = "// <<< ANTIGRAVITY_MOD_END <<<";
/// <summary>
/// 既存スクリプトファイルへModコードを注入(または更新)します。
/// </summary>
private static void InjectModToExistingScript(string scriptPath, string modCode)
{
if (!File.Exists(scriptPath)) return;
try
{
string content = File.ReadAllText(scriptPath, Encoding.UTF8);
int startIdx = content.IndexOf(ModStartTag, StringComparison.Ordinal);
if (startIdx >= 0)
{
int endIdx = content.IndexOf(ModEndTag, StringComparison.Ordinal);
if (endIdx > startIdx)
{
content = content[..startIdx].TrimEnd() + "\n\n" + modCode + "\n";
File.WriteAllText(scriptPath, content, Encoding.UTF8);
return;
}
}
content = content.TrimEnd() + "\n\n" + modCode + "\n";
File.WriteAllText(scriptPath, content, Encoding.UTF8);
}
catch { }
}
/// <summary>
/// 既存スクリプトファイルから注入されたModコードを削除します。
/// </summary>
private static void RemoveModFromExistingScript(string scriptPath)
{
if (!File.Exists(scriptPath)) return;
try
{
string content = File.ReadAllText(scriptPath, Encoding.UTF8);
int startIdx = content.IndexOf(ModStartTag, StringComparison.Ordinal);
if (startIdx >= 0)
{
int endIdx = content.IndexOf(ModEndTag, StringComparison.Ordinal);
if (endIdx > startIdx)
{
endIdx += ModEndTag.Length;
content = content.Remove(startIdx, endIdx - startIdx).TrimEnd() + "\n";
File.WriteAllText(scriptPath, content, Encoding.UTF8);
}
}
}
catch { }
}
/// <summary>
/// Modスクリプトを展開フォルダ内の既存スクリプト群に注入し、data.dts を再構築します。
/// (SRPG_Unpackerの仕様上、新規ファイル名は無視されるため、既存ファイルへの確実な注入を行います)
/// </summary>
public async Task<(bool Success, string Message)> ApplyModAndRepackAsync(TkoolGameItem item, IProgress<string>? progress = null)
{
var gameDir = item.RootDirectory;
// 1. まだ解凍されていない場合は解凍を実行
if (!SrpgArchiveService.IsExtracted(gameDir))
{
progress?.Report("アーカイブ(data.dts)を初回展開中...");
var unpackRes = await this._archiveService.UnpackDataDtsAsync(gameDir, progress);
if (!unpackRes.Success)
{
return unpackRes;
}
}
var extractedDir = SrpgArchiveService.GetExtractedDirectory(gameDir);
progress?.Report("Modスクリプトを生成中...");
var modBody = this.GenerateModScript(item);
var jsContent = $"{ModStartTag}\n{modBody}\n{ModEndTag}";
// 2. 既存のスクリプトへ注入
// (Pluginフォルダ内の既存スクリプトは全標準スクリプト読み込み完了後に実行されるため最優先で注入)
var mainScript = Path.Combine(extractedDir, "Script", "map", "map-playerturn.js");
var turnChangeScript = Path.Combine(extractedDir, "Script", "map", "map-turnchange.js");
var pluginDir = Path.Combine(extractedDir, "Plugin");
progress?.Report("スクリプトへModコードを注入中...");
InjectModToExistingScript(mainScript, jsContent);
InjectModToExistingScript(turnChangeScript, jsContent);
if (Directory.Exists(pluginDir))
{
var existingPlugin = Directory.GetFiles(pluginDir, "*.js")
.FirstOrDefault(f => !Path.GetFileName(f).StartsWith("99_AntigravityMod", StringComparison.OrdinalIgnoreCase));
if (existingPlugin != null)
{
InjectModToExistingScript(existingPlugin, jsContent);
}
}
try
{
var directPluginDir = Path.Combine(gameDir, "Plugin");
if (!Directory.Exists(directPluginDir)) Directory.CreateDirectory(directPluginDir);
File.WriteAllText(Path.Combine(directPluginDir, ModScriptFileName), jsContent, Encoding.UTF8);
}
catch { }
// 3. data.dts を再パック
progress?.Report("Modを適用した data.dts を再構築中...");
var repackRes = await this._archiveService.RepackDataDtsAsync(gameDir, progress);
if (repackRes.Success)
{
item.IsModded = true;
item.IsSrpgExtracted = true;
return (true, "SRPG Studio 改造プラグインの注入とアーカイブ再構築が完了しました!");
}
else
{
return repackRes;
}
}
/// <summary>
/// Modスクリプトの注入を解除し、data.dts を再構築(またはバックアップから復元)します。
/// </summary>
public async Task<(bool Success, string Message)> RemoveModAndRepackAsync(TkoolGameItem item, IProgress<string>? progress = null)
{
var gameDir = item.RootDirectory;
var extractedDir = SrpgArchiveService.GetExtractedDirectory(gameDir);
// 1. 注入したスクリプトからModコードを削除
var targets = new List<string>
{
Path.Combine(extractedDir, "Script", "map", "map-playerturn.js"),
Path.Combine(extractedDir, "Script", "map", "map-turnchange.js"),
Path.Combine(extractedDir, "Script", "singleton", "singleton-system.js")
};
var pluginDir = Path.Combine(extractedDir, "Plugin");
if (Directory.Exists(pluginDir))
{
foreach (var f in Directory.GetFiles(pluginDir, "*.js"))
{
targets.Add(f);
}
}
foreach (var target in targets)
{
RemoveModFromExistingScript(target);
}
var modJsPath = Path.Combine(pluginDir, ModScriptFileName);
if (File.Exists(modJsPath)) File.Delete(modJsPath);
try
{
var directModJs = Path.Combine(gameDir, "Plugin", ModScriptFileName);
if (File.Exists(directModJs)) File.Delete(directModJs);
}
catch { }
// 2. バックアップが存在すればバックアップ復元を試行
progress?.Report("オリジナルバックアップから data.dts を復元中...");
var (Success, Message) = await this._archiveService.RevertBackupAsync(gameDir);
if (Success)
{
item.IsModded = false;
return (true, "改造プラグインを解除し、元のアーカイブへ復元しました。");
}
// バックアップが無い場合は Mod解除状態で再パック
progress?.Report("Mod解除状態でアーカイブを再構築中...");
var repackRes = await this._archiveService.RepackDataDtsAsync(gameDir, progress);
if (repackRes.Success)
{
item.IsModded = false;
return (true, "改造プラグインを解除し、アーカイブを再構築しました。");
}
return repackRes;
}
/// <summary>
/// SRPG Studio ゲームに対するすべての改造(プロキシDLL・プラグイン改造・解凍データ等)を完全に解除し、
/// 元の安全な状態に復元します。
/// </summary>
public async Task<(bool Success, string Message)> RestoreAllModsAsync(TkoolGameItem item, IProgress<string>? progress = null)
{
var logs = new List<string>();
var gameDir = item.RootDirectory;
// 1. プロキシDLL解除
if (IsProxyDllEnabled(gameDir))
{
this.DisableProxyDll(gameDir);
logs.Add("・プロキシDLL (version.dll) を解除しました");
}
// 2. 注入コードおよびModプラグインの削除
var extractedDir = SrpgArchiveService.GetExtractedDirectory(gameDir);
var targets = new List<string>
{
Path.Combine(extractedDir, "Script", "map", "map-playerturn.js"),
Path.Combine(extractedDir, "Script", "singleton", "singleton-system.js")
};
var pluginDir = Path.Combine(extractedDir, "Plugin");
if (Directory.Exists(pluginDir))
{
foreach (var f in Directory.GetFiles(pluginDir, "*.js")) targets.Add(f);
}
foreach (var t in targets) RemoveModFromExistingScript(t);
var modJsPath = Path.Combine(pluginDir, ModScriptFileName);
if (File.Exists(modJsPath))
{
File.Delete(modJsPath);
logs.Add($"・Modプラグインスクリプト ({ModScriptFileName}) を削除しました");
}
try
{
var directModJs = Path.Combine(gameDir, "Plugin", ModScriptFileName);
if (File.Exists(directModJs))
{
File.Delete(directModJs);
}
}
catch { }
// 3. バックアップからの data.dts 復元
progress?.Report("バックアップから元の data.dts を復元中...");
var (Success, Message) = await this._archiveService.RevertBackupAsync(gameDir);
if (Success)
{
logs.Add($"・{Message}");
}
else
{
logs.Add("・元の data.dts バックアップは適用不要または存在しませんでした");
}
// 4. 解凍フォルダの退避
var restoreExtractedRes = this._archiveService.RestoreExtractedState(gameDir);
if (restoreExtractedRes.Success && !restoreExtractedRes.Message.Contains("存在しません"))
{
logs.Add($"・{restoreExtractedRes.Message}");
}
// 5. フラグ更新
item.SrpgProxyDll = false;
item.IsModded = false;
item.IsSrpgExtracted = false;
string summary = logs.Count > 0 ? string.Join("\n", logs) : "解除対象の改造はありませんでした。";
return (true, summary);
}
}
}
File diff suppressed because it is too large. Load diff
+208
View File
@@ -0,0 +1,208 @@
using System;
using System.IO;
using System.Text;
namespace GameLauncher.Engines.Tkool
{
/// <summary>
/// 対象ゲームの plugins.js に対する可逆なJSプラグイン注入(mod)を行うサービス。
///
/// 設計方針:
/// - ゲーム専用改造は他ゲームへ一切影響を与えない(対象ゲームフォルダ内でのみ完結)。
/// - 注入前に plugins.js を *.glbak へバックアップし、marker 区間のみを書き換える。
/// - Restore は *.glbak から復元し、配置した mod JS を削除して完全可逆にする。
/// - exe内 package.nw 直接書換は最終手段(必須バックアップ)。
/// </summary>
public sealed class TkoolInjectionService
{
/// <summary>注入マーカー(この区間のみを除去すれば完全に元へ戻せる)</summary>
public const string BeginMarker = "/* === GAMELAUNCHER_MOD_BEGIN === */";
public const string EndMarker = "/* === GAMELAUNCHER_MOD_END === */";
/// <summary>注入する改造プラグインファイル名</summary>
public const string ModPluginId = "GameLauncher_Mod";
public const string ModPluginFileName = "GameLauncher_Mod.js";
/// <summary>exe内コンテナ改変時のバックアップ拡張子</summary>
public const string ExeBackupSuffix = ".glbak";
/// <summary>
/// plugins.js に marker が存在する場合、改造注入済みと判定します。
/// </summary>
public static bool CheckIsModded(string pluginsJsPath)
{
if (string.IsNullOrEmpty(pluginsJsPath) || !File.Exists(pluginsJsPath))
{
return false;
}
try
{
var content = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
// パス破損の影響を避けるため、対称な EndMarker(先頭/末尾共通)で判定
return content.Contains(BeginMarker) || content.Contains(ModPluginId);
}
catch
{
return false;
}
}
/// <summary>
/// modプラグインエントリを plugins.js へ marker 付きで追記し、
/// mod JS を js/plugins/ へ配置します。バックアップ(*.glbak)は必須。
/// </summary>
public bool Apply(string pluginsJsPath, string pluginsDir, string modSourcePath)
{
if (string.IsNullOrEmpty(pluginsJsPath) || !File.Exists(pluginsJsPath))
{
return false;
}
if (string.IsNullOrEmpty(modSourcePath) || !File.Exists(modSourcePath))
{
return false;
}
try
{
var backupPath = pluginsJsPath + ExeBackupSuffix;
// 1. バックアップ(未作成時のみ)。既に marker がある場合はクリーン化して保持
if (!File.Exists(backupPath))
{
var original = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
File.WriteAllText(backupPath, RemoveInjection(original), new UTF8Encoding(false));
}
// 2. mod JS を plugins ディレクトリへ配置
if (string.IsNullOrEmpty(pluginsDir))
{
pluginsDir = Path.Combine(Path.GetDirectoryName(pluginsJsPath)!, "plugins");
}
Directory.CreateDirectory(pluginsDir);
File.Copy(modSourcePath, Path.Combine(pluginsDir, ModPluginFileName), overwrite: true);
// 3. バックアップ(クリーン状態)を元に marker 区間を注入
var baseContent = File.ReadAllText(backupPath, Encoding.UTF8);
var injected = InjectEntry(RemoveInjection(baseContent));
File.WriteAllText(pluginsJsPath, injected, new UTF8Encoding(false));
return true;
}
catch
{
return false;
}
}
/// <summary>
/// *.glbak から plugins.js を復元し、配置した mod JS を削除します(完全可逆)。
/// </summary>
public bool Restore(string pluginsJsPath, string pluginsDir)
{
if (string.IsNullOrEmpty(pluginsJsPath) || !File.Exists(pluginsJsPath))
{
return false;
}
try
{
var backupPath = pluginsJsPath + ExeBackupSuffix;
if (File.Exists(backupPath))
{
var backupContent = File.ReadAllText(backupPath, Encoding.UTF8);
File.WriteAllText(pluginsJsPath, backupContent, new UTF8Encoding(false));
try { File.Delete(backupPath); } catch { }
}
else
{
// バックアップが無くても現状から marker 区間を除去
var current = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
File.WriteAllText(pluginsJsPath, RemoveInjection(current), new UTF8Encoding(false));
}
// 配置した mod JS を削除(ゴミを残さない)
if (!string.IsNullOrEmpty(pluginsDir))
{
var modPlugin = Path.Combine(pluginsDir, ModPluginFileName);
if (File.Exists(modPlugin))
{
try { File.Delete(modPlugin); } catch { }
}
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// plugins.js の配列へ mod プラグインのエントリを marker 付きで追加します。
/// </summary>
private static string InjectEntry(string content)
{
if (string.IsNullOrWhiteSpace(content))
{
return content;
}
int arrayStart = content.IndexOf('[');
int arrayEnd = content.LastIndexOf(']');
if (arrayStart == -1 || arrayEnd == -1 || arrayEnd <= arrayStart)
{
return content;
}
var entry = $"{BeginMarker}{{\"name\":\"{ModPluginId}\",\"status\":true,\"description\":\"GameLauncher mod\",\"parameters\":{{}}}}{EndMarker}";
var prefix = content[..(arrayStart + 1)];
var inner = content.Substring(arrayStart + 1, arrayEnd - arrayStart - 1);
var suffix = content[arrayEnd..];
var trimmedInner = inner.Trim();
var newInner = string.IsNullOrEmpty(trimmedInner)
? "\n" + entry + "\n"
: inner.TrimEnd() + ",\n" + entry + "\n";
return prefix + newInner + suffix;
}
/// <summary>
/// marker 区間(BEGIN..END)を完全に除去します。これにより注入前の状態へ復元できます。
/// </summary>
private static string RemoveInjection(string content)
{
if (string.IsNullOrEmpty(content))
{
return content;
}
string prev;
do
{
prev = content;
int begin = content.IndexOf(BeginMarker, StringComparison.Ordinal);
if (begin < 0) break;
int end = content.IndexOf(EndMarker, begin, StringComparison.Ordinal);
if (end < 0) break;
end += EndMarker.Length;
// 直前のカンマ・余分な空白も除去対象に含める
int cutStart = begin;
int scan = begin - 1;
while (scan >= 0 && char.IsWhiteSpace(content[scan])) scan--;
if (scan >= 0 && content[scan] == ',') cutStart = scan;
content = content[..cutStart] + content[end..];
}
while (content != prev);
return content;
}
}
}
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@@ -8,7 +8,7 @@ using System.Text.RegularExpressions;
using GameLauncher.Helpers; using GameLauncher.Helpers;
using GameLauncher.Models; using GameLauncher.Models;
namespace GameLauncher.Services namespace GameLauncher.Engines.Tkool
{ {
/// <summary> /// <summary>
/// ツクールスクリプト改造プラグインの動的検出・適用・復元・管理を行うサービス /// ツクールスクリプト改造プラグインの動的検出・適用・復元・管理を行うサービス
@@ -31,17 +31,21 @@ namespace GameLauncher.Services
"BattleTurnRecover", "BattleTurnRecover",
"MaxGainGold", "MaxGainGold",
"MaxGainExp", "MaxGainExp",
"InstantMessage" "InstantMessage",
"GameLauncher_Mod",
"GameLauncherMod",
"GameLauncher_StandaloneMod",
"GameLauncherStandaloneMod"
]; ];
private List<ModPluginDefinition> _availablePlugins = []; private List<ModPluginDefinition> _availablePlugins = [];
/// <summary>現在認識されている利用可能なプラグイン一覧</summary> /// <summary>現在認識されている利用可能なプラグイン一覧</summary>
public IReadOnlyList<ModPluginDefinition> AvailablePlugins => _availablePlugins; public IReadOnlyList<ModPluginDefinition> AvailablePlugins => this._availablePlugins;
public TkoolModService() public TkoolModService()
{ {
LoadAvailablePlugins(); this.LoadAvailablePlugins();
} }
/// <summary> /// <summary>
@@ -86,13 +90,22 @@ namespace GameLauncher.Services
{ {
try try
{ {
list.Add(ModPluginDefinition.FromFile(file)); var def = ModPluginDefinition.FromFile(file);
if (string.Equals(def.Id, "GameLauncher_Mod", StringComparison.OrdinalIgnoreCase) ||
string.Equals(def.Id, "GameLauncher_StandaloneMod", StringComparison.OrdinalIgnoreCase) ||
string.Equals(def.Id, "GameLauncherMod", StringComparison.OrdinalIgnoreCase) ||
string.Equals(def.Id, "GameLauncherStandaloneMod", StringComparison.OrdinalIgnoreCase))
{
continue;
}
list.Add(def);
} }
catch { } catch { }
} }
} }
_availablePlugins = list; this._availablePlugins = list;
return list; return list;
} }
@@ -146,11 +159,11 @@ namespace GameLauncher.Services
{ {
if (game.ApplyMod) if (game.ApplyMod)
{ {
return ApplyMod(game, defaultSettings); return this.ApplyMod(game, defaultSettings);
} }
else else
{ {
return RestoreOriginal(game); return this.RestoreOriginal(game);
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -178,33 +191,52 @@ namespace GameLauncher.Services
Directory.CreateDirectory(pluginsDir); Directory.CreateDirectory(pluginsDir);
} }
var backupPath = pluginsJsPath + BackupSuffix; var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var backupPath = Path.Combine(gameBackupDir, "plugins.js" + BackupSuffix);
var legacyBackupPath = pluginsJsPath + BackupSuffix;
// 1. バックアップが存在しない場合、バックアップを作成する // 1. バックアップが存在しない場合、バックアップを作成する (Backups フォルダに保存)
if (!File.Exists(backupPath)) if (!File.Exists(backupPath))
{
if (File.Exists(legacyBackupPath))
{
// 既存のゲーム内バックアップがあれば Backups フォルダへコピー
File.Copy(legacyBackupPath, backupPath, true);
}
else
{ {
string currentContent = File.ReadAllText(pluginsJsPath, Encoding.UTF8); string currentContent = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
// 既に改造プラグイン(新旧問わず)が埋め込まれている場合はクリーンアップしたものをバックアップとして保持 // 既に改造プラグイン(新旧問わず)が埋め込まれている場合はクリーンアップしたものをバックアップとして保持
string cleanContent = CleanManagedPluginsFromContent(currentContent); string cleanContent = CleanManagedPluginsFromContent(currentContent);
File.WriteAllText(backupPath, cleanContent, new UTF8Encoding(false)); File.WriteAllText(backupPath, cleanContent, new UTF8Encoding(false));
} }
}
// 2. バックアップ(クリーン状態)を元に編集を開始 // 2. バックアップ(クリーン状態)を元に編集を開始
string baseContent = File.ReadAllText(backupPath, Encoding.UTF8); string baseContent = File.ReadAllText(backupPath, Encoding.UTF8);
// 最新の動的プラグイン一覧を取得 // 最新の動的プラグイン一覧を取得
if (_availablePlugins.Count == 0) if (this._availablePlugins.Count == 0)
{ {
LoadAvailablePlugins(); this.LoadAvailablePlugins();
} }
// 有効化対象のプラグインを取得 // 有効化対象のプラグインを取得
var pluginsToEnable = _availablePlugins // ※ResourceLoaderFix はリソース読み込み不具合の必須救済プラグインのため、常に有効化・先頭配置
.Where(p => game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: true)) var fixPlugin = this._availablePlugins.FirstOrDefault(p => string.Equals(p.Id, "ResourceLoaderFix", StringComparison.OrdinalIgnoreCase));
var pluginsToEnable = this._availablePlugins
.Where(p => string.Equals(p.Id, "ResourceLoaderFix", StringComparison.OrdinalIgnoreCase) || game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: true))
.ToList(); .ToList();
// ResourceLoaderFix を最優先(先頭)に配置して、他プラグイン実行前のリソース要求も確実に救済
if (fixPlugin != null && pluginsToEnable.Contains(fixPlugin))
{
pluginsToEnable.Remove(fixPlugin);
pluginsToEnable.Insert(0, fixPlugin);
}
// 3. ゲーム側の plugins ディレクトリから不要な旧プラグインや無効プラグインを安全に掃除 // 3. ゲーム側の plugins ディレクトリから不要な旧プラグインや無効プラグインを安全に掃除
var allManaged = GetAllManagedPluginNames(_availablePlugins); var allManaged = GetAllManagedPluginNames(this._availablePlugins);
var enabledIds = new HashSet<string>(pluginsToEnable.Select(p => p.Id), StringComparer.OrdinalIgnoreCase); var enabledIds = new HashSet<string>(pluginsToEnable.Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
foreach (var pluginId in allManaged) foreach (var pluginId in allManaged)
@@ -223,7 +255,7 @@ namespace GameLauncher.Services
// 4. 有効対象のプラグインファイルをゲーム側へ配置 // 4. 有効対象のプラグインファイルをゲーム側へ配置
foreach (var plugin in pluginsToEnable) foreach (var plugin in pluginsToEnable)
{ {
CopyPluginToGame(plugin, pluginsDir); this.CopyPluginToGame(plugin, pluginsDir);
} }
// 5. plugins.js をパース・再構築して有効プラグインを追加 // 5. plugins.js をパース・再構築して有効プラグインを追加
@@ -245,7 +277,9 @@ namespace GameLauncher.Services
{ {
var pluginsJsPath = game.PluginsJsPath; var pluginsJsPath = game.PluginsJsPath;
var pluginsDir = game.PluginsDirPath; var pluginsDir = game.PluginsDirPath;
var backupPath = pluginsJsPath + BackupSuffix; var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var backupPath = Path.Combine(gameBackupDir, "plugins.js" + BackupSuffix);
var legacyBackupPath = pluginsJsPath + BackupSuffix;
// 1. バックアップが存在する場合はバックアップから復元(再構築を通すことで壊れたバックアップも修復) // 1. バックアップが存在する場合はバックアップから復元(再構築を通すことで壊れたバックアップも修復)
if (File.Exists(backupPath)) if (File.Exists(backupPath))
@@ -254,6 +288,14 @@ namespace GameLauncher.Services
string cleanContent = RebuildPluginsJs(backupContent, null); string cleanContent = RebuildPluginsJs(backupContent, null);
File.WriteAllText(pluginsJsPath, cleanContent, new UTF8Encoding(false)); File.WriteAllText(pluginsJsPath, cleanContent, new UTF8Encoding(false));
} }
else if (File.Exists(legacyBackupPath))
{
string backupContent = File.ReadAllText(legacyBackupPath, Encoding.UTF8);
string cleanContent = RebuildPluginsJs(backupContent, null);
File.WriteAllText(pluginsJsPath, cleanContent, new UTF8Encoding(false));
// Backups フォルダへもコピー
try { File.Copy(legacyBackupPath, backupPath, true); } catch { }
}
else else
{ {
// バックアップがなくても、現在の plugins.js から新旧すべての管理プラグインを綺麗に除去 // バックアップがなくても、現在の plugins.js から新旧すべての管理プラグインを綺麗に除去
@@ -265,7 +307,7 @@ namespace GameLauncher.Services
// 2. ゲーム側の plugins フォルダから新旧すべてのプラグインファイルを安全に削除(ゴミを残さない) // 2. ゲーム側の plugins フォルダから新旧すべてのプラグインファイルを安全に削除(ゴミを残さない)
if (!string.IsNullOrEmpty(pluginsDir) && Directory.Exists(pluginsDir)) if (!string.IsNullOrEmpty(pluginsDir) && Directory.Exists(pluginsDir))
{ {
var allManaged = GetAllManagedPluginNames(_availablePlugins); var allManaged = GetAllManagedPluginNames(this._availablePlugins);
foreach (var pluginName in allManaged) foreach (var pluginName in allManaged)
{ {
var targetFile = Path.Combine(pluginsDir, $"{pluginName}.js"); var targetFile = Path.Combine(pluginsDir, $"{pluginName}.js");
@@ -276,6 +318,12 @@ namespace GameLauncher.Services
} }
} }
// 3. ゲームフォルダ内の旧バックアップファイルがあれば削除してBackupsフォルダに一本化
if (File.Exists(legacyBackupPath))
{
try { File.Delete(legacyBackupPath); } catch { }
}
game.IsModded = false; game.IsModded = false;
return (true, "ゲームを改造前のオリジナル状態に正常に復元しました。(旧プラグインも完全削除済み)"); return (true, "ゲームを改造前のオリジナル状態に正常に復元しました。(旧プラグインも完全削除済み)");
} }
@@ -306,9 +354,9 @@ namespace GameLauncher.Services
return content; return content;
} }
string prefix = content.Substring(0, arrayStart + 1); string prefix = content[..(arrayStart + 1)];
string inner = content.Substring(arrayStart + 1, arrayEnd - arrayStart - 1); string inner = content.Substring(arrayStart + 1, arrayEnd - arrayStart - 1);
string suffix = content.Substring(arrayEnd); string suffix = content[arrayEnd..];
// 新旧すべてのプラグイン名を除去対象とする // 新旧すべてのプラグイン名を除去対象とする
var managedSet = GetAllManagedPluginNames(); var managedSet = GetAllManagedPluginNames();
@@ -362,7 +410,7 @@ namespace GameLauncher.Services
if (depth == 0) if (depth == 0)
{ {
string objText = inner.Substring(objStart, i - objStart).Trim(); string objText = inner[objStart..i].Trim();
// このオブジェクトが新旧管理対象プラグインかどうか判定 // このオブジェクトが新旧管理対象プラグインかどうか判定
var match = Regex.Match(objText, @"""name""\s*:\s*""([^""]+)"""); var match = Regex.Match(objText, @"""name""\s*:\s*""([^""]+)""");
if (match.Success && managedSet.Contains(match.Groups[1].Value)) if (match.Success && managedSet.Contains(match.Groups[1].Value))
+618
View File
@@ -0,0 +1,618 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using GameLauncher.Helpers;
namespace GameLauncher.Engines.Tkool
{
/// <summary>
/// ツクールMV/MZ等のゲームリソース(画像・音声・スクリプト等)における
/// URLエンコード名、文字化け、機種依存文字(丸数字等)の不整合を、
/// 「実際のゲームコード・データで使われているファイル名」と照合して並列かつ超高速に自動修復するサービス。
///
/// 設計方針:
/// - コード主導のピンポイント照合:
/// 1. data/*.json や plugins.js 等のゲームコード・定義データから要求リソース名を並列抽出。
/// 2. コード側が要求しているのにディスク上に存在しないファイル名(例: エロステ_ページ②.png)を特定。
/// 3. ディスク上の類似ファイル(エロステ_ページ2.png や URLデコード名)から要求通りのファイルを作成。
/// - マルチスレッド並列処理:
/// ・Parallel.ForEach による CPU コア全開の超高速走査・チェック・リンク生成。
/// - 独立ログファイル出力:
/// ・Logs フォルダ内に詳細ログファイル(ResourceRepair_*.log)を出力し、
/// ランチャー画面上のテキストボックス肥大化によるUIフリーズを完全防止。
/// </summary>
public class TkoolResourceRepairService
{
[DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);
/// <summary>修復完了キャッシュマーカーファイル名</summary>
public const string RepairMarkerFileName = ".gl_resource_repaired";
private static bool _encodingProviderRegistered;
// 丸数字マッピング (①: U+2460 〜 ⑳: U+2473)
private static readonly string[] CircleNumbers =
[
"①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩",
"⑪", "⑫", "⑬", "⑭", "⑮", "⑯", "⑰", "⑱", "⑲", "⑳"
];
// 全角数字マッピング (0: U+FF10 〜 9: U+FF19)
private static readonly string[] FullWidthNumbers =
[
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
];
public TkoolResourceRepairService()
{
EnsureEncodingProvider();
}
private static void EnsureEncodingProvider()
{
if (!_encodingProviderRegistered)
{
try
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
_encodingProviderRegistered = true;
}
catch { }
}
}
/// <summary>
/// 修復処理のリアルタイム進捗情報
/// </summary>
public record RepairProgress(int Current, int Total, int RepairedCount, string CurrentStatus);
/// <summary>
/// 修復処理の結果情報
/// </summary>
public record RepairResult(bool Success, int RepairedCount, int CleanedCount, long ElapsedMilliseconds, string Message, string LogFilePath);
/// <summary>
/// ログファイルの保存先ディレクトリを取得します。
/// </summary>
public static string GetLogsDirectory()
{
var exeDir = AppPathHelper.GetExeDirectory();
var logsDir = Path.Combine(exeDir, "Logs");
if (!Directory.Exists(logsDir))
{
Directory.CreateDirectory(logsDir);
}
return logsDir;
}
/// <summary>
/// 指定したツクールゲームのリソースファイルを非同期・並列で修復します(UIをブロックしません)。
/// </summary>
public Task<RepairResult> RepairGameResourcesAsync(
TkoolGameItem game,
bool forceRescan = false,
IProgress<RepairProgress>? progress = null,
Action<string>? uiLogCallback = null)
{
return Task.Run(() => this.RepairGameResources(game, forceRescan, progress, uiLogCallback));
}
/// <summary>
/// 指定したツクールゲームのリソースファイルを並列走査・コード照合修復します。
/// </summary>
public RepairResult RepairGameResources(
TkoolGameItem game,
bool forceRescan = false,
IProgress<RepairProgress>? progress = null,
Action<string>? uiLogCallback = null)
{
if (game == null)
{
return new RepairResult(false, 0, 0, 0, "対象ゲームが指定されていません。", string.Empty);
}
var sw = Stopwatch.StartNew();
// ログファイルの初期化
var logsDir = GetLogsDirectory();
var safeGameName = Regex.Replace(game.FolderName ?? game.Title ?? "Game", @"[\\/:*?""<>|]", "_");
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var logFilePath = Path.Combine(logsDir, $"ResourceRepair_{safeGameName}_{timestamp}.log");
var logLines = new ConcurrentBag<string>();
void FileLog(string message)
{
logLines.Add($"[{DateTime.Now:HH:mm:ss.fff}] {message}");
}
FileLog($"=== ゲームリソース高速並列修復開始 ===");
FileLog($"ゲーム名: {game.Title}");
FileLog($"ルートフォルダ: {game.RootDirectory}");
FileLog($"並列CPUコア数: {Environment.ProcessorCount}");
uiLogCallback?.Invoke($"[リソース修復] {game.Title}: ゲームコードとの並列照合を開始します...");
progress?.Report(new RepairProgress(0, 100, 0, "ゲームコード・データを収集中..."));
var targetDirs = this.CollectResourceDirectories(game);
if (targetDirs.Count == 0)
{
sw.Stop();
var msg = "修復対象のリソースディレクトリが見つかりませんでした。";
FileLog(msg);
this.WriteLogFile(logFilePath, logLines);
uiLogCallback?.Invoke($"[リソース修復] {msg}");
return new RepairResult(true, 0, 0, sw.ElapsedMilliseconds, msg, logFilePath);
}
// -------------------------------------------------------------
// ステップ 1: ゲームデータ (data/*.json, js/*.js) から要求リソース名を並列抽出
// -------------------------------------------------------------
FileLog("ステップ 1: data フォルダ内の JSON およびスクリプトから、コード上で実際に使用されているリソース名を並列抽出中...");
var requestedNames = this.ExtractRequestedResourceNamesFromCode(game, FileLog);
FileLog($"ステップ 1 完了: コード上で使われているリソース識別子を {requestedNames.Count} 件抽出しました。");
progress?.Report(new RepairProgress(20, 100, 0, $"コードリソース抽出完了 ({requestedNames.Count}件)"));
// -------------------------------------------------------------
// ステップ 2: 素材フォルダ (img, audio 等) の実ファイルを並列収集
// -------------------------------------------------------------
FileLog("ステップ 2: 素材フォルダ (img, audio 等) の全ファイルを並列収集・分類中...");
var resourceFiles = new ConcurrentBag<string>();
var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
Parallel.ForEach(targetDirs, parallelOptions, dir =>
{
if (!Directory.Exists(dir)) return;
try
{
foreach (var f in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories))
{
var name = Path.GetFileName(f);
if (!string.Equals(name, RepairMarkerFileName, StringComparison.OrdinalIgnoreCase))
{
resourceFiles.Add(f);
}
}
}
catch (Exception ex)
{
FileLog($"[警告] 一覧取得例外: {dir} ({ex.Message})");
}
});
var allFilesList = resourceFiles.ToList();
FileLog($"ステップ 2 完了: 素材ファイルを合計 {allFilesList.Count} 件検出しました。");
progress?.Report(new RepairProgress(40, 100, 0, $"素材ファイル収集完了 ({allFilesList.Count}件)"));
int repairedCount = 0;
int cleanedCount = 0;
// -------------------------------------------------------------
// ステップ 3: 過去の破損ファイル (%と丸数字の混在) の並列クリーンアップ
// -------------------------------------------------------------
Parallel.ForEach(allFilesList, parallelOptions, filePath =>
{
var fileName = Path.GetFileName(filePath);
if (fileName.Contains('%') && this.ContainsCircleNumber(fileName))
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
System.Threading.Interlocked.Increment(ref cleanedCount);
FileLog($"[不正ファイル削除] {fileName}");
}
}
catch { }
}
});
// -------------------------------------------------------------
// ステップ 4: パーセントエンコードされたファイル名の安全完全デコード (並列)
// -------------------------------------------------------------
FileLog("ステップ 4: URLエンコードされたファイル名の完全デコードと日本語リンク作成中 (並列)...");
var newlyDecodedFiles = new ConcurrentBag<string>();
Parallel.ForEach(allFilesList, parallelOptions, filePath =>
{
var fileName = Path.GetFileName(filePath);
if (fileName.Contains('%'))
{
try
{
var unescaped = this.FullyUnescapeString(fileName);
if (!string.Equals(unescaped, fileName, StringComparison.Ordinal) && !unescaped.Contains('%'))
{
var dirPath = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(dirPath))
{
var unescapedPath = Path.Combine(dirPath, unescaped);
if (!File.Exists(unescapedPath))
{
if (this.CreateLinkOrCopy(filePath, unescapedPath))
{
System.Threading.Interlocked.Increment(ref repairedCount);
newlyDecodedFiles.Add(unescapedPath);
FileLog($"[URLデコード作成] {fileName} -> {unescaped}");
}
}
}
}
}
catch { }
}
});
// ステップ4で新しく作成されたファイルも素材リストに合流
if (!newlyDecodedFiles.IsEmpty)
{
allFilesList.AddRange(newlyDecodedFiles);
}
progress?.Report(new RepairProgress(70, 100, repairedCount, "コード上のファイル名と実素材の照合中..."));
// -------------------------------------------------------------
// ステップ 5: コード上で要求されているファイル名と実素材の照合・表記揺れ解決 (並列)
// -------------------------------------------------------------
FileLog("ステップ 5: コード上で要求されているファイル名(丸数字など)と実素材の表記揺れ照合中 (並列)...");
// ディレクトリごとに実ファイル名辞書を作成(高速ルックアップ用)
var dirFilesMap = allFilesList
.GroupBy(f => Path.GetDirectoryName(f) ?? string.Empty)
.ToDictionary(g => g.Key, g => g.Select(p => Path.GetFileName(p)).ToHashSet(StringComparer.OrdinalIgnoreCase));
// ディレクトリごとに実ファイルの正規化キー辞書を作成(重複キーによるArgumentException例外を安全に回避)
var dirNormalizedMap = allFilesList
.GroupBy(f => Path.GetDirectoryName(f) ?? string.Empty)
.ToDictionary(g => g.Key, g =>
{
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var p in g)
{
var key = this.NormalizeFuzzyKey(Path.GetFileNameWithoutExtension(p));
if (!dict.ContainsKey(key))
{
dict[key] = p;
}
}
return dict;
});
// コードで要求されている各リソース名について照合
Parallel.ForEach(requestedNames, parallelOptions, reqName =>
{
var reqExt = Path.GetExtension(reqName);
var reqNameNoExt = string.IsNullOrEmpty(reqExt) ? reqName : Path.GetFileNameWithoutExtension(reqName);
var normalizedReq = this.NormalizeFuzzyKey(reqNameNoExt);
foreach (var (dirPath, fileSet) in dirFilesMap)
{
// 拡張子がある場合とない場合(.png を補完)を検討
var extensionsToCheck = string.IsNullOrEmpty(reqExt)
? new[] { ".png", ".ogg", ".m4a" }
: [reqExt];
foreach (var ext in extensionsToCheck)
{
var expectedFileName = reqNameNoExt + ext;
// すでにその名前が存在していれば修復不要
if (fileSet.Contains(expectedFileName)) continue;
// ディレクトリ内に正規化キーが一致する実ファイルがあるか探す
if (dirNormalizedMap.TryGetValue(dirPath, out var normDict) &&
normDict.TryGetValue(normalizedReq, out var existingFilePath))
{
var existingExt = Path.GetExtension(existingFilePath);
if (string.Equals(existingExt, ext, StringComparison.OrdinalIgnoreCase))
{
var targetPath = Path.Combine(dirPath, expectedFileName);
if (!File.Exists(targetPath))
{
if (this.CreateLinkOrCopy(existingFilePath, targetPath))
{
System.Threading.Interlocked.Increment(ref repairedCount);
FileLog($"[コード要求リソース修復] コード要求名: {expectedFileName} <- 実ファイル: {Path.GetFileName(existingFilePath)}");
lock (fileSet) { fileSet.Add(expectedFileName); }
}
}
}
}
}
}
});
sw.Stop();
// ログファイルへの一括書き込み
FileLog($"=== 修復完了: 作成 {repairedCount} 件、クリーンアップ {cleanedCount} 件 (所要時間: {sw.ElapsedMilliseconds}ms) ===");
this.WriteLogFile(logFilePath, logLines);
var summaryMsg = $"リソース修復完了: コード要求照合により {repairedCount} 件作成、{cleanedCount} 件クリーンアップ (所要時間: {sw.ElapsedMilliseconds}ms)";
uiLogCallback?.Invoke($"[リソース修復] {summaryMsg}");
uiLogCallback?.Invoke($"[リソース修復] 詳細ログを出力しました: {logFilePath}");
progress?.Report(new RepairProgress(100, 100, repairedCount, "完了"));
return new RepairResult(true, repairedCount, cleanedCount, sw.ElapsedMilliseconds, summaryMsg, logFilePath);
}
/// <summary>
/// ゲームの data/*.json および js/*.js からコード上で要求されているリソース名を並列抽出します。
/// </summary>
private HashSet<string> ExtractRequestedResourceNamesFromCode(TkoolGameItem game, Action<string> log)
{
var requested = new ConcurrentBag<string>();
var dataDirs = new List<string>();
// data フォルダおよび js フォルダの探索
var roots = new List<string>();
if (game.IsEvbExtracted && !string.IsNullOrEmpty(game.EvbExtractedDirPath) && Directory.Exists(game.EvbExtractedDirPath))
{
roots.Add(game.EvbExtractedDirPath);
}
if (!string.IsNullOrEmpty(game.RootDirectory) && Directory.Exists(game.RootDirectory))
{
roots.Add(game.RootDirectory);
}
foreach (var r in roots)
{
var candidates = new[] { r, Path.Combine(r, "www") };
foreach (var c in candidates)
{
var dataPath = Path.Combine(c, "data");
if (Directory.Exists(dataPath) && !dataDirs.Contains(dataPath)) dataDirs.Add(dataPath);
var jsPath = Path.Combine(c, "js");
if (Directory.Exists(jsPath) && !dataDirs.Contains(jsPath)) dataDirs.Add(jsPath);
}
}
var textFiles = new List<string>();
foreach (var d in dataDirs)
{
try
{
textFiles.AddRange(Directory.GetFiles(d, "*.json", SearchOption.AllDirectories));
textFiles.AddRange(Directory.GetFiles(d, "*.js", SearchOption.AllDirectories));
}
catch { }
}
log($"コード検査対象ファイル数: {textFiles.Count} 件 (並列抽出)");
var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
Parallel.ForEach(textFiles, parallelOptions, file =>
{
try
{
var text = File.ReadAllText(file, Encoding.UTF8);
// JSON/JS文字列 "..." または '...' を抽出
var matches = Regex.Matches(text, @"""([^""\r\n]{1,80})""|'([^'\r\n]{1,80})'");
foreach (Match m in matches)
{
var val = (m.Groups[1].Success ? m.Groups[1].Value : m.Groups[2].Value).Trim();
// 素材名として意味のある文字列(日本語、丸数字、記号、拡張子付き等)を収集
if (this.IsPotentialResourceName(val))
{
requested.Add(val);
}
}
}
catch { }
});
return new HashSet<string>(requested, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// 文字列が画像・音声等のリソース名候補として適切か判定します。
/// </summary>
private bool IsPotentialResourceName(string text)
{
if (string.IsNullOrWhiteSpace(text) || text.Length > 80) return false;
// システム予約語やJSON構文は除外
if (text == "true" || text == "false" || text == "null" || text == "undefined") return false;
if (text.StartsWith("{") || text.StartsWith("[")) return false;
// 拡張子を持つ、または日本語/丸数字を含む、または _ や - を含む識別子
if (text.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
text.EndsWith(".ogg", StringComparison.OrdinalIgnoreCase) ||
text.EndsWith(".m4a", StringComparison.OrdinalIgnoreCase))
{
return true;
}
// 日本語・全角文字または丸数字を含む文字列(例: "エロステ_ページ②")
if (this.ContainsNonAscii(text) || this.ContainsCircleNumber(text))
{
// 空白のみや極端な記号列は除外
return !text.Contains("<") && !text.Contains(">");
}
return false;
}
/// <summary>
/// 丸数字(①〜⑳)⇔ 通常数字(1〜20)および 全角数字 を正規化したファジーマッチ用キーを生成します。
/// </summary>
private string NormalizeFuzzyKey(string text)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
var res = text.Normalize(NormalizationForm.FormC).ToLowerInvariant();
// 丸数字 -> 通常数字
for (int i = 0; i < CircleNumbers.Length; i++)
{
res = res.Replace(CircleNumbers[i], (i + 1).ToString());
}
// 全角数字 -> 半角数字
for (int i = 0; i < FullWidthNumbers.Length; i++)
{
res = res.Replace(FullWidthNumbers[i], i.ToString());
}
// 波ダッシュ・チルダ
res = res.Replace('\u301C', '\uFF5E');
// 全角カッコ -> 半角カッコ
res = res.Replace('(', '(').Replace(')', ')');
return res;
}
/// <summary>
/// 蓄積されたログ行をログファイルへ一括書き込みします。
/// </summary>
private void WriteLogFile(string path, IEnumerable<string> lines)
{
try
{
File.WriteAllLines(path, lines, new UTF8Encoding(true));
}
catch { }
}
/// <summary>
/// パーセントエンコードされた文字列を100%完全にデコードします。
/// </summary>
private string FullyUnescapeString(string input)
{
if (string.IsNullOrEmpty(input) || !input.Contains('%')) return input;
try
{
var unescaped = Uri.UnescapeDataString(input);
if (!unescaped.Contains('%')) return unescaped;
}
catch { }
try
{
return Regex.Replace(input, @"((?:%[0-9A-Fa-f]{2})+)", match =>
{
try
{
var hexPart = match.Value;
var bytes = new List<byte>();
for (int i = 0; i < hexPart.Length; i += 3)
{
if (hexPart[i] == '%' && i + 2 < hexPart.Length)
{
bytes.Add(Convert.ToByte(hexPart.Substring(i + 1, 2), 16));
}
}
return Encoding.UTF8.GetString([.. bytes]);
}
catch
{
return match.Value;
}
});
}
catch
{
return input;
}
}
/// <summary>
/// 丸数字が含まれているか判定します。
/// </summary>
private bool ContainsCircleNumber(string text)
{
if (string.IsNullOrEmpty(text)) return false;
foreach (var circle in CircleNumbers)
{
if (text.Contains(circle)) return true;
}
return false;
}
/// <summary>
/// 非ASCII文字(全角文字・日本語等)が含まれているか判定します。
/// </summary>
private bool ContainsNonAscii(string text)
{
if (string.IsNullOrEmpty(text)) return false;
foreach (char c in text)
{
if (c > 127) return true;
}
return false;
}
/// <summary>
/// ハードリンクを最優先で作成し、失敗した場合はファイルコピーを行います。
/// </summary>
private bool CreateLinkOrCopy(string sourceFile, string targetFile)
{
try
{
if (File.Exists(targetFile)) return true;
if (CreateHardLink(targetFile, sourceFile, IntPtr.Zero))
{
return true;
}
File.Copy(sourceFile, targetFile, overwrite: false);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 修復対象となるリソースフォルダ一覧(img, audio, js, data等)を収集します。
/// </summary>
private List<string> CollectResourceDirectories(TkoolGameItem game)
{
var result = new List<string>();
var roots = new List<string>();
if (game.IsEvbExtracted && !string.IsNullOrEmpty(game.EvbExtractedDirPath) && Directory.Exists(game.EvbExtractedDirPath))
{
roots.Add(game.EvbExtractedDirPath);
}
if (!string.IsNullOrEmpty(game.RootDirectory) && Directory.Exists(game.RootDirectory))
{
roots.Add(game.RootDirectory);
}
foreach (var root in roots)
{
var candidates = new[] { root, Path.Combine(root, "www"), Path.Combine(root, "package.nw") };
foreach (var baseDir in candidates)
{
if (!Directory.Exists(baseDir)) continue;
var subDirs = new[] { "img", "audio", "js", "data" };
foreach (var sub in subDirs)
{
var target = Path.Combine(baseDir, sub);
if (Directory.Exists(target) && !result.Contains(target))
{
result.Add(target);
}
}
}
}
return result;
}
}
}
@@ -1,11 +1,15 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using GameLauncher.Helpers;
using GameLauncher.Models; using GameLauncher.Models;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Nwjs;
using GameLauncher.Engines.Unity;
namespace GameLauncher.Services namespace GameLauncher.Engines.Tyrano
{ {
/// <summary> /// <summary>
/// ティラノスクリプトゲームの個別改造設定オプション /// ティラノスクリプトゲームの個別改造設定オプション
@@ -69,16 +73,25 @@ namespace GameLauncher.Services
try try
{ {
var dir = Path.GetDirectoryName(indexPath)!; var dir = Path.GetDirectoryName(indexPath)!;
var backupPath = indexPath + IndexBackupSuffix; var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var backupPath = Path.Combine(gameBackupDir, "index.html" + IndexBackupSuffix);
var legacyBackupPath = indexPath + IndexBackupSuffix;
// 1. バックアップの作成(存在しない場合) // 1. バックアップの作成(存在しない場合、Backups フォルダに保存)
if (!File.Exists(backupPath)) if (!File.Exists(backupPath))
{
if (File.Exists(legacyBackupPath))
{
File.Copy(legacyBackupPath, backupPath, true);
}
else
{ {
string originalContent = File.ReadAllText(indexPath, Encoding.UTF8); string originalContent = File.ReadAllText(indexPath, Encoding.UTF8);
// 既にタグが含まれていた場合は除去したものをバックアップとする // 既にタグが含まれていた場合は除去したものをバックアップとする
string cleanContent = RemoveScriptTag(originalContent); string cleanContent = RemoveScriptTag(originalContent);
File.WriteAllText(backupPath, cleanContent, new UTF8Encoding(false)); File.WriteAllText(backupPath, cleanContent, new UTF8Encoding(false));
} }
}
// 2. 有効化する機能の判定 // 2. 有効化する機能の判定
bool unlockCg = game.IsPluginEnabled("TyranoUnlockAllCg", pluginSettings, fallbackVal: true); bool unlockCg = game.IsPluginEnabled("TyranoUnlockAllCg", pluginSettings, fallbackVal: true);
@@ -121,14 +134,21 @@ namespace GameLauncher.Services
try try
{ {
var dir = Path.GetDirectoryName(indexPath)!; var dir = Path.GetDirectoryName(indexPath)!;
var backupPath = indexPath + IndexBackupSuffix; var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var backupPath = Path.Combine(gameBackupDir, "index.html" + IndexBackupSuffix);
var legacyBackupPath = indexPath + IndexBackupSuffix;
var modJsPath = Path.Combine(dir, ModScriptFileName); var modJsPath = Path.Combine(dir, ModScriptFileName);
// 1. index.html の復元 // 1. index.html の復元 (Backups フォルダを優先)
if (File.Exists(backupPath)) if (File.Exists(backupPath))
{ {
File.Copy(backupPath, indexPath, true); File.Copy(backupPath, indexPath, true);
} }
else if (File.Exists(legacyBackupPath))
{
File.Copy(legacyBackupPath, indexPath, true);
try { File.Copy(legacyBackupPath, backupPath, true); } catch { }
}
else if (File.Exists(indexPath)) else if (File.Exists(indexPath))
{ {
string content = File.ReadAllText(indexPath, Encoding.UTF8); string content = File.ReadAllText(indexPath, Encoding.UTF8);
@@ -136,6 +156,12 @@ namespace GameLauncher.Services
File.WriteAllText(indexPath, clean, new UTF8Encoding(false)); File.WriteAllText(indexPath, clean, new UTF8Encoding(false));
} }
// ゲームフォルダ内の旧バックアップがあれば削除
if (File.Exists(legacyBackupPath))
{
try { File.Delete(legacyBackupPath); } catch { }
}
// 2. tyrano_launcher_mod.js の削除 // 2. tyrano_launcher_mod.js の削除
if (File.Exists(modJsPath)) if (File.Exists(modJsPath))
{ {
@@ -1,4 +1,4 @@
namespace GameLauncher.Models namespace GameLauncher.Engines.Unity
{ {
/// <summary> /// <summary>
/// ゲームエンジンの大分類 /// ゲームエンジンの大分類
@@ -7,17 +7,28 @@ namespace GameLauncher.Models
{ {
Tkool, Tkool,
Tyrano, Tyrano,
Unity Unity,
Wolf,
SrpgStudio,
Evb,
Nwjs,
Other
} }
/// <summary> /// <summary>
/// ツクールのエンジンの種類 /// エンジンの種類
/// </summary> /// </summary>
public enum TkoolEngineType public enum TkoolEngineType
{ {
MV, MV,
MZ, MZ,
Tyrano, Tyrano,
VX,
VXAce,
Wolf,
SrpgStudio,
Nwjs,
Other,
Unknown Unknown
} }
@@ -42,7 +53,8 @@ namespace GameLauncher.Models
FolderLastModifiedAsc = 3, // フォルダ更新日時 (古い順) FolderLastModifiedAsc = 3, // フォルダ更新日時 (古い順)
TitleAsc = 4, // タイトル (昇順) TitleAsc = 4, // タイトル (昇順)
TitleDesc = 5, // タイトル (降順) TitleDesc = 5, // タイトル (降順)
FolderNameAsc = 6 // フォルダ名 (昇順) FolderNameAsc = 6, // フォルダ名 (昇順)
BookmarkedFirst = 7 // ★ ブックマーク優先
} }
/// <summary> /// <summary>
@@ -1,7 +1,8 @@
using System; using System;
using System.IO; using System.IO;
using GameLauncher.Models;
namespace GameLauncher.Models namespace GameLauncher.Engines.Unity
{ {
/// <summary> /// <summary>
/// Unityゲームのデータモデル /// Unityゲームのデータモデル
@@ -20,22 +21,22 @@ namespace GameLauncher.Models
/// <summary>[Game]_Data ディレクトリ絶対パス</summary> /// <summary>[Game]_Data ディレクトリ絶対パス</summary>
public string DataDirectoryPath public string DataDirectoryPath
{ {
get => _dataDirectoryPath; get => this._dataDirectoryPath;
set { if (_dataDirectoryPath != value) { _dataDirectoryPath = value; OnPropertyChanged(); } } set { if (this._dataDirectoryPath != value) { this._dataDirectoryPath = value; this.OnPropertyChanged(); } }
} }
/// <summary>app.info 由来の会社名/開発者名</summary> /// <summary>app.info 由来の会社名/開発者名</summary>
public string CompanyName public string CompanyName
{ {
get => _companyName; get => this._companyName;
set set
{ {
if (_companyName != value) if (this._companyName != value)
{ {
_companyName = value; this._companyName = value;
OnPropertyChanged(); this.OnPropertyChanged();
OnPropertyChanged(nameof(RegistryPath)); this.OnPropertyChanged(nameof(this.RegistryPath));
OnPropertyChanged(nameof(LocalLowPath)); this.OnPropertyChanged(nameof(this.LocalLowPath));
} }
} }
} }
@@ -43,35 +44,35 @@ namespace GameLauncher.Models
/// <summary>app.info 由来の製品名</summary> /// <summary>app.info 由来の製品名</summary>
public string ProductName public string ProductName
{ {
get => _productName; get => this._productName;
set set
{ {
if (_productName != value) if (this._productName != value)
{ {
_productName = value; this._productName = value;
OnPropertyChanged(); this.OnPropertyChanged();
OnPropertyChanged(nameof(RegistryPath)); this.OnPropertyChanged(nameof(this.RegistryPath));
OnPropertyChanged(nameof(LocalLowPath)); this.OnPropertyChanged(nameof(this.LocalLowPath));
} }
} }
} }
public override bool IsIL2CPP => BackendType == UnityBackendType.IL2CPP; public override bool IsIL2CPP => this.BackendType == UnityBackendType.IL2CPP;
public override bool IsMono => BackendType == UnityBackendType.Mono; public override bool IsMono => this.BackendType == UnityBackendType.Mono;
/// <summary>バックエンド形式 (IL2CPP / Mono)</summary> /// <summary>バックエンド形式 (IL2CPP / Mono)</summary>
public UnityBackendType BackendType public UnityBackendType BackendType
{ {
get => _backendType; get => this._backendType;
set set
{ {
if (_backendType != value) if (this._backendType != value)
{ {
_backendType = value; this._backendType = value;
OnPropertyChanged(); this.OnPropertyChanged();
OnPropertyChanged(nameof(BackendBadgeText)); this.OnPropertyChanged(nameof(this.BackendBadgeText));
OnPropertyChanged(nameof(IsIL2CPP)); this.OnPropertyChanged(nameof(this.IsIL2CPP));
OnPropertyChanged(nameof(IsMono)); this.OnPropertyChanged(nameof(this.IsMono));
} }
} }
} }
@@ -79,15 +80,15 @@ namespace GameLauncher.Models
/// <summary>Unityバージョン文字列</summary> /// <summary>Unityバージョン文字列</summary>
public override string UnityVersion public override string UnityVersion
{ {
get => _unityVersion; get => this._unityVersion;
set { if (_unityVersion != value) { _unityVersion = value; OnPropertyChanged(); } } set { if (this._unityVersion != value) { this._unityVersion = value; this.OnPropertyChanged(); } }
} }
/// <summary>セーブデータ(レジストリまたはファイル)が検出されたかどうか</summary> /// <summary>セーブデータ(レジストリまたはファイル)が検出されたかどうか</summary>
public override bool HasSaveData public override bool HasSaveData
{ {
get => _hasSaveData; get => this._hasSaveData;
set { if (_hasSaveData != value) { _hasSaveData = value; OnPropertyChanged(); } } set { if (this._hasSaveData != value) { this._hasSaveData = value; this.OnPropertyChanged(); } }
} }
/// <summary> /// <summary>
@@ -98,9 +99,9 @@ namespace GameLauncher.Models
{ {
get get
{ {
if (string.IsNullOrEmpty(CompanyName) || string.IsNullOrEmpty(ProductName)) if (string.IsNullOrEmpty(this.CompanyName) || string.IsNullOrEmpty(this.ProductName))
return string.Empty; return string.Empty;
return $@"Software\{CompanyName}\{ProductName}"; return $@"Software\{this.CompanyName}\{this.ProductName}";
} }
} }
@@ -112,22 +113,28 @@ namespace GameLauncher.Models
{ {
get get
{ {
if (string.IsNullOrEmpty(CompanyName) || string.IsNullOrEmpty(ProductName)) if (string.IsNullOrEmpty(this.CompanyName) || string.IsNullOrEmpty(this.ProductName))
return string.Empty; return string.Empty;
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var appData = Path.GetDirectoryName(localAppData); var appData = Path.GetDirectoryName(localAppData);
if (string.IsNullOrEmpty(appData)) return string.Empty; if (string.IsNullOrEmpty(appData)) return string.Empty;
return Path.Combine(appData, "LocalLow", CompanyName, ProductName); return Path.Combine(appData, "LocalLow", this.CompanyName, this.ProductName);
} }
} }
public override string BackendBadgeText => BackendType switch public override string BackendBadgeText => this.BackendType switch
{ {
UnityBackendType.IL2CPP => "IL2CPP", UnityBackendType.IL2CPP => "IL2CPP",
UnityBackendType.Mono => "Mono", UnityBackendType.Mono => "Mono",
_ => "Unity" _ => "Unity"
}; };
/// <summary>
/// エンジン種別ラベル。Unityは専用バッジ(IL2CPP/Mono等)で表現するため空文字を返し、
/// エンジン種別ラベル自体は表示しません。
/// </summary>
public override string EngineLabelText => string.Empty;
} }
} }
@@ -1,9 +1,10 @@
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using GameLauncher.Models;
namespace GameLauncher.Models namespace GameLauncher.Engines.Unity
{ {
/// <summary> /// <summary>
/// PlayerPrefs(レジストリ)の1エントリを表すモデル /// PlayerPrefs(レジストリ)の1エントリを表すモデル
@@ -27,35 +28,35 @@ namespace GameLauncher.Models
/// <summary>レジストリの生キー名(例: ClearedLevel_h1378399435)</summary> /// <summary>レジストリの生キー名(例: ClearedLevel_h1378399435)</summary>
public string RawKey public string RawKey
{ {
get => _rawKey; get => this._rawKey;
set { if (_rawKey != value) { _rawKey = value; OnPropertyChanged(); } } set { if (this._rawKey != value) { this._rawKey = value; this.OnPropertyChanged(); } }
} }
/// <summary>Unityのハッシュを除去した整形式キー名(例: ClearedLevel)</summary> /// <summary>Unityのハッシュを除去した整形式キー名(例: ClearedLevel)</summary>
public string CleanKey public string CleanKey
{ {
get => _cleanKey; get => this._cleanKey;
set { if (_cleanKey != value) { _cleanKey = value; OnPropertyChanged(); } } set { if (this._cleanKey != value) { this._cleanKey = value; this.OnPropertyChanged(); } }
} }
/// <summary>値のデータ型</summary> /// <summary>値のデータ型</summary>
public PlayerPrefsType Type public PlayerPrefsType Type
{ {
get => _type; get => this._type;
set { if (_type != value) { _type = value; OnPropertyChanged(); OnPropertyChanged(nameof(TypeDisplay)); } } set { if (this._type != value) { this._type = value; this.OnPropertyChanged(); this.OnPropertyChanged(nameof(this.TypeDisplay)); } }
} }
/// <summary>実際の値(int, float, string, byte[])</summary> /// <summary>実際の値(int, float, string, byte[])</summary>
public object? Value public object? Value
{ {
get => _value; get => this._value;
set set
{ {
if (!Equals(_value, value)) if (!Equals(this._value, value))
{ {
_value = value; this._value = value;
OnPropertyChanged(); this.OnPropertyChanged();
UpdateEditValue(); this.UpdateEditValue();
} }
} }
} }
@@ -63,15 +64,15 @@ namespace GameLauncher.Models
/// <summary>UI表示・編集用の文字列値</summary> /// <summary>UI表示・編集用の文字列値</summary>
public string EditValue public string EditValue
{ {
get => _editValue; get => this._editValue;
set set
{ {
if (_editValue != value) if (this._editValue != value)
{ {
_editValue = value; this._editValue = value;
_isModified = true; this._isModified = true;
OnPropertyChanged(); this.OnPropertyChanged();
OnPropertyChanged(nameof(IsModified)); this.OnPropertyChanged(nameof(this.IsModified));
} }
} }
} }
@@ -79,11 +80,11 @@ namespace GameLauncher.Models
/// <summary>値が変更されたかどうか</summary> /// <summary>値が変更されたかどうか</summary>
public bool IsModified public bool IsModified
{ {
get => _isModified; get => this._isModified;
set { if (_isModified != value) { _isModified = value; OnPropertyChanged(); } } set { if (this._isModified != value) { this._isModified = value; this.OnPropertyChanged(); } }
} }
public string TypeDisplay => Type switch public string TypeDisplay => this.Type switch
{ {
PlayerPrefsType.Int => "Int (数値)", PlayerPrefsType.Int => "Int (数値)",
PlayerPrefsType.Float => "Float (小数)", PlayerPrefsType.Float => "Float (小数)",
@@ -94,19 +95,19 @@ namespace GameLauncher.Models
private void UpdateEditValue() private void UpdateEditValue()
{ {
if (_value == null) if (this._value == null)
{ {
_editValue = string.Empty; this._editValue = string.Empty;
} }
else if (_value is byte[] bytes) else if (this._value is byte[] bytes)
{ {
try try
{ {
var text = System.Text.Encoding.UTF8.GetString(bytes).TrimEnd('\0'); var text = System.Text.Encoding.UTF8.GetString(bytes).TrimEnd('\0');
if (text.All(c => !char.IsControl(c) || c == '\r' || c == '\n' || c == '\t')) if (text.All(c => !char.IsControl(c) || c == '\r' || c == '\n' || c == '\t'))
{ {
_editValue = text; this._editValue = text;
_type = PlayerPrefsType.String; this._type = PlayerPrefsType.String;
return; return;
} }
} }
@@ -117,21 +118,21 @@ namespace GameLauncher.Models
float f = BitConverter.ToSingle(bytes, 0); float f = BitConverter.ToSingle(bytes, 0);
if (!float.IsNaN(f) && !float.IsInfinity(f)) if (!float.IsNaN(f) && !float.IsInfinity(f))
{ {
_editValue = f.ToString("G"); this._editValue = f.ToString("G");
_type = PlayerPrefsType.Float; this._type = PlayerPrefsType.Float;
return; return;
} }
} }
_editValue = BitConverter.ToString(bytes).Replace("-", " "); this._editValue = BitConverter.ToString(bytes).Replace("-", " ");
} }
else else
{ {
_editValue = _value.ToString() ?? string.Empty; this._editValue = this._value.ToString() ?? string.Empty;
} }
_isModified = false; this._isModified = false;
OnPropertyChanged(nameof(EditValue)); this.OnPropertyChanged(nameof(this.EditValue));
OnPropertyChanged(nameof(IsModified)); this.OnPropertyChanged(nameof(this.IsModified));
} }
} }
@@ -151,13 +152,13 @@ namespace GameLauncher.Models
{ {
get get
{ {
if (FileSize < 1024) return $"{FileSize} B"; if (this.FileSize < 1024) return $"{this.FileSize} B";
if (FileSize < 1024 * 1024) return $"{FileSize / 1024.0:F1} KB"; if (this.FileSize < 1024 * 1024) return $"{this.FileSize / 1024.0:F1} KB";
return $"{FileSize / (1024.0 * 1024.0):F2} MB"; return $"{this.FileSize / (1024.0 * 1024.0):F2} MB";
} }
} }
public string LastModifiedDisplay => LastModified.ToString("yyyy/MM/dd HH:mm:ss"); public string LastModifiedDisplay => this.LastModified.ToString("yyyy/MM/dd HH:mm:ss");
} }
/// <summary> /// <summary>
@@ -171,6 +172,6 @@ namespace GameLauncher.Models
public string BackupType { get; set; } = string.Empty; // "Registry (.reg)" または "ファイル" public string BackupType { get; set; } = string.Empty; // "Registry (.reg)" または "ファイル"
public string Note { get; set; } = string.Empty; public string Note { get; set; } = string.Empty;
public string TimestampDisplay => Timestamp.ToString("yyyy/MM/dd HH:mm:ss"); public string TimestampDisplay => this.Timestamp.ToString("yyyy/MM/dd HH:mm:ss");
} }
} }
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
@@ -11,7 +11,7 @@ using Microsoft.Win32;
using GameLauncher.Helpers; using GameLauncher.Helpers;
using GameLauncher.Models; using GameLauncher.Models;
namespace GameLauncher.Services namespace GameLauncher.Engines.Unity
{ {
/// <summary> /// <summary>
/// UnityのPlayerPrefs(レジストリ)およびセーブファイル(LocalLow / ゲームフォルダ)の編集・バックアップを行うサービス /// UnityのPlayerPrefs(レジストリ)およびセーブファイル(LocalLow / ゲームフォルダ)の編集・バックアップを行うサービス
@@ -81,7 +81,7 @@ namespace GameLauncher.Services
catch { } catch { }
// キー名昇順でソート // キー名昇順でソート
return list.OrderBy(e => e.CleanKey, StringComparer.OrdinalIgnoreCase).ToList(); return [.. list.OrderBy(e => e.CleanKey, StringComparer.OrdinalIgnoreCase)];
} }
/// <summary> /// <summary>
@@ -319,7 +319,7 @@ namespace GameLauncher.Services
proc?.WaitForExit(3000); proc?.WaitForExit(3000);
// JSONバックアップも併せて出力 // JSONバックアップも併せて出力
var entries = GetPlayerPrefs(registryPath); var entries = this.GetPlayerPrefs(registryPath);
var jsonBackupFile = Path.Combine(backupDir, $"PlayerPrefs_{timestamp}.json"); var jsonBackupFile = Path.Combine(backupDir, $"PlayerPrefs_{timestamp}.json");
var serializableList = entries.Select(e => new var serializableList = entries.Select(e => new
{ {
@@ -416,7 +416,7 @@ namespace GameLauncher.Services
FileSize = fi.Length, FileSize = fi.Length,
LastModified = fi.LastWriteTime, LastModified = fi.LastWriteTime,
LocationType = "LocalLow", LocationType = "LocalLow",
IsTextOrJson = CheckIsTextOrJson(f) IsTextOrJson = this.CheckIsTextOrJson(f)
}); });
} }
} }
@@ -429,7 +429,7 @@ namespace GameLauncher.Services
try try
{ {
// ルート直下 // ルート直下
CollectCandidateFiles(game.RootDirectory, "ゲームフォルダ", list); this.CollectCandidateFiles(game.RootDirectory, "ゲームフォルダ", list);
// Save / SaveData / saves / savedata サブフォルダ // Save / SaveData / saves / savedata サブフォルダ
var subNames = new[] { "Save", "SaveData", "saves", "savedata", "Save_Data" }; var subNames = new[] { "Save", "SaveData", "saves", "savedata", "Save_Data" };
@@ -438,21 +438,21 @@ namespace GameLauncher.Services
var subPath = Path.Combine(game.RootDirectory, sub); var subPath = Path.Combine(game.RootDirectory, sub);
if (Directory.Exists(subPath)) if (Directory.Exists(subPath))
{ {
CollectCandidateFiles(subPath, "ゲームフォルダ/" + sub, list, isStrict: false); this.CollectCandidateFiles(subPath, "ゲームフォルダ/" + sub, list, isStrict: false);
} }
} }
// Dataフォルダ直下のセーブファイル候補 // Dataフォルダ直下のセーブファイル候補
if (!string.IsNullOrEmpty(game.DataDirectoryPath) && Directory.Exists(game.DataDirectoryPath)) if (!string.IsNullOrEmpty(game.DataDirectoryPath) && Directory.Exists(game.DataDirectoryPath))
{ {
CollectCandidateFiles(game.DataDirectoryPath, "Dataフォルダ", list); this.CollectCandidateFiles(game.DataDirectoryPath, "Dataフォルダ", list);
} }
} }
catch { } catch { }
} }
// 更新日時降順でソート // 更新日時降順でソート
return list.OrderByDescending(f => f.LastModified).ToList(); return [.. list.OrderByDescending(f => f.LastModified)];
} }
private void CollectCandidateFiles(string dir, string locationLabel, List<SaveFileEntry> list, bool isStrict = true) private void CollectCandidateFiles(string dir, string locationLabel, List<SaveFileEntry> list, bool isStrict = true)
@@ -494,7 +494,7 @@ namespace GameLauncher.Services
FileSize = fi.Length, FileSize = fi.Length,
LastModified = fi.LastWriteTime, LastModified = fi.LastWriteTime,
LocationType = locationLabel, LocationType = locationLabel,
IsTextOrJson = CheckIsTextOrJson(f) IsTextOrJson = this.CheckIsTextOrJson(f)
}); });
} }
} }
@@ -649,7 +649,7 @@ namespace GameLauncher.Services
} }
catch { } catch { }
return list.OrderByDescending(b => b.Timestamp).ToList(); return [.. list.OrderByDescending(b => b.Timestamp)];
} }
/// <summary> /// <summary>
+209
View File
@@ -0,0 +1,209 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GameLauncher.Helpers;
using GameLauncher.Models;
using GameLauncher.Engines.Tkool;
namespace GameLauncher.Engines.Wolf
{
/// <summary>
/// ウディタ(WOLF RPGエディター)の Data.wolf アーカイブの解凍・抽出・状態管理サービス
/// </summary>
public class WolfArchiveService
{
/// <summary>
/// 指定されたゲームフォルダ内に Data.wolf または .wolf アーカイブが存在するか判定します。
/// </summary>
public bool HasWolfArchive(string gameDirectory)
{
if (string.IsNullOrEmpty(gameDirectory) || !Directory.Exists(gameDirectory))
return false;
var dataWolf = Path.Combine(gameDirectory, "Data.wolf");
if (File.Exists(dataWolf)) return true;
try
{
return Directory.EnumerateFiles(gameDirectory, "*.wolf", SearchOption.TopDirectoryOnly).Any();
}
catch
{
return false;
}
}
/// <summary>
/// 指定されたゲームフォルダ内に Data.wolf の解凍先フォルダ(Data フォルダ)が存在するか判定します。
/// </summary>
public bool IsExtracted(string gameDirectory)
{
if (string.IsNullOrEmpty(gameDirectory) || !Directory.Exists(gameDirectory))
return false;
var dataDir = Path.Combine(gameDirectory, "Data");
return Directory.Exists(dataDir);
}
/// <summary>
/// 有効な Wolf 解凍ツールの実行ファイルパスを取得します。
/// </summary>
public string? ResolveExtractorPath(string? customPath)
{
// 1. ユーザー指定パス
if (!string.IsNullOrWhiteSpace(customPath) && File.Exists(customPath))
{
return customPath;
}
// 2. エンジン別ツールフォルダ (Engines\Wolf\Tools\UberWolfCli.exe) を優先解決
foreach (var toolName in new[] { "UberWolfCli.exe", "UberWolf.exe", "WolfDec.exe" })
{
var resolved = AppPathHelper.ResolveEngineTool("Wolf", toolName);
if (!string.IsNullOrEmpty(resolved) && File.Exists(resolved))
{
return resolved;
}
}
return null;
}
/// <summary>
/// Data.wolf を解凍・抽出します。
/// </summary>
public async Task<(bool success, string message)> ExtractArchiveAsync(
TkoolGameItem game,
string? customExtractorPath,
IProgress<string>? progress = null)
{
var gameDir = game.RootDirectory;
if (!Directory.Exists(gameDir))
{
return (false, "ゲームのルートディレクトリが見つかりません。");
}
var extractorPath = this.ResolveExtractorPath(customExtractorPath);
if (string.IsNullOrEmpty(extractorPath) || !File.Exists(extractorPath))
{
return (false, "Wolf RPG アーカイブ解凍ツール(UberWolfCli.exe / WolfDec.exe)が見つかりません。設定ダイアログからツールのパスを指定してください。");
}
// 解凍対象の探索 (Data.wolf または Game.exe)
var targetFile = Path.Combine(gameDir, "Data.wolf");
if (!File.Exists(targetFile))
{
var wolfFiles = Directory.GetFiles(gameDir, "*.wolf");
if (wolfFiles.Length > 0)
{
targetFile = wolfFiles[0];
}
else
{
targetFile = Path.Combine(gameDir, "Game.exe");
}
}
if (!File.Exists(targetFile))
{
return (false, "解凍対象の Data.wolf または Game.exe が見つかりません。");
}
progress?.Report($"[解凍開始] ツール: {Path.GetFileName(extractorPath)} 対象: {Path.GetFileName(targetFile)}");
try
{
// UberWolfCli.exe の場合は -o (上書き) -u (プロテクト解除) を渡す
var isUberWolf = Path.GetFileName(extractorPath).Contains("UberWolf", StringComparison.OrdinalIgnoreCase);
var arguments = isUberWolf
? $"-o -u \"{targetFile}\""
: $"\"{targetFile}\"";
var psi = new ProcessStartInfo
{
FileName = extractorPath,
Arguments = arguments,
WorkingDirectory = gameDir,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using var process = new Process { StartInfo = psi };
var outputLog = new System.Text.StringBuilder();
process.OutputDataReceived += (_, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
outputLog.AppendLine(e.Data);
progress?.Report(e.Data);
}
};
process.ErrorDataReceived += (_, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
outputLog.AppendLine(e.Data);
progress?.Report($"[情報] {e.Data}");
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await process.WaitForExitAsync();
var dataDir = Path.Combine(gameDir, "Data");
if (Directory.Exists(dataDir) && Directory.EnumerateFileSystemEntries(dataDir).Any())
{
progress?.Report($"[解凍完了] Data フォルダへの抽出に成功しました: {dataDir}");
return (true, "Data.wolf の解凍・抽出が完了しました。Data フォルダのファイルを直接編集・改造できます。");
}
else
{
return (false, $"解凍処理は終了しましたが、Data フォルダが確認できませんでした。\nログ: {outputLog}");
}
}
catch (Exception ex)
{
return (false, $"解凍処理中に例外が発生しました: {ex.Message}");
}
}
/// <summary>
/// 解凍された Data フォルダを Backups フォルダに退避し、元の Data.wolf 優先読み込み状態に復元します。
/// </summary>
public (bool success, string message) RestoreArchiveState(TkoolGameItem game)
{
var gameDir = game.RootDirectory;
var dataDir = Path.Combine(gameDir, "Data");
if (!Directory.Exists(dataDir))
{
return (true, "Data フォルダは存在しないため、既に元のアーカイブ読み込み状態です。");
}
try
{
// バックアップ保存先(Backups フォルダ)
var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var backupDataDir = Path.Combine(backupDir, $"Data_Extracted_{timestamp}");
// Data フォルダを Backups へ移動(元に戻す)
Directory.Move(dataDir, backupDataDir);
return (true, $"解凍されていた Data フォルダを Backups フォルダへ退避しました。\n(退避先: {backupDataDir})\n元の Data.wolf アーカイブ優先読み込みに復元されました。");
}
catch (Exception ex)
{
return (false, $"復元処理中にエラーが発生しました: {ex.Message}");
}
}
}
}
+216
View File
@@ -0,0 +1,216 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.Json;
using GameLauncher.Helpers;
using GameLauncher.Models;
using GameLauncher.Engines.Tkool;
namespace GameLauncher.Engines.Wolf
{
/// <summary>
/// ウディタ(WOLF RPGエディター)向けのプロキシDLL(メモリフック/スピードハック)
/// およびデバッグモード(テストプレイモード)管理サービス
/// </summary>
public class WolfModService
{
public const string ProxyDllName = "version.dll";
public const string ConfigFileName = "speedhack_config.json";
public const string GameExeBackupSuffix = ".original_launcher_backup";
/// <summary>
/// プロキシDLL(version.dll)がゲームフォルダ内に配置されているか判定します。
/// </summary>
public bool IsProxyDllInstalled(TkoolGameItem game)
{
if (string.IsNullOrEmpty(game.RootDirectory) || !Directory.Exists(game.RootDirectory))
return false;
var dllPath = Path.Combine(game.RootDirectory, ProxyDllName);
return File.Exists(dllPath);
}
/// <summary>
/// プロキシDLL(メモリフック/スピードハック)をゲームフォルダに適用します。
/// </summary>
/// <param name="game">対象のウディタゲーム</param>
/// <param name="baseSpeed">基本スピード倍率(1.0〜10.0)</param>
/// <param name="toggleSpeed">F6キー押下時のトグルスピード倍率(3.0など)</param>
/// <param name="holdSpeed">Ctrlキー押下時の早送り倍率(5.0など)</param>
public (bool success, string message) ApplyProxyDll(
TkoolGameItem game,
double baseSpeed = 1.0,
double toggleSpeed = 3.0,
double holdSpeed = 5.0)
{
var gameDir = game.RootDirectory;
if (!Directory.Exists(gameDir))
return (false, "ゲームディレクトリが見つかりません。");
try
{
// 1. プロキシDLL本体の探索 (Tools\speedhack-i686\version.dll)
var sourceDllPath = this.ResolveProxyDllPath();
if (string.IsNullOrEmpty(sourceDllPath) || !File.Exists(sourceDllPath))
{
return (false, "プロキシDLL(Engines\\Wolf\\Tools\\speedhack-i686\\version.dll)が見つかりません。");
}
var targetDllPath = Path.Combine(gameDir, ProxyDllName);
var targetConfigPath = Path.Combine(gameDir, ConfigFileName);
// 2. 元々同名DLLが存在していた場合は Backups フォルダに退避
var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var backupDllPath = Path.Combine(backupDir, ProxyDllName + GameExeBackupSuffix);
if (File.Exists(targetDllPath) && !File.Exists(backupDllPath))
{
File.Copy(targetDllPath, backupDllPath, overwrite: true);
}
// 3. プロキシDLLをコピー配置
File.Copy(sourceDllPath, targetDllPath, overwrite: true);
// 4. speedhack_config.json の生成・書き込み
var configContent = this.GenerateSpeedhackConfig(baseSpeed, toggleSpeed, holdSpeed);
File.WriteAllText(targetConfigPath, configContent, new UTF8Encoding(false));
game.WolfProxyDll = true;
game.IsModded = true;
return (true, $"プロキシDLL(version.dll)を配置しました。\n・[F6] キー: {toggleSpeed:0.#}倍速 トグル\n・[Ctrl] キー: {holdSpeed:0.#}倍速 早送り\n・通常速度: {baseSpeed:0.#}倍");
}
catch (Exception ex)
{
return (false, $"プロキシDLLの適用に失敗しました: {ex.Message}");
}
}
/// <summary>
/// プロキシDLLをゲームフォルダから削除し、初期状態に完全復元します。
/// </summary>
public (bool success, string message) RemoveProxyDll(TkoolGameItem game)
{
var gameDir = game.RootDirectory;
if (!Directory.Exists(gameDir))
return (false, "ゲームディレクトリが見つかりません。");
try
{
var targetDllPath = Path.Combine(gameDir, ProxyDllName);
var targetConfigPath = Path.Combine(gameDir, ConfigFileName);
var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var backupDllPath = Path.Combine(backupDir, ProxyDllName + GameExeBackupSuffix);
// 1. プロキシDLLの削除またはオリジナル復元
if (File.Exists(backupDllPath))
{
File.Copy(backupDllPath, targetDllPath, overwrite: true);
try { File.Delete(backupDllPath); } catch { }
}
else if (File.Exists(targetDllPath))
{
File.Delete(targetDllPath);
}
// 2. 設定ファイルの削除
if (File.Exists(targetConfigPath))
{
try { File.Delete(targetConfigPath); } catch { }
}
game.WolfProxyDll = false;
game.IsModded = false;
return (true, "プロキシDLL(version.dll)を解除し、ゲームを元の状態に復元しました。");
}
catch (Exception ex)
{
return (false, $"プロキシDLLの解除に失敗しました: {ex.Message}");
}
}
/// <summary>
/// 全ての改造(プロキシDLL、パッチ等)を解除し、ゲームを完全に元に戻します。
/// </summary>
public (bool success, string message) RestoreAllMods(TkoolGameItem game)
{
var sb = new StringBuilder();
// 1. プロキシDLLの解除
var (dllSuccess, dllMsg) = this.RemoveProxyDll(game);
sb.AppendLine(dllMsg);
// 2. Game.exe バックアップからの復元(存在する場合)
var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var backupExePath = Path.Combine(backupDir, "Game.exe" + GameExeBackupSuffix);
var gameExePath = Path.Combine(game.RootDirectory, "Game.exe");
if (File.Exists(backupExePath))
{
try
{
File.Copy(backupExePath, gameExePath, overwrite: true);
sb.AppendLine("・Game.exe をオリジナルバックアップから復元しました。");
}
catch (Exception ex)
{
sb.AppendLine($"・Game.exe の復元中にエラーが発生しました: {ex.Message}");
}
}
return (true, sb.ToString().Trim());
}
/// <summary>
/// speedhack-rs の version.dll の配置パスを探索・解決します。
/// </summary>
private string? ResolveProxyDllPath()
{
// エンジン別ツールフォルダ (Engines\Wolf\Tools\speedhack-i686\version.dll) を優先解決
var resolved = AppPathHelper.ResolveEngineTool("Wolf", Path.Combine("speedhack-i686", ProxyDllName));
if (!string.IsNullOrEmpty(resolved) && File.Exists(resolved))
{
return resolved;
}
// 互換: プロキシDLL直置きのケース
var direct = AppPathHelper.ResolveEngineTool("Wolf", ProxyDllName);
if (!string.IsNullOrEmpty(direct) && File.Exists(direct))
{
return direct;
}
return null;
}
/// <summary>
/// speedhack_config.json の JSON 文字列を生成します。
/// </summary>
private string GenerateSpeedhackConfig(double baseSpeed, double toggleSpeed, double holdSpeed)
{
var obj = new
{
console = false,
base_speed = baseSpeed,
speed_states = new object[]
{
new
{
keys = new[] { "F6" },
speed = toggleSpeed,
is_toggle = true
},
new
{
keys = new[] { "Control" },
speed = holdSpeed,
is_toggle = false
}
}
};
return JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true });
}
}
}
+401
View File
@@ -0,0 +1,401 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using GameLauncher.Helpers;
namespace GameLauncher.Engines.Wolf
{
/// <summary>
/// ウディタ(WOLF RPGエディター)セーブデータ内の1つの変数項目
/// </summary>
public class WolfVariableItem
{
public string Category { get; set; } = "通常変数";
public int Index { get; set; }
public string DisplayName { get; set; } = string.Empty;
public int Value { get; set; }
public int Offset { get; set; }
}
/// <summary>
/// ウディタセーブデータ内の可変データベース項目
/// </summary>
public class WolfDbItem
{
public string TypeName { get; set; } = string.Empty;
public int TypeId { get; set; }
public int DataId { get; set; }
public string DataName { get; set; } = string.Empty;
public int FieldId { get; set; }
public string FieldName { get; set; } = string.Empty;
public bool IsString { get; set; }
public int NumberValue { get; set; }
public string StringValue { get; set; } = string.Empty;
public int Offset { get; set; }
}
/// <summary>
/// ウディタセーブデータ内の文字列項目
/// </summary>
public class WolfStringItem
{
public int Offset { get; set; }
public int Length { get; set; }
public string Value { get; set; } = string.Empty;
}
/// <summary>
/// パース済みウディタセーブデータ
/// </summary>
public class WolfSaveData
{
public string FilePath { get; set; } = string.Empty;
public string FileName { get; set; } = string.Empty;
public string GameTitle { get; set; } = string.Empty;
public ushort FileVersion { get; set; }
public bool IsUtf8 { get; set; }
public byte[] RawDecryptedBytes { get; set; } = [];
public List<WolfVariableItem> Variables { get; set; } = [];
public List<WolfDbItem> DatabaseItems { get; set; } = [];
public List<WolfStringItem> Strings { get; set; } = [];
}
/// <summary>
/// WOLF RPGエディターのセーブデータ(SaveXX.sav)の復号・暗号化・解析・編集サービス
/// </summary>
public class WolfSaveService
{
private const int START_OFFSET = 0x14;
private static readonly uint[] INC_STEPS = [1, 2, 5];
private static readonly uint[] ENC_INC_STEPS = [5, 2, 1];
static WolfSaveService()
{
// Shift-JIS (932) のサポート登録
try
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
catch { }
}
/// <summary>
/// 指定されたゲームディレクトリからセーブデータファイル一覧を取得します。
/// </summary>
public List<string> GetSaveFiles(string gameDirectory)
{
var result = new List<string>();
if (string.IsNullOrEmpty(gameDirectory) || !Directory.Exists(gameDirectory))
return result;
var searchDirs = new List<string> { gameDirectory };
var saveSubDir = Path.Combine(gameDirectory, "Save");
if (Directory.Exists(saveSubDir)) searchDirs.Add(saveSubDir);
var saveSubDir2 = Path.Combine(gameDirectory, "save");
if (Directory.Exists(saveSubDir2) && !searchDirs.Contains(saveSubDir2)) searchDirs.Add(saveSubDir2);
foreach (var dir in searchDirs)
{
try
{
var files = Directory.GetFiles(dir, "*.sav")
.OrderBy(f => Path.GetFileName(f), StringComparer.OrdinalIgnoreCase);
result.AddRange(files);
}
catch { }
}
return [.. result.Distinct(StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// 暗号化されたウディタセーブデータを復号します。
/// </summary>
public byte[] Decrypt(byte[] encryptedData)
{
if (encryptedData == null || encryptedData.Length < START_OFFSET)
return encryptedData ?? [];
byte[] copy = (byte[])encryptedData.Clone();
byte[] seeds = [copy[0], copy[3], copy[9]];
for (int i = 0; i < seeds.Length; i++)
{
uint state = seeds[i];
int inc = (int)INC_STEPS[i];
for (int j = START_OFFSET; j < copy.Length; j += inc)
{
state = state * 214013 + 2531011;
int r = (int)((state >> 16) & 0x7FFF);
byte xor = (byte)((r >> 12) & 0xFF);
copy[j] ^= xor;
}
}
return copy;
}
/// <summary>
/// 復号状態のウディタセーブデータを暗号化します(チェックサム自動更新付き)。
/// </summary>
public byte[] Encrypt(byte[] plainData)
{
if (plainData == null || plainData.Length < START_OFFSET)
return plainData ?? [];
byte[] copy = (byte[])plainData.Clone();
// 1. チェックサムの再計算 (オフセット 0x14 からの総和を 0x02 に格納)
byte checksum = 0;
for (int i = START_OFFSET; i < copy.Length; i++)
{
checksum += copy[i];
}
copy[0x02] = checksum;
// 2. 暗号化 (seeds は copy[9], copy[3], copy[0] の逆順、インクリメントも 5, 2, 1)
byte[] seeds = [copy[9], copy[3], copy[0]];
for (int i = 0; i < seeds.Length; i++)
{
uint state = seeds[i];
int inc = (int)ENC_INC_STEPS[i];
for (int j = START_OFFSET; j < copy.Length; j += inc)
{
state = state * 214013 + 2531011;
int r = (int)((state >> 16) & 0x7FFF);
byte xor = (byte)((r >> 12) & 0xFF);
copy[j] ^= xor;
}
}
return copy;
}
/// <summary>
/// セーブファイルを読み込み、復号してパースします。
/// </summary>
public WolfSaveData LoadSave(string filePath)
{
if (!File.Exists(filePath))
throw new FileNotFoundException($"セーブデータファイルが見つかりません: {filePath}");
byte[] rawBytes = File.ReadAllBytes(filePath);
byte[] decrypted = this.Decrypt(rawBytes);
var result = new WolfSaveData
{
FilePath = filePath,
FileName = Path.GetFileName(filePath),
RawDecryptedBytes = decrypted
};
if (decrypted.Length < 0x20) return result;
// 文字エンコーディング判定 (オフセット6が 0x55 なら UTF-8, それ以外は Shift-JIS)
result.IsUtf8 = (decrypted[6] == 0x55);
Encoding enc = result.IsUtf8 ? Encoding.UTF8 : Encoding.GetEncoding(932);
// ゲームタイトルの取得 (オフセット 0x15 からの文字列)
if (decrypted[0x14] == 0x19 && decrypted.Length > 0x17)
{
ushort titleLen = BitConverter.ToUInt16(decrypted, 0x15);
if (titleLen > 1 && 0x17 + titleLen <= decrypted.Length)
{
result.GameTitle = enc.GetString(decrypted, 0x17, titleLen - 1).Trim('\0');
int nextOffset = 0x17 + titleLen;
if (nextOffset + 2 <= decrypted.Length)
{
result.FileVersion = BitConverter.ToUInt16(decrypted, nextOffset);
}
}
}
// セーブデータ内の全文字列スキャン
this.ScanStrings(result, decrypted, enc);
// セーブデータ内の通常変数スキャン
this.ScanVariables(result, decrypted);
return result;
}
/// <summary>
/// 文字列の検出スキャン
/// </summary>
private void ScanStrings(WolfSaveData model, byte[] data, Encoding enc)
{
for (int i = START_OFFSET; i < data.Length - 4; i++)
{
uint strLen = BitConverter.ToUInt32(data, i);
if (strLen >= 2 && strLen <= 128 && i + 4 + strLen <= data.Length)
{
// 末尾がNULL終端かチェック
if (data[i + 4 + strLen - 1] == 0)
{
try
{
string s = enc.GetString(data, i + 4, (int)strLen - 1);
// 意味のあるテキストか判定(2文字以上の文字、制御文字を含まない)
if (s.Length >= 2 && !s.Any(c => char.IsControl(c) && c != '\r' && c != '\n' && c != '\t'))
{
model.Strings.Add(new WolfStringItem
{
Offset = i + 4,
Length = (int)strLen - 1,
Value = s
});
}
}
catch { }
}
}
}
}
/// <summary>
/// 変数テーブルのスキャン(32bit整数群)
/// </summary>
private void ScanVariables(WolfSaveData model, byte[] data)
{
// 4バイト境界に沿って整数値を抽出(特に100以上の意味ありそうな数値やステータス)
int varIdx = 0;
for (int i = 0x50; i < data.Length - 4; i += 4)
{
int val = BitConverter.ToInt32(data, i);
// 範囲制限(極端に大きなゴミデータや負の値のノイズを適度にフィルタ)
if (val >= 0 && val <= 999999999)
{
model.Variables.Add(new WolfVariableItem
{
Category = "通常・内部変数",
Index = varIdx++,
DisplayName = $"変数 [0x{i:X5}]",
Value = val,
Offset = i
});
}
}
}
/// <summary>
/// セーブファイルをバックアップしてから上書き保存します。
/// バックアップは必ず Z:\自作ソフト\GameLauncher\Backups に保存されます。
/// </summary>
public string SaveToFile(WolfSaveData model, string folderName, string rootDirectory)
{
if (model == null || model.RawDecryptedBytes == null || model.RawDecryptedBytes.Length == 0)
throw new InvalidOperationException("保存対象のデータが空です。");
// 1. バックアップ作成 (Backups フォルダへ)
string? backupPath = this.BackupSaveFile(model.FilePath, folderName, rootDirectory);
// 2. 変数・項目の変更を RawDecryptedBytes に書き戻し
foreach (var item in model.Variables)
{
if (item.Offset >= START_OFFSET && item.Offset + 4 <= model.RawDecryptedBytes.Length)
{
byte[] valBytes = BitConverter.GetBytes(item.Value);
Buffer.BlockCopy(valBytes, 0, model.RawDecryptedBytes, item.Offset, 4);
}
}
// 3. 暗号化 & チェックサム再計算
byte[] encrypted = this.Encrypt(model.RawDecryptedBytes);
// 4. アトミック書き込み
string tempFile = model.FilePath + ".tmp_" + Guid.NewGuid().ToString("N");
File.WriteAllBytes(tempFile, encrypted);
File.Move(tempFile, model.FilePath, overwrite: true);
return backupPath ?? string.Empty;
}
/// <summary>
/// セーブデータのバックアップを作成します。
/// </summary>
public string? BackupSaveFile(string saveFilePath, string folderName, string rootDirectory)
{
if (!File.Exists(saveFilePath)) return null;
try
{
var backupDir = AppPathHelper.GetGameBackupDirectory(folderName, rootDirectory);
if (!Directory.Exists(backupDir))
{
Directory.CreateDirectory(backupDir);
}
var fileName = Path.GetFileNameWithoutExtension(saveFilePath);
var ext = Path.GetExtension(saveFilePath);
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var destName = $"{fileName}_{timestamp}{ext}";
var destPath = Path.Combine(backupDir, destName);
File.Copy(saveFilePath, destPath, overwrite: true);
return destPath;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[WolfSaveService] Backup error: {ex.Message}");
return null;
}
}
/// <summary>
/// セーブデータを JSON 形式でエクスポートします。
/// </summary>
public void ExportToJson(WolfSaveData model, string jsonFilePath)
{
var dto = new
{
model.FileName,
model.GameTitle,
model.FileVersion,
model.IsUtf8,
Variables = model.Variables.Select(v => new { v.Offset, v.DisplayName, v.Value }),
Strings = model.Strings.Select(s => new { s.Offset, s.Length, s.Value })
};
var options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize(dto, options);
File.WriteAllText(jsonFilePath, json, Encoding.UTF8);
}
/// <summary>
/// JSON 形式の編集内容をセーブデータモデルへインポート・反映します。
/// </summary>
public void ImportFromJson(WolfSaveData model, string jsonFilePath)
{
if (!File.Exists(jsonFilePath))
throw new FileNotFoundException($"JSONファイルが見つかりません: {jsonFilePath}");
string json = File.ReadAllText(jsonFilePath, Encoding.UTF8);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.TryGetProperty("Variables", out var varsElement) && varsElement.ValueKind == JsonValueKind.Array)
{
var varDict = model.Variables.ToDictionary(v => v.Offset, v => v);
foreach (var item in varsElement.EnumerateArray())
{
if (item.TryGetProperty("Offset", out var offsetProp) &&
item.TryGetProperty("Value", out var valProp))
{
int offset = offsetProp.GetInt32();
int val = valProp.GetInt32();
if (varDict.TryGetValue(offset, out var entry))
{
entry.Value = val;
}
}
}
}
}
}
}
+20 -1
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
@@ -14,8 +14,19 @@
<PublishSingleFile>true</PublishSingleFile> <PublishSingleFile>true</PublishSingleFile>
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract> <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
<DebugType>embedded</DebugType> <DebugType>embedded</DebugType>
<ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Remove="Engines\Nwjs\NwjsUnpackerToolProvider.cs" />
</ItemGroup>
<ItemGroup>
<None Remove="Engines\Nwjs\Tools\speedhack-i686\hid.dll" />
<None Remove="Engines\Nwjs\Tools\speedhack-i686\version.dll" />
<None Remove="plugins\AlwaysMaxHpMp.js" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<None Update="plugins\**"> <None Update="plugins\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
@@ -23,6 +34,14 @@
<None Update="Config.tjs"> <None Update="Config.tjs">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<!-- 各エンジンの外部ツール(例: EVB 解凍ツール evbunpack.exe)をビルド出力へコピー -->
<None Update="Engines\**\Tools\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="Engines\Nwjs\Tools\speedhack-i686\" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+1 -1
View File
@@ -1,3 +1,3 @@
<Solution> <Solution>
<Project Path="GameLauncher.csproj" /> <Project Path="GameLauncher.csproj" />
</Solution> </Solution>
+110 -1
View File
@@ -1,4 +1,4 @@
using System; using System;
using System.IO; using System.IO;
namespace GameLauncher.Helpers namespace GameLauncher.Helpers
@@ -157,6 +157,24 @@ namespace GameLauncher.Helpers
return path; return path;
} }
/// <summary>
/// サムネイル画像キャッシュの格納ルートディレクトリを取得します。
/// GameLauncher.exe のあるフォルダ直下の「Thumbnails」フォルダを使用・作成します。
/// </summary>
public static string GetThumbnailsDirectory()
{
var thumbDir = Path.Combine(GetExeDirectory(), "Thumbnails");
if (!Directory.Exists(thumbDir))
{
try
{
Directory.CreateDirectory(thumbDir);
}
catch { }
}
return thumbDir;
}
/// <summary> /// <summary>
/// Unityセーブデータバックアップ全体の格納ルートディレクトリを取得します。 /// Unityセーブデータバックアップ全体の格納ルートディレクトリを取得します。
/// GameLauncher.exe のあるフォルダ直下の「Backups」フォルダを使用・作成します。 /// GameLauncher.exe のあるフォルダ直下の「Backups」フォルダを使用・作成します。
@@ -164,6 +182,24 @@ namespace GameLauncher.Helpers
/// </summary> /// </summary>
public static string GetBackupsDirectory() public static string GetBackupsDirectory()
{ {
// ユーザー指定ルール: バックアップは全て Z:\自作ソフト\GameLauncher\Backups (exe直下のBackupsフォルダ) で行う
var prodBackups = @"Z:\自作ソフト\GameLauncher\Backups";
if (Directory.Exists(@"Z:\自作ソフト\GameLauncher"))
{
try
{
if (!Directory.Exists(prodBackups))
{
Directory.CreateDirectory(prodBackups);
}
if (Directory.Exists(prodBackups))
{
return prodBackups;
}
}
catch { }
}
var exeBackups = Path.Combine(GetExeDirectory(), "Backups"); var exeBackups = Path.Combine(GetExeDirectory(), "Backups");
try try
@@ -255,5 +291,78 @@ namespace GameLauncher.Helpers
CopyDirectory(sub, destSub); CopyDirectory(sub, destSub);
} }
} }
/// <summary>
/// Gets the engine-specific tools directory, e.g. "Engines/Wolf/Tools".
/// External tools are grouped per engine so that each engine only references
/// its own tools and never depends on another engine's files.
/// </summary>
/// <param name="engineName">Engine identifier ("Rgss", "Wolf", "Nwjs", ...).</param>
/// <returns>Absolute path to the engine tools directory (created when possible).</returns>
public static string GetEngineToolsDirectory(string engineName)
{
var safeEngine = string.IsNullOrWhiteSpace(engineName) ? "Common" : engineName.Trim();
var path = Path.Combine(GetExeDirectory(), "Engines", safeEngine, "Tools");
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch { }
return path;
}
/// <summary>
/// Resolves an engine-specific external tool file path.
/// Searches the deployed location, the production folder, and the source
/// tree fallback, returning the first existing candidate or null.
/// </summary>
/// <param name="engineName">Engine identifier ("Rgss", "Wolf", "Nwjs", ...).</param>
/// <param name="toolFileName">Tool file name (e.g. "UberWolfCli.exe").</param>
/// <returns>Absolute path to the tool, or null if not found.</returns>
public static string? ResolveEngineTool(string engineName, string toolFileName)
{
if (string.IsNullOrWhiteSpace(engineName) || string.IsNullOrWhiteSpace(toolFileName))
{
return null;
}
var safeEngine = engineName.Trim();
var exeDir = GetExeDirectory();
var candidates = new[]
{
Path.Combine(exeDir, "Engines", safeEngine, "Tools", toolFileName),
Path.Combine(AppContext.BaseDirectory, "Engines", safeEngine, "Tools", toolFileName),
Path.Combine(exeDir, "Engines", safeEngine, "Tools"),
};
// First two candidates are full file paths; check those directly.
for (var i = 0; i < 2; i++)
{
if (File.Exists(candidates[i]))
{
return candidates[i];
}
}
// Fallbacks for development-time source layout.
var devFallbacks = new[]
{
$@"C:\VS2026\GameLauncher\Engines\{safeEngine}\Tools\{toolFileName}",
$@"Z:\自作ソフト\GameLauncher\Engines\{safeEngine}\Tools\{toolFileName}",
};
foreach (var candidate in devFallbacks)
{
if (File.Exists(candidate))
{
return candidate;
}
}
return null;
}
} }
} }
+43 -1
View File
@@ -1,8 +1,10 @@
using System; using System;
using System.Globalization; using System.Globalization;
using System.Windows; using System.Windows;
using System.Windows.Data; using System.Windows.Data;
using GameLauncher.Models; using GameLauncher.Models;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Unity;
namespace GameLauncher.Helpers namespace GameLauncher.Helpers
{ {
@@ -106,4 +108,44 @@ namespace GameLauncher.Helpers
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }
/// <summary>
/// 文字列が null または空文字(空白のみ含む)の場合に Collapsed、文字が存在する場合に Visible を返すコンバーター
/// </summary>
public class StringNotEmptyToVisibilityConverter : IValueConverter
{
public static readonly StringNotEmptyToVisibilityConverter Instance = new();
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is string s && !string.IsNullOrWhiteSpace(s))
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
/// <summary>
/// bool値が true の場合に Visible、false または null の場合に Collapsed を返すコンバーター
/// </summary>
public class BooleanToVisibilityConverter : IValueConverter
{
public static readonly BooleanToVisibilityConverter Instance = new();
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return value is true ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return value is Visibility v && v == Visibility.Visible;
}
}
} }
+602 -175
View File
File diff suppressed because it is too large. Load diff
+1451 -352
View File
File diff suppressed because it is too large. Load diff
+282 -39
View File
@@ -1,9 +1,11 @@
using System; using System;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.ComponentModel; using System.ComponentModel;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Windows; using System.Windows;
using System.Windows.Media; using System.Windows.Media;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Unity;
namespace GameLauncher.Models namespace GameLauncher.Models
{ {
@@ -20,6 +22,7 @@ namespace GameLauncher.Models
private ImageSource? _iconImage; private ImageSource? _iconImage;
private DateTime? _lastLaunched; private DateTime? _lastLaunched;
private DateTime? _folderLastModified; private DateTime? _folderLastModified;
private bool _isBookmarked;
public event PropertyChangedEventHandler? PropertyChanged; public event PropertyChangedEventHandler? PropertyChanged;
@@ -31,51 +34,51 @@ namespace GameLauncher.Models
/// <summary>ゲームの表示タイトル</summary> /// <summary>ゲームの表示タイトル</summary>
public string Title public string Title
{ {
get => _title; get => this._title;
set { if (_title != value) { _title = value; OnPropertyChanged(); } } set { if (this._title != value) { this._title = value; this.OnPropertyChanged(); } }
} }
/// <summary>フォルダ名</summary> /// <summary>フォルダ名</summary>
public string FolderName public string FolderName
{ {
get => _folderName; get => this._folderName;
set { if (_folderName != value) { _folderName = value; OnPropertyChanged(); } } set { if (this._folderName != value) { this._folderName = value; this.OnPropertyChanged(); } }
} }
/// <summary>ゲームのルートディレクトリ絶対パス</summary> /// <summary>ゲームのルートディレクトリ絶対パス</summary>
public string RootDirectory public string RootDirectory
{ {
get => _rootDirectory; get => this._rootDirectory;
set { if (_rootDirectory != value) { _rootDirectory = value; OnPropertyChanged(); } } set { if (this._rootDirectory != value) { this._rootDirectory = value; this.OnPropertyChanged(); } }
} }
/// <summary>ゲームの実行ファイル(.exe等)絶対パス</summary> /// <summary>ゲームの実行ファイル(.exe等)絶対パス</summary>
public string ExecutablePath public string ExecutablePath
{ {
get => _executablePath; get => this._executablePath;
set { if (_executablePath != value) { _executablePath = value; OnPropertyChanged(); } } set { if (this._executablePath != value) { this._executablePath = value; this.OnPropertyChanged(); } }
} }
/// <summary>アプリアイコン画像</summary> /// <summary>アプリアイコン画像</summary>
public ImageSource? IconImage public ImageSource? IconImage
{ {
get => _iconImage; get => this._iconImage;
set { if (_iconImage != value) { _iconImage = value; OnPropertyChanged(); } } set { if (this._iconImage != value) { this._iconImage = value; this.OnPropertyChanged(); } }
} }
/// <summary>ランチャーからの最終起動日時</summary> /// <summary>ランチャーからの最終起動日時</summary>
public DateTime? LastLaunched public DateTime? LastLaunched
{ {
get => _lastLaunched; get => this._lastLaunched;
set set
{ {
if (_lastLaunched != value) if (this._lastLaunched != value)
{ {
_lastLaunched = value; this._lastLaunched = value;
OnPropertyChanged(); this.OnPropertyChanged();
OnPropertyChanged(nameof(LastLaunchedDisplay)); this.OnPropertyChanged(nameof(this.LastLaunchedDisplay));
OnPropertyChanged(nameof(LastLaunchedCardDisplay)); this.OnPropertyChanged(nameof(this.LastLaunchedCardDisplay));
OnPropertyChanged(nameof(LastLaunchedDetailDisplay)); this.OnPropertyChanged(nameof(this.LastLaunchedDetailDisplay));
} }
} }
} }
@@ -83,48 +86,111 @@ namespace GameLauncher.Models
/// <summary>フォルダ更新日時</summary> /// <summary>フォルダ更新日時</summary>
public DateTime? FolderLastModified public DateTime? FolderLastModified
{ {
get => _folderLastModified; get => this._folderLastModified;
set set
{ {
if (_folderLastModified != value) if (this._folderLastModified != value)
{ {
_folderLastModified = value; this._folderLastModified = value;
OnPropertyChanged(); this.OnPropertyChanged();
OnPropertyChanged(nameof(FolderLastModifiedDisplay)); this.OnPropertyChanged(nameof(this.FolderLastModifiedDisplay));
OnPropertyChanged(nameof(FolderLastModifiedCardDisplay)); this.OnPropertyChanged(nameof(this.FolderLastModifiedCardDisplay));
OnPropertyChanged(nameof(FolderLastModifiedDetailDisplay)); this.OnPropertyChanged(nameof(this.FolderLastModifiedDetailDisplay));
} }
} }
} }
/// <summary>ユーザーによるブックマーク登録状態</summary>
public bool IsBookmarked
{
get => this._isBookmarked;
set
{
if (this._isBookmarked != value)
{
this._isBookmarked = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.BookmarkIcon));
this.OnPropertyChanged(nameof(this.BookmarkTooltip));
this.OnPropertyChanged(nameof(this.BookmarkButtonText));
this.OnPropertyChanged(nameof(this.BookmarkBrush));
}
}
}
public string BookmarkIcon => this._isBookmarked ? "★" : "☆";
public string BookmarkTooltip => this._isBookmarked ? "ブックマーク解除" : "ブックマークに追加";
public string BookmarkButtonText => this._isBookmarked ? "★ ブックマーク中" : "☆ ブックマーク";
public Brush BookmarkBrush => this._isBookmarked
? new SolidColorBrush(Color.FromRgb(0xFD, 0xCB, 0x6E))
: new SolidColorBrush(Color.FromArgb(0x88, 0xAA, 0xAA, 0xBB));
/// <summary>ゲームエンジンの種別</summary> /// <summary>ゲームエンジンの種別</summary>
public abstract GameEngineKind EngineKind { get; } public abstract GameEngineKind EngineKind { get; }
public bool IsTkoolOrTyrano => EngineKind is GameEngineKind.Tkool or GameEngineKind.Tyrano; public bool IsTkoolOrTyrano => this.EngineKind is GameEngineKind.Tkool or GameEngineKind.Tyrano;
public bool IsUnity => EngineKind == GameEngineKind.Unity; public bool IsUnity => this.EngineKind == GameEngineKind.Unity;
public string LastLaunchedDisplay => LastLaunched.HasValue /// <summary>Enigma Virtual Box でパックされたゲームか</summary>
? LastLaunched.Value.ToString("yyyy/MM/dd HH:mm") public virtual bool IsEvb => false;
/// <summary>Enigma Virtual Box でパックされた exe を持つゲームかどうか</summary>
public virtual bool IsEvbPacked
{
get => false;
set { }
}
/// <summary>EVB 解凍済みかどうか</summary>
public virtual bool IsEvbExtracted
{
get => false;
set { }
}
/// <summary>EVB バッジの可視性(該当しなければ Collapsed)</summary>
public virtual Visibility EvbBadgeVisibility => Visibility.Collapsed;
/// <summary>EVB バッジのテキスト(該当しなければ空文字)</summary>
public virtual string EvbBadgeText => string.Empty;
/// <summary>EVB 要解凍バッジの可視性(該当しなければ Collapsed)</summary>
public virtual Visibility EvbNeedsUnpackVisibility => Visibility.Collapsed;
/// <summary>EVB 要解凍バッジのテキスト(該当しなければ空文字)</summary>
public virtual string EvbNeedsUnpackBadgeText => string.Empty;
/// <summary>EVB 解凍済みバッジの可視性(該当しなければ Collapsed)</summary>
public virtual Visibility EvbExtractedVisibility => Visibility.Collapsed;
/// <summary>EVB 解凍済みバッジのテキスト(該当しなければ空文字)</summary>
public virtual string EvbExtractedBadgeText => string.Empty;
/// <summary>EVB 詳細状態テキスト</summary>
public virtual string EvbDetailStatusText => string.Empty;
public string LastLaunchedDisplay => this.LastLaunched.HasValue
? this.LastLaunched.Value.ToString("yyyy/MM/dd HH:mm")
: "未起動"; : "未起動";
public string LastLaunchedCardDisplay => LastLaunched.HasValue public string LastLaunchedCardDisplay => this.LastLaunched.HasValue
? $"▶ {LastLaunched.Value:yy/MM/dd HH:mm}" ? $"▶ {this.LastLaunched.Value:yy/MM/dd HH:mm}"
: "▶ 未起動"; : "▶ 未起動";
public string LastLaunchedDetailDisplay => LastLaunched.HasValue public string LastLaunchedDetailDisplay => this.LastLaunched.HasValue
? LastLaunched.Value.ToString("yyyy/MM/dd HH:mm:ss") ? this.LastLaunched.Value.ToString("yyyy/MM/dd HH:mm:ss")
: "まだ起動されていません"; : "まだ起動されていません";
public string FolderLastModifiedDisplay => FolderLastModified.HasValue public string FolderLastModifiedDisplay => this.FolderLastModified.HasValue
? FolderLastModified.Value.ToString("yyyy/MM/dd HH:mm") ? this.FolderLastModified.Value.ToString("yyyy/MM/dd HH:mm")
: "-"; : "-";
public string FolderLastModifiedCardDisplay => FolderLastModified.HasValue public string FolderLastModifiedCardDisplay => this.FolderLastModified.HasValue
? $"📁 {FolderLastModified.Value:yy/MM/dd HH:mm}" ? $"📁 {this.FolderLastModified.Value:yy/MM/dd HH:mm}"
: "📁 -"; : "📁 -";
public string FolderLastModifiedDetailDisplay => FolderLastModified.HasValue public string FolderLastModifiedDetailDisplay => this.FolderLastModified.HasValue
? FolderLastModified.Value.ToString("yyyy/MM/dd HH:mm:ss") ? this.FolderLastModified.Value.ToString("yyyy/MM/dd HH:mm:ss")
: "不明"; : "不明";
// ================= バッジ・UIバインディング共通仮想プロパティ ================= // ================= バッジ・UIバインディング共通仮想プロパティ =================
@@ -134,9 +200,135 @@ namespace GameLauncher.Models
/// <summary>ツクールMZか</summary> /// <summary>ツクールMZか</summary>
public virtual bool IsMZ => false; public virtual bool IsMZ => false;
/// <summary>ツクールVXか</summary>
public virtual bool IsVX => false;
/// <summary>ツクールVX Aceか</summary>
public virtual bool IsVXAce => false;
/// <summary>RGSS系(VX / VX Ace)か</summary>
public virtual bool IsRgss => false;
/// <summary>ティラノスクリプトか</summary> /// <summary>ティラノスクリプトか</summary>
public virtual bool IsTyrano => false; public virtual bool IsTyrano => false;
/// <summary>WOLF RPGエディター(ウディタ)か</summary>
public virtual bool IsWolf => false;
/// <summary>SRPG Studioか</summary>
public virtual bool IsSrpgStudio => false;
/// <summary>NW.js汎用ゲームか</summary>
public virtual bool IsNwjs => false;
/// <summary>その他のゲームエンジンか</summary>
public virtual bool IsOther => false;
/// <summary>
/// エンジン種別ラベルの表示文字列。空文字の場合はラベル自体を表示しません。
/// (Unity等は該当しないため空、ツクール系は MV/MZ 等を返す)
/// </summary>
public virtual string EngineLabelText => string.Empty;
/// <summary>エンジン種別ラベルの背景色</summary>
public virtual Brush EngineLabelBackground => Brushes.Transparent;
/// <summary>その他バッジの可視性(該当しなければ Collapsed)</summary>
public virtual Visibility OtherBadgeVisibility => Visibility.Collapsed;
/// <summary>プリンセスシナジー(専用改造対象のMZゲーム)か</summary>
public virtual bool IsPrincessSynergy => false;
/// <summary>RGSSアーカイブ(rgss3a/rgss2a等)を持つか</summary>
public virtual bool HasRgssArchive
{
get => false;
set { }
}
/// <summary>RGSSアーカイブが抽出済み(Scripts.rvdata/rvdata2が存在)か</summary>
public virtual bool IsRgssExtracted
{
get => false;
set { }
}
/// <summary>Wolfアーカイブ(Data.wolf等)を持つか</summary>
public virtual bool HasWolfArchive
{
get => false;
set { }
}
/// <summary>Wolfアーカイブが解凍済み(Dataフォルダが存在)か</summary>
public virtual bool IsWolfExtracted
{
get => false;
set { }
}
/// <summary>ウディタアーカイブバッジのテキスト(該当しなければ空文字)</summary>
public virtual string WolfArchiveBadgeText => string.Empty;
/// <summary>ウディタアーカイブバッジの背景色</summary>
public virtual Brush WolfArchiveBadgeBackground => Brushes.Transparent;
/// <summary>ウディタアーカイブバッジの可視性(該当しなければ Collapsed)</summary>
public virtual Visibility WolfArchiveBadgeVisibility => Visibility.Collapsed;
/// <summary>ウディタアーカイブ詳細状態テキスト</summary>
public virtual string WolfArchiveDetailStatusText => string.Empty;
/// <summary>SRPG Studioアーカイブ(data.dts)を持つか</summary>
public virtual bool HasSrpgArchive
{
get => false;
set { }
}
/// <summary>SRPG Studioアーカイブが解凍済み(data_extracted等が存在)か</summary>
public virtual bool IsSrpgExtracted
{
get => false;
set { }
}
/// <summary>RGSSバッジのテキスト</summary>
public virtual string RgssBadgeText => string.Empty;
/// <summary>RGSSバッジの背景色</summary>
public virtual Brush RgssBadgeBackground => Brushes.Transparent;
/// <summary>RGSSバッジの可視性</summary>
public virtual Visibility RgssBadgeVisibility => Visibility.Collapsed;
/// <summary>RGSS詳細状態テキスト</summary>
public virtual string RgssDetailStatusText => string.Empty;
/// <summary>SRPG Studioバッジのテキスト</summary>
public virtual string SrpgBadgeText => string.Empty;
/// <summary>SRPG Studioバッジの背景色</summary>
public virtual Brush SrpgBadgeBackground => Brushes.Transparent;
/// <summary>SRPG Studioバッジの可視性</summary>
public virtual Visibility SrpgBadgeVisibility => Visibility.Collapsed;
/// <summary>SRPG Studio詳細状態テキスト</summary>
public virtual string SrpgDetailStatusText => string.Empty;
/// <summary>NW.jsバッジのテキスト</summary>
public virtual string NwjsBadgeText => string.Empty;
/// <summary>NW.jsバッジの背景色</summary>
public virtual Brush NwjsBadgeBackground => Brushes.Transparent;
/// <summary>NW.jsバッジの可視性</summary>
public virtual Visibility NwjsBadgeVisibility => Visibility.Collapsed;
/// <summary>NW.js詳細状態テキスト</summary>
public virtual string NwjsDetailStatusText => string.Empty;
/// <summary>Unity IL2CPPか</summary> /// <summary>Unity IL2CPPか</summary>
public virtual bool IsIL2CPP => false; public virtual bool IsIL2CPP => false;
@@ -212,5 +404,56 @@ namespace GameLauncher.Models
get => _emptyPluginOptions; get => _emptyPluginOptions;
set { } set { }
} }
/// <summary>共通プラグイン設定コレクション</summary>
public virtual ObservableCollection<ModPluginOptionItem> CommonPluginOptions
{
get => _emptyPluginOptions;
set { }
}
/// <summary>固有ゲーム専用プラグイン設定コレクション</summary>
public virtual ObservableCollection<ModPluginOptionItem> SpecificPluginOptions
{
get => _emptyPluginOptions;
set { }
}
/// <summary>固有ゲーム専用プラグインが存在するかどうか</summary>
public virtual bool HasSpecificPlugins => false;
/// <summary>プリンセスシナジー専用: HP常時MAX</summary>
public virtual bool PrincessAlwaysMaxHp
{
get => false;
set { }
}
/// <summary>プリンセスシナジー専用: MP常時MAX</summary>
public virtual bool PrincessAlwaysMaxMp
{
get => false;
set { }
}
/// <summary>ウディタ プロキシDLL適用フラグ</summary>
public virtual bool WolfProxyDll
{
get => false;
set { }
}
/// <summary>SRPG Studio プロキシDLL適用フラグ</summary>
public virtual bool SrpgProxyDll
{
get => false;
set { }
}
/// <summary>
/// スクリプト改造(プラグイン注入など)が適用可能な状態かどうか。
/// 該当ゲームが改造非対応(ウディタ・SRPG・NW.js・その他・未解凍状態など)の場合は false を返し、
/// 右側パネルのスクリプト改造項目を非表示にします。
/// </summary>
public virtual bool CanApplyScriptMod => false;
} }
} }
+26 -2
View File
@@ -1,6 +1,8 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Unity;
namespace GameLauncher.Models namespace GameLauncher.Models
{ {
@@ -23,10 +25,22 @@ namespace GameLauncher.Models
/// <summary>追加のスキャン対象ルートディレクトリ一覧</summary> /// <summary>追加のスキャン対象ルートディレクトリ一覧</summary>
public List<string> TargetDirectories { get; set; } = []; public List<string> TargetDirectories { get; set; } = [];
/// <summary>RGSS Extractor の実行ファイルパス(ツクールVX/VX Ace暗号化アーカイブ展開用)</summary>
public string RgssExtractorPath { get; set; } = @"C:\Soft\RGSS-Extractor-v1.0\RGSS Extractor.exe";
/// <summary>Wolf RPG アーカイブ解凍ツールの実行ファイルパス(UberWolfCli.exe / WolfDec.exe など)</summary>
public string WolfExtractorPath { get; set; } = string.Empty;
/// <summary>ウィンドウ拡大用の外部ツール実行ファイルパス(Sizer等。空の場合はランチャー内蔵のWin32 API方式を使用)</summary>
public string WindowResizeToolPath { get; set; } = string.Empty;
// フィルター状態の保存(再起動時復元用) // フィルター状態の保存(再起動時復元用)
public string TkoolEngineFilter { get; set; } = "All"; public string TkoolEngineFilter { get; set; } = "All";
public bool TkoolFilterModdedOnly { get; set; } public bool TkoolFilterModdedOnly { get; set; }
public bool TkoolFilterAsarOnly { get; set; } public bool TkoolFilterAsarOnly { get; set; }
public bool TkoolFilterRgssOnly { get; set; }
public bool TkoolFilterAllRgss { get; set; }
public bool FilterBookmarkedOnly { get; set; }
public string UnityBackendFilter { get; set; } = "All"; public string UnityBackendFilter { get; set; } = "All";
public bool UnityFilterSaveOnly { get; set; } public bool UnityFilterSaveOnly { get; set; }
} }
@@ -43,8 +57,9 @@ namespace GameLauncher.Models
if (x is not GameItemBase a || y is not GameItemBase b) if (x is not GameItemBase a || y is not GameItemBase b)
return 0; return 0;
return SortOrder switch return this.SortOrder switch
{ {
GameSortOrder.BookmarkedFirst => CompareBookmarkedFirst(a, b),
GameSortOrder.LastLaunchedDesc => CompareNullableDateTimeDesc(a.LastLaunched, b.LastLaunched, a.Title, b.Title), GameSortOrder.LastLaunchedDesc => CompareNullableDateTimeDesc(a.LastLaunched, b.LastLaunched, a.Title, b.Title),
GameSortOrder.LastLaunchedAsc => CompareNullableDateTimeAsc(a.LastLaunched, b.LastLaunched, a.Title, b.Title), GameSortOrder.LastLaunchedAsc => CompareNullableDateTimeAsc(a.LastLaunched, b.LastLaunched, a.Title, b.Title),
GameSortOrder.FolderLastModifiedDesc => CompareNullableDateTimeDesc(a.FolderLastModified, b.FolderLastModified, a.Title, b.Title), GameSortOrder.FolderLastModifiedDesc => CompareNullableDateTimeDesc(a.FolderLastModified, b.FolderLastModified, a.Title, b.Title),
@@ -56,6 +71,15 @@ namespace GameLauncher.Models
}; };
} }
private static int CompareBookmarkedFirst(GameItemBase a, GameItemBase b)
{
if (a.IsBookmarked != b.IsBookmarked)
{
return a.IsBookmarked ? -1 : 1;
}
return CompareNullableDateTimeDesc(a.LastLaunched, b.LastLaunched, a.Title, b.Title);
}
private static int CompareNullableDateTimeDesc(DateTime? d1, DateTime? d2, string title1, string title2) private static int CompareNullableDateTimeDesc(DateTime? d1, DateTime? d2, string title1, string title2)
{ {
if (d1.HasValue && d2.HasValue) if (d1.HasValue && d2.HasValue)
+39 -9
View File
@@ -1,4 +1,4 @@
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.IO; using System.IO;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
@@ -17,6 +17,18 @@ namespace GameLauncher.Models
public string FileName { get; set; } = string.Empty; // ファイル名 (例: "BattleSpeedUp.js") public string FileName { get; set; } = string.Empty; // ファイル名 (例: "BattleSpeedUp.js")
public string FilePath { get; set; } = string.Empty; // フルパス public string FilePath { get; set; } = string.Empty; // フルパス
/// <summary>特定ゲーム専用プラグインかどうか</summary>
public bool IsGameSpecific { get; set; }
/// <summary>対象ゲーム識別子 (例: "PrincessSynergy")</summary>
public string TargetGameKey { get; set; } = string.Empty;
/// <summary>表示用グループ名</summary>
public string GroupName { get; set; } = "共通機能";
/// <summary>初期チェックの既定値 (未設定時の初期値)</summary>
public bool DefaultEnabled { get; set; } = true;
/// <summary> /// <summary>
/// .js ファイルから定義情報を解析・生成します。 /// .js ファイルから定義情報を解析・生成します。
/// </summary> /// </summary>
@@ -38,6 +50,16 @@ namespace GameLauncher.Models
catch { } catch { }
string displayName = GetFriendlyName(id, desc); string displayName = GetFriendlyName(id, desc);
bool isSpecific = id is "AlwaysMaxHp" or "AlwaysMaxMp";
string targetKey = isSpecific ? "PrincessSynergy" : string.Empty;
string groupName = isSpecific ? "固有ゲーム専用プラグイン" : "共通プラグイン";
bool defEnabled = id switch
{
"ShopMaxBuy" => false,
"AlwaysMaxHp" => false,
"AlwaysMaxMp" => false,
_ => true
};
return new ModPluginDefinition return new ModPluginDefinition
{ {
@@ -45,7 +67,11 @@ namespace GameLauncher.Models
Name = displayName, Name = displayName,
Description = desc, Description = desc,
FileName = fileName, FileName = fileName,
FilePath = filePath FilePath = filePath,
IsGameSpecific = isSpecific,
TargetGameKey = targetKey,
GroupName = groupName,
DefaultEnabled = defEnabled
}; };
} }
@@ -65,6 +91,8 @@ namespace GameLauncher.Models
"GoldGainMax" => "所持金増減時MAX (9999999G)", "GoldGainMax" => "所持金増減時MAX (9999999G)",
"ExpGainMax" => "経験値獲得時MAX (一気にLv99)", "ExpGainMax" => "経験値獲得時MAX (一気にLv99)",
"MessageInstant" => "メッセージ瞬間表示 (ウェイトスキップ)", "MessageInstant" => "メッセージ瞬間表示 (ウェイトスキップ)",
"AlwaysMaxHp" => "HP常時MAX (プリンセスシナジー専用)",
"AlwaysMaxMp" => "MP常時MAX (プリンセスシナジー専用)",
_ => !string.IsNullOrEmpty(desc) ? $"{id} ({desc})" : id _ => !string.IsNullOrEmpty(desc) ? $"{id} ({desc})" : id
}; };
} }
@@ -78,19 +106,21 @@ namespace GameLauncher.Models
private bool _isEnabled = true; private bool _isEnabled = true;
public ModPluginDefinition Definition { get; set; } = null!; public ModPluginDefinition Definition { get; set; } = null!;
public string Id => Definition.Id; public string Id => this.Definition.Id;
public string Name => Definition.Name; public string Name => this.Definition.Name;
public string Description => Definition.Description; public string Description => this.Definition.Description;
public string GroupName => this.Definition.GroupName;
public bool IsGameSpecific => this.Definition.IsGameSpecific;
public bool IsEnabled public bool IsEnabled
{ {
get => _isEnabled; get => this._isEnabled;
set set
{ {
if (_isEnabled != value) if (this._isEnabled != value)
{ {
_isEnabled = value; this._isEnabled = value;
OnPropertyChanged(); this.OnPropertyChanged();
} }
} }
} }
+17 -17
View File
@@ -1,4 +1,4 @@
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
@@ -26,36 +26,36 @@ namespace GameLauncher.Models
/// <summary>項目名(キー名、変数名)</summary> /// <summary>項目名(キー名、変数名)</summary>
public string Key public string Key
{ {
get => _key; get => this._key;
set { if (_key != value) { _key = value; OnPropertyChanged(); } } set { if (this._key != value) { this._key = value; this.OnPropertyChanged(); } }
} }
/// <summary>分類・カテゴリ(セクション、オブジェクト名など)</summary> /// <summary>分類・カテゴリ(セクション、オブジェクト名など)</summary>
public string Category public string Category
{ {
get => _category; get => this._category;
set { if (_category != value) { _category = value; OnPropertyChanged(); } } set { if (this._category != value) { this._category = value; this.OnPropertyChanged(); } }
} }
/// <summary>データ型(Int, Float, Bool, String など)</summary> /// <summary>データ型(Int, Float, Bool, String など)</summary>
public string Type public string Type
{ {
get => _type; get => this._type;
set { if (_type != value) { _type = value; OnPropertyChanged(); } } set { if (this._type != value) { this._type = value; this.OnPropertyChanged(); } }
} }
/// <summary>GUI編集用の値文字列</summary> /// <summary>GUI編集用の値文字列</summary>
public string EditValue public string EditValue
{ {
get => _editValue; get => this._editValue;
set set
{ {
if (_editValue != value) if (this._editValue != value)
{ {
_editValue = value; this._editValue = value;
_isModified = true; this._isModified = true;
OnPropertyChanged(); this.OnPropertyChanged();
OnPropertyChanged(nameof(IsModified)); this.OnPropertyChanged(nameof(this.IsModified));
} }
} }
} }
@@ -63,15 +63,15 @@ namespace GameLauncher.Models
/// <summary>値がユーザーによって変更されたかどうか</summary> /// <summary>値がユーザーによって変更されたかどうか</summary>
public bool IsModified public bool IsModified
{ {
get => _isModified; get => this._isModified;
set { if (_isModified != value) { _isModified = value; OnPropertyChanged(); } } set { if (this._isModified != value) { this._isModified = value; this.OnPropertyChanged(); } }
} }
/// <summary>備考・説明・オフセット位置など</summary> /// <summary>備考・説明・オフセット位置など</summary>
public string Description public string Description
{ {
get => _description; get => this._description;
set { if (_description != value) { _description = value; OnPropertyChanged(); } } set { if (this._description != value) { this._description = value; this.OnPropertyChanged(); } }
} }
/// <summary>内部保持用の生データや元データ(再エンコード用)</summary> /// <summary>内部保持用の生データや元データ(再エンコード用)</summary>
-348
View File
@@ -1,348 +0,0 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Media;
namespace GameLauncher.Models
{
/// <summary>
/// 各プラグイン改造の個別有効/無効オプション(互換用)
/// </summary>
public class ModPluginOptions : System.ComponentModel.INotifyPropertyChanged
{
private bool _speedUp = true;
private bool _antigravityGameTweaks = true;
private bool _dropItem99 = true;
private bool _turnStartFullRecover = true;
private bool _turnStartFullRecoverHp = true;
private bool _turnStartFullRecoverMp = true;
private bool _turnStartFullRecoverTp = true;
private bool _maxGainGold = true;
private bool _maxGainExp = true;
private bool _instantMessage = true;
public bool SpeedUp
{
get => _speedUp;
set { if (_speedUp != value) { _speedUp = value; OnPropertyChanged(); } }
}
public bool AntigravityGameTweaks
{
get => _antigravityGameTweaks;
set { if (_antigravityGameTweaks != value) { _antigravityGameTweaks = value; OnPropertyChanged(); } }
}
public bool DropItem99
{
get => _dropItem99;
set { if (_dropItem99 != value) { _dropItem99 = value; OnPropertyChanged(); } }
}
public bool TurnStartFullRecover
{
get => _turnStartFullRecover;
set { if (_turnStartFullRecover != value) { _turnStartFullRecover = value; OnPropertyChanged(); } }
}
public bool TurnStartFullRecoverHp
{
get => _turnStartFullRecoverHp;
set { if (_turnStartFullRecoverHp != value) { _turnStartFullRecoverHp = value; OnPropertyChanged(); } }
}
public bool TurnStartFullRecoverMp
{
get => _turnStartFullRecoverMp;
set { if (_turnStartFullRecoverMp != value) { _turnStartFullRecoverMp = value; OnPropertyChanged(); } }
}
public bool TurnStartFullRecoverTp
{
get => _turnStartFullRecoverTp;
set { if (_turnStartFullRecoverTp != value) { _turnStartFullRecoverTp = value; OnPropertyChanged(); } }
}
public bool MaxGainGold
{
get => _maxGainGold;
set { if (_maxGainGold != value) { _maxGainGold = value; OnPropertyChanged(); } }
}
public bool MaxGainExp
{
get => _maxGainExp;
set { if (_maxGainExp != value) { _maxGainExp = value; OnPropertyChanged(); } }
}
public bool InstantMessage
{
get => _instantMessage;
set { if (_instantMessage != value) { _instantMessage = value; OnPropertyChanged(); } }
}
public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string? name = null)
{
PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(name));
}
}
/// <summary>
/// ツクールおよびティラノスクリプトゲームのデータモデル
/// </summary>
public class TkoolGameItem : GameItemBase
{
private string _pluginsJsPath = string.Empty;
private string _pluginsDirPath = string.Empty;
private TkoolEngineType _engineType = TkoolEngineType.Unknown;
private bool _isModded;
private bool _applyMod = true;
private bool _hasCustomApplyMod;
private bool _isInitializingApplyMod;
private ModPluginOptions _modOptions = new();
// app.asar 関連プロパティ
private bool _isAsar;
private bool _isAsarExtracted;
private string? _asarPath;
private string? _asarExtractedDirPath;
private string? _relativePluginsJsInAsar;
public override GameEngineKind EngineKind => EngineType == TkoolEngineType.Tyrano
? GameEngineKind.Tyrano
: GameEngineKind.Tkool;
public string PluginsJsPath
{
get => _pluginsJsPath;
set { if (_pluginsJsPath != value) { _pluginsJsPath = value; OnPropertyChanged(); } }
}
public string PluginsDirPath
{
get => _pluginsDirPath;
set { if (_pluginsDirPath != value) { _pluginsDirPath = value; OnPropertyChanged(); } }
}
public override bool IsMV => EngineType == TkoolEngineType.MV;
public override bool IsMZ => EngineType == TkoolEngineType.MZ;
public override bool IsTyrano => EngineType == TkoolEngineType.Tyrano;
public TkoolEngineType EngineType
{
get => _engineType;
set
{
if (_engineType != value)
{
_engineType = value;
OnPropertyChanged();
OnPropertyChanged(nameof(EngineKind));
OnPropertyChanged(nameof(EngineDisplayName));
OnPropertyChanged(nameof(IsMV));
OnPropertyChanged(nameof(IsMZ));
OnPropertyChanged(nameof(IsTyrano));
}
}
}
public override bool IsModded
{
get => _isModded;
set { if (_isModded != value) { _isModded = value; OnPropertyChanged(); } }
}
public bool HasCustomApplyMod
{
get => _hasCustomApplyMod;
set { if (_hasCustomApplyMod != value) { _hasCustomApplyMod = value; OnPropertyChanged(); } }
}
public override bool ApplyMod
{
get => _applyMod;
set
{
if (_applyMod != value)
{
_applyMod = value;
if (!_isInitializingApplyMod)
{
HasCustomApplyMod = true;
}
OnPropertyChanged();
}
}
}
public void SetDefaultApplyMod(bool defaultVal)
{
if (!_hasCustomApplyMod)
{
_isInitializingApplyMod = true;
_applyMod = defaultVal;
_isInitializingApplyMod = false;
OnPropertyChanged(nameof(ApplyMod));
}
}
public override bool IsAsar
{
get => _isAsar;
set
{
if (_isAsar != value)
{
_isAsar = value;
OnPropertyChanged();
OnPropertyChanged(nameof(AsarBadgeVisibility));
OnPropertyChanged(nameof(AsarBadgeText));
OnPropertyChanged(nameof(AsarBadgeBackground));
OnPropertyChanged(nameof(AsarDetailStatusText));
}
}
}
public override bool IsAsarExtracted
{
get => _isAsarExtracted;
set
{
if (_isAsarExtracted != value)
{
_isAsarExtracted = value;
OnPropertyChanged();
OnPropertyChanged(nameof(AsarBadgeText));
OnPropertyChanged(nameof(AsarBadgeBackground));
OnPropertyChanged(nameof(AsarDetailStatusText));
}
}
}
public string? AsarPath
{
get => _asarPath;
set { if (_asarPath != value) { _asarPath = value; OnPropertyChanged(); } }
}
public string? AsarExtractedDirPath
{
get => _asarExtractedDirPath;
set { if (_asarExtractedDirPath != value) { _asarExtractedDirPath = value; OnPropertyChanged(); } }
}
public string? RelativePluginsJsInAsar
{
get => _relativePluginsJsInAsar;
set { if (_relativePluginsJsInAsar != value) { _relativePluginsJsInAsar = value; OnPropertyChanged(); } }
}
public override Visibility AsarBadgeVisibility => IsAsar ? Visibility.Visible : Visibility.Collapsed;
public override string AsarBadgeText => !IsAsar ? string.Empty : (IsAsarExtracted ? "ASAR (解凍済)" : "ASAR (圧縮)");
public override Brush AsarBadgeBackground => IsAsarExtracted
? new SolidColorBrush(Color.FromRgb(0x00, 0x89, 0x7B))
: new SolidColorBrush(Color.FromRgb(0x5E, 0x35, 0xB1));
public override string AsarDetailStatusText => !IsAsar
? string.Empty
: (IsAsarExtracted ? "📦 app.asar 形式(解凍済み・改造可能)" : "📦 app.asar 形式(圧縮中・起動時またはボタンで解凍可能)");
private Dictionary<string, bool> _pluginSettings = new(StringComparer.OrdinalIgnoreCase);
private ObservableCollection<ModPluginOptionItem> _pluginOptions = [];
public Dictionary<string, bool> PluginSettings
{
get => _pluginSettings;
set { if (_pluginSettings != value) { _pluginSettings = value; OnPropertyChanged(); } }
}
public override ObservableCollection<ModPluginOptionItem> PluginOptions
{
get => _pluginOptions;
set { if (_pluginOptions != value) { _pluginOptions = value; OnPropertyChanged(); } }
}
public bool IsPluginEnabled(string pluginId, Dictionary<string, bool>? defaultSettings = null, bool fallbackVal = true)
{
if (_pluginSettings.TryGetValue(pluginId, out var val))
{
return val;
}
if (pluginId is "BattleTurnRecoverHp" or "BattleTurnRecoverMp" or "BattleTurnRecoverTp")
{
if (_pluginSettings.TryGetValue("BattleTurnRecover", out var legacyVal))
{
return legacyVal;
}
}
if (defaultSettings != null && defaultSettings.TryGetValue(pluginId, out var defVal))
{
return defVal;
}
if (pluginId is "BattleTurnRecoverHp" or "BattleTurnRecoverMp" or "BattleTurnRecoverTp")
{
if (defaultSettings != null && defaultSettings.TryGetValue("BattleTurnRecover", out var legacyDefVal))
{
return legacyDefVal;
}
}
return fallbackVal;
}
public static readonly ModPluginDefinition[] DefaultTyranoPlugins =
[
new() { Id = "TyranoUnlockAllCg", Name = "🔓 全CG・全回想の全開放", Description = "システム変数(sf)のCG・回想フラグを全開放し、最初からCG・シーン鑑賞を可能にします。" },
new() { Id = "TyranoFastMessage", Name = "⚡ メッセージ超高速化・演出ウェイト短縮", Description = "文字送り速度を最大化し、[wait]演出の停止時間を短縮して快適にスキップ可能にします。" },
new() { Id = "TyranoDevTools", Name = "🛠 開発者ツール (F12) の有効化", Description = "F12キーでブラウザ・アプリの開発者ツールコンソールを開けるようにします。" },
new() { Id = "TyranoCheatMenu", Name = "🎛 画面上変数(f)チートエディタ表示", Description = "画面右上にボタンを配置し、ゲーム内変数・フラグの閲覧と直接書き換えができるメニューを表示します。" }
];
public void SyncPluginOptions(IEnumerable<ModPluginDefinition> availablePlugins, Dictionary<string, bool>? defaultSettings = null)
{
_pluginOptions.Clear();
var targetDefs = EngineType == TkoolEngineType.Tyrano ? DefaultTyranoPlugins : availablePlugins;
foreach (var def in targetDefs)
{
bool isEnabled = IsPluginEnabled(def.Id, defaultSettings, fallbackVal: true);
var item = new ModPluginOptionItem
{
Definition = def,
IsEnabled = isEnabled
};
item.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(ModPluginOptionItem.IsEnabled))
{
_pluginSettings[def.Id] = item.IsEnabled;
}
};
_pluginOptions.Add(item);
}
}
public ModPluginOptions ModOptions
{
get => _modOptions;
set { if (_modOptions != value) { _modOptions = value; OnPropertyChanged(); } }
}
public string EngineDisplayName => EngineType switch
{
TkoolEngineType.MV => "RPGツクールMV",
TkoolEngineType.MZ => "RPGツクールMZ",
TkoolEngineType.Tyrano => "ティラノスクリプト",
_ => "ツクール/ティラノ"
};
}
}
+118 -2
View File
@@ -1,8 +1,88 @@
# GameLauncher (ツクールMV・MZ・ティラノ & Unity 統合ゲームランチャー) # GameLauncher (ツクールMV・MZ・ティラノ & Unity 統合ゲームランチャー)
RPGツクール(MV・MZ)、ティラノスクリプト、およびUnity製ゲームを1つの洗練された画面で一元管理・高速起動できる統合ランチャーです。 RPGツクール(MV・MZ)、ティラノスクリプト、およびUnity製ゲームを1つの洗練された画面で一元管理・高速起動できる統合ランチャーです。
従来の **TkoolLauncher** と **UnityLauncher** の全機能(スクリプト改造、ASAR解凍・復元、PlayerPrefsレジストリ編集、セーブファイル編集、バックアップ)が欠けることなく完全に統合されています。 従来の **TkoolLauncher** と **UnityLauncher** の全機能(スクリプト改造、ASAR解凍・復元、PlayerPrefsレジストリ編集、セーブファイル編集、バックアップ)が欠けることなく完全に統合されています。
> 📌 **AI エージェント / 開発者向け規則**: 本プロジェクトでの変更は必ず [`AGENTS.md`](AGENTS.md) に従ってください(エンジン別構成・ゲーム個別対応の隔離・外部ツールのエンジン別配置など)。
---
## 📁 フォルダ構成(エンジン別アーキテクチャ)
エンジンごとに処理を統一し、ゲーム専用の改造が他ゲームへ影響しないよう、エンジン別フォルダで完全に分離しています。
```
GameLauncher/
├── Engines/ … エンジン別の処理(エンジンごとに独立)
│ ├── Common/ … 全エンジン共通の基盤
│ │ ├── IEngineModule.cs … エンジン共通インターフェース
│ │ └── EngineDetectionHelper.cs … エンジン判定・誤検出補正
│ ├── Rgss/ … RPGツクールVX/VX Ace (RGSS) / SRPG Studio
│ │ ├── RgssModService.cs … スクリプト改造 (Scripts.rvdata2)
│ │ ├── SrpgModService.cs … SRPG Studio 改造
│ │ ├── SrpgArchiveService.cs … data.dts 解凍・再構築
│ │ ├── Games/ … ゲーム個別対応
│ │ │ └── IiniTitleRepair/ … Game.ini タイトル文字化け修復
│ │ └── Tools/ … エンジン専用ツール
│ │ └── SRPG_Unpacker.exe
│ ├── Tkool/ … RPGツクールMV/MZ (NW.js)
│ │ ├── TkoolModService.cs
│ │ ├── TkoolInjectionService.cs
│ │ ├── TkoolGameItem.cs
│ │ ├── Games/ … ゲーム個別対応
│ │ └── Tools/ … エンジン専用ツール
│ ├── Tyrano/ … ティラノスクリプト
│ │ ├── TyranoModService.cs
│ │ ├── Games/
│ │ └── Tools/
│ ├── Wolf/ … WOLF RPGエディター(ウディタ)
│ │ ├── WolfModService.cs
│ │ ├── WolfArchiveService.cs
│ │ ├── WolfSaveService.cs
│ │ ├── Games/
│ │ └── Tools/
│ │ └── UberWolfCli.exe
│ ├── Unity/ … Unity (IL2CPP / Mono)
│ │ ├── UnitySaveManagerService.cs
│ │ ├── UnityGameItem.cs / UnitySaveItem.cs / UnityEnums.cs
│ │ ├── Games/
│ │ └── Tools/
│ ├── Nwjs/ … 汎用 NW.js パッケージ / ASAR
│ │ ├── AsarArchiveService.cs
│ │ ├── Games/
│ │ └── Tools/
│ └── Evb/ … Enigma Virtual Box (EVB) パック済みゲーム
│ ├── EvbDetectionHelper.cs … PE セクション署名による EVB 検出
│ ├── EvbDetector.cs … 互換ファサード
│ ├── EvbUnpackService.cs … 解凍・復元・本来エンジン再判定
│ ├── EvbUnpackerToolProvider.cs … evbunpack 解決・引数生成
│ ├── EvbEngineModule.cs … IEngineModule 実装
│ ├── Games/ … ゲーム個別対応
│ └── Tools/
│ └── evbunpack/ … evbunpack.exe(同梱)+ README/LICENSE
├── Services/ … エンジン非依存の共通サービス
│ ├── GameScannerService.cs … ゲーム検出・キャッシュ
│ ├── SaveDataCodecManager.cs … セーブコーデック統括
│ ├── WindowResizeService.cs
│ └── Codecs/ … EasySave3 / YU-RIS コーデック
├── Models/ … エンジン非依存の共通モデル
│ ├── GameItemBase.cs
│ ├── LauncherConfig.cs
│ └── ModPluginDefinition.cs
├── Helpers/ … パス解決・コンバータ
│ ├── AppPathHelper.cs … 実行時パス・エンジン別ツール解決
│ └── Converters.cs
├── plugins/ … 改造スクリプト(JS)
├── Backups/ … セーブ・アーカイブのバックアップ
└── (UI)MainWindow / ConfigDialog / SaveEditorWindow など … WPF画面
```
### 設計原則
- **エンジンごとに処理を統一**: 各エンジンは `Engines/<Engine>/` 配下にサービス・モデルをまとめる。
- **ゲーム個別対応はエンジン配下に隔離**: 特定ゲーム専用の改造は `Engines/<Engine>/Games/<GameName>/` に配置し、共通処理から **明示的に呼び出す**。他ゲームへ影響しないことを保証する。
- **外部ツールもエンジン別**: 外部ツール・外部ファイルは `Engines/<Engine>/Tools/` に配置し、`AppPathHelper.ResolveEngineTool(engine, fileName)` で解決する。エンジン間でツールを共有しない。
--- ---
## 🌟 主な機能一覧 ## 🌟 主な機能一覧
@@ -50,6 +130,40 @@ RPGツクール(MV・MZ)、ティラノスクリプト、およびUnity製
- regedit で PlayerPrefs を直接開く - regedit で PlayerPrefs を直接開く
- セーブデータ(レジストリ & ファイル)の即時一括バックアップ(`Backups/` ディレクトリ) - セーブデータ(レジストリ & ファイル)の即時一括バックアップ(`Backups/` ディレクトリ)
### 5. Enigma Virtual Box (EVB) パック済みゲームの解凍(Evb エンジン)
Enigma Virtual Box は汎用パッカーで、RGSS / NW.js / Wolf / Unity など **どのエンジンのゲームでも** 1つの exe に包めます。
`Evb` エンジンはこのパッケージ層を他エンジンの**前段**で検出し、同梱の `evbunpack` で解凍してから本来のエンジンを再判定します。
- **自動検出**: PE セクション署名(`.enigma1` / `.enigma2`)および埋め込みマーカー(`Enigma Virtual Box`)で判定。通常の(非パック)ゲームは誤検出しません。
- **バッジ表示**: EVB パック済みゲームには `EVB` バッジを表示。未解凍のときは「要解凍」バッジも併せて表示します。
- **一目で分かるガイド**: EVB ゲームを選択すると、詳細パネルに「このゲームは EVB でパックされています」という手順ガイド(①解凍 → ②本来エンジン自動判定 → ③復元可能)が表示されます。
- **解凍(📦 EVBを解凍)**:
- 同梱の `Engines/Evb/Tools/evbunpack/evbunpack.exe` を実行し、ゲームフォルダ内 `_evb_extracted` へ出力します。
- 解凍後、`EngineDetectionHelper` により本来のエンジン(Rgss / Tkool / Nwjs / Wolf / Unity など)を再判定します。
- 元の exe は `*.glbak` としてバックアップされ、いつでも復元できます。
- **復元(↩ 解凍を元に戻す)**: `_evb_extracted` を削除して元の状態へ戻します(元 exe のバックアップは保持)。
- 解凍ツール(`evbunpack.exe`)はリポジトリ同梱です(自動ダウンロードは行いません)。詳細・出典・ライセンス・PE バリアント(`-pe 10_70 / 9_70 / 7_80`)は [`Engines/Evb/Tools/evbunpack/README.md`](Engines/Evb/Tools/evbunpack/README.md) を参照してください。
> **evbunpack の出典 & ライセンス**: [mos9527/evbunpack](https://github.com/mos9527/evbunpack)(Enigma Virtual Box Unpacker、Apache-2.0、2026-02-06 にアーカイブ化)。同梱フォルダには `LICENSE` を同梱しています。
---
## 🧩 新しいエンジンを追加する手順
1. `Engines/<NewEngine>/` フォルダを作成する。
2. `IEngineModule`(`Engines/Common/IEngineModule.cs`)を実装したサービスを作成する。
3. `EngineDetectionHelper` に判定ロジック・エイリアスを追加し、必要なら `DetectFromDirectory` にディレクトリ特徴を追記する。
4. エンジン専用の外部ツールがある場合は `Engines/<NewEngine>/Tools/` に配置し、`AppPathHelper.ResolveEngineTool("<NewEngine>", "<tool>")` で解決する。
5. エンジン専用モデルは同フォルダに配置し、名前空間を `GameLauncher.Engines.<NewEngine>` とする。
## 🎮 ゲーム個別対応を追加する手順
1. `Engines/<Engine>/Games/<GameName>/` フォルダを作成する。
2. 名前空間を `GameLauncher.Engines.<Engine>.Games.<GameName>` とした専用クラスを作成する。
3. 共通処理から **明示的に呼び出す**(他ゲームには一切影響させない)。
4. 可能な限りバックアップからの復元手段を用意し、後で元に戻せるようにする。
--- ---
## 💻 動作環境 & 技術スタック ## 💻 動作環境 & 技術スタック
@@ -68,9 +182,11 @@ RPGツクール(MV・MZ)、ティラノスクリプト、およびUnity製
- **プロファイル格納先**: `Z:\自作ソフト\GameLauncher\Profiles\` - **プロファイル格納先**: `Z:\自作ソフト\GameLauncher\Profiles\`
- **セーブバックアップ先**: `Z:\自作ソフト\GameLauncher\Backups\` - **セーブバックアップ先**: `Z:\自作ソフト\GameLauncher\Backups\`
- **プラグイン格納先**: `Z:\自作ソフト\GameLauncher\plugins\` - **プラグイン格納先**: `Z:\自作ソフト\GameLauncher\plugins\`
- **エンジン別ツール**: `Z:\自作ソフト\GameLauncher\Engines\<Engine>\Tools\`
### 発行方法 ### 発行方法
`publish.bat` または `publish.ps1` を実行することで、自動的に単一ファイルとして `Z:\自作ソフト\GameLauncher\` に出力されます。 `publish.ps1` を実行することで、自動的に単一ファイルとして `Z:\自作ソフト\GameLauncher\` に出力されます。
(`publish.ps1` は `Engines/<Engine>/Tools/` 配下の外部ツールも併せて配置します)
```powershell ```powershell
dotnet publish "c:\VS2026\GameLauncher\GameLauncher.csproj" -c Release -r win-x64 --self-contained false -o "Z:\自作ソフト\GameLauncher" dotnet publish "c:\VS2026\GameLauncher\GameLauncher.csproj" -c Release -r win-x64 --self-contained false -o "Z:\自作ソフト\GameLauncher"
``` ```
+3 -2
View File
@@ -1,4 +1,4 @@
<Window x:Class="GameLauncher.SaveEditorWindow" <Window x:Class="GameLauncher.SaveEditorWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
@@ -6,6 +6,7 @@
xmlns:local="clr-namespace:GameLauncher" xmlns:local="clr-namespace:GameLauncher"
xmlns:helpers="clr-namespace:GameLauncher.Helpers" xmlns:helpers="clr-namespace:GameLauncher.Helpers"
xmlns:models="clr-namespace:GameLauncher.Models" xmlns:models="clr-namespace:GameLauncher.Models"
xmlns:unity="clr-namespace:GameLauncher.Engines.Unity"
mc:Ignorable="d" mc:Ignorable="d"
Title="Unity セーブエディタ" Height="720" Width="1080" Title="Unity セーブエディタ" Height="720" Width="1080"
MinHeight="550" MinWidth="850" MinHeight="550" MinWidth="850"
@@ -331,7 +332,7 @@
<ListBox x:Name="lstSaveFiles" Grid.Row="1" Background="#1C1C26" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="1" <ListBox x:Name="lstSaveFiles" Grid.Row="1" Background="#1C1C26" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="1"
SelectionChanged="lstSaveFiles_SelectionChanged"> SelectionChanged="lstSaveFiles_SelectionChanged">
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type models:SaveFileEntry}"> <DataTemplate DataType="{x:Type unity:SaveFileEntry}">
<Border Padding="8,6" CornerRadius="4" BorderBrush="#2D2D3E" BorderThickness="0,0,0,1"> <Border Padding="8,6" CornerRadius="4" BorderBrush="#2D2D3E" BorderThickness="0,0,0,1">
<Grid> <Grid>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
+167 -162
View File
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Diagnostics; using System.Diagnostics;
@@ -15,6 +15,11 @@ using GameLauncher.Helpers;
using GameLauncher.Models; using GameLauncher.Models;
using GameLauncher.Services; using GameLauncher.Services;
using GameLauncher.Services.Codecs; using GameLauncher.Services.Codecs;
using GameLauncher.Engines.Unity;
using GameLauncher.Engines.Nwjs;
using GameLauncher.Engines.Wolf;
using GameLauncher.Engines.Rgss;
using GameLauncher.Engines.Tkool;
namespace GameLauncher namespace GameLauncher
{ {
@@ -28,7 +33,7 @@ namespace GameLauncher
// PlayerPrefs データ // PlayerPrefs データ
private readonly ObservableCollection<PlayerPrefsEntry> _allPrefs = []; private readonly ObservableCollection<PlayerPrefsEntry> _allPrefs = [];
private ListCollectionView _prefsView = null!; private readonly ListCollectionView _prefsView = null!;
// ファイル一覧データ // ファイル一覧データ
private readonly ObservableCollection<SaveFileEntry> _saveFiles = []; private readonly ObservableCollection<SaveFileEntry> _saveFiles = [];
@@ -36,7 +41,7 @@ namespace GameLauncher
// GUIセーブプロパティデータ // GUIセーブプロパティデータ
private readonly ObservableCollection<SaveDataPropertyEntry> _guiProperties = []; private readonly ObservableCollection<SaveDataPropertyEntry> _guiProperties = [];
private ListCollectionView _guiPropsView = null!; private readonly ListCollectionView _guiPropsView = null!;
private ISaveDataCodec? _currentCodec; private ISaveDataCodec? _currentCodec;
// バックアップ一覧データ // バックアップ一覧データ
@@ -44,36 +49,36 @@ namespace GameLauncher
public SaveEditorWindow(UnityGameItem game) public SaveEditorWindow(UnityGameItem game)
{ {
InitializeComponent(); this.InitializeComponent();
Game = game; this.Game = game;
lblGameTitle.Text = game.Title; this.lblGameTitle.Text = game.Title;
lblGameInfo.Text = $"{game.CompanyName} / {game.ProductName} ({game.BackendBadgeText})"; this.lblGameInfo.Text = $"{game.CompanyName} / {game.ProductName} ({game.BackendBadgeText})";
// PlayerPrefs ビュー // PlayerPrefs ビュー
_prefsView = (ListCollectionView)CollectionViewSource.GetDefaultView(_allPrefs); this._prefsView = (ListCollectionView)CollectionViewSource.GetDefaultView(this._allPrefs);
_prefsView.Filter = FilterPrefs; this._prefsView.Filter = this.FilterPrefs;
dgPlayerPrefs.ItemsSource = _prefsView; this.dgPlayerPrefs.ItemsSource = this._prefsView;
// ファイル一覧 // ファイル一覧
lstSaveFiles.ItemsSource = _saveFiles; this.lstSaveFiles.ItemsSource = this._saveFiles;
// GUI プロパティビュー // GUI プロパティビュー
_guiPropsView = (ListCollectionView)CollectionViewSource.GetDefaultView(_guiProperties); this._guiPropsView = (ListCollectionView)CollectionViewSource.GetDefaultView(this._guiProperties);
_guiPropsView.Filter = FilterGuiProperties; this._guiPropsView.Filter = this.FilterGuiProperties;
dgGuiProperties.ItemsSource = _guiPropsView; this.dgGuiProperties.ItemsSource = this._guiPropsView;
// バックアップ一覧 // バックアップ一覧
dgBackups.ItemsSource = _backups; this.dgBackups.ItemsSource = this._backups;
Loaded += SaveEditorWindow_Loaded; Loaded += this.SaveEditorWindow_Loaded;
} }
private void SaveEditorWindow_Loaded(object sender, RoutedEventArgs e) private void SaveEditorWindow_Loaded(object sender, RoutedEventArgs e)
{ {
ReloadPlayerPrefs(); this.ReloadPlayerPrefs();
ReloadSaveFiles(); this.ReloadSaveFiles();
ReloadBackups(); this.ReloadBackups();
} }
// ==================================================================== // ====================================================================
@@ -82,26 +87,26 @@ namespace GameLauncher
public void ReloadPlayerPrefs() public void ReloadPlayerPrefs()
{ {
_allPrefs.Clear(); this._allPrefs.Clear();
if (string.IsNullOrEmpty(Game.RegistryPath)) if (string.IsNullOrEmpty(this.Game.RegistryPath))
{ {
lblStatus.Text = "レジストリ情報が設定されていません (app.info が見つかりませんでした)"; this.lblStatus.Text = "レジストリ情報が設定されていません (app.info が見つかりませんでした)";
return; return;
} }
var entries = _saveService.GetPlayerPrefs(Game.RegistryPath); var entries = this._saveService.GetPlayerPrefs(this.Game.RegistryPath);
foreach (var entry in entries) foreach (var entry in entries)
{ {
_allPrefs.Add(entry); this._allPrefs.Add(entry);
} }
lblStatus.Text = $"PlayerPrefs: {entries.Count} 件のキーを読み込みました (HKCU\\{Game.RegistryPath})"; this.lblStatus.Text = $"PlayerPrefs: {entries.Count} 件のキーを読み込みました (HKCU\\{this.Game.RegistryPath})";
} }
private bool FilterPrefs(object obj) private bool FilterPrefs(object obj)
{ {
if (obj is not PlayerPrefsEntry entry) return false; if (obj is not PlayerPrefsEntry entry) return false;
var query = txtSearchPrefs.Text.Trim(); var query = this.txtSearchPrefs.Text.Trim();
if (string.IsNullOrEmpty(query)) return true; if (string.IsNullOrEmpty(query)) return true;
return entry.CleanKey.Contains(query, StringComparison.OrdinalIgnoreCase) || return entry.CleanKey.Contains(query, StringComparison.OrdinalIgnoreCase) ||
@@ -111,26 +116,26 @@ namespace GameLauncher
private void txtSearchPrefs_TextChanged(object sender, TextChangedEventArgs e) private void txtSearchPrefs_TextChanged(object sender, TextChangedEventArgs e)
{ {
_prefsView.Refresh(); this._prefsView.Refresh();
} }
private void dgPlayerPrefs_SelectionChanged(object sender, SelectionChangedEventArgs e) private void dgPlayerPrefs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ {
if (dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry) if (this.dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry)
{ {
lblSelectedKeyName.Text = entry.CleanKey; this.lblSelectedKeyName.Text = entry.CleanKey;
txtEditValueBar.Text = entry.EditValue; this.txtEditValueBar.Text = entry.EditValue;
txtEditValueBar.IsEnabled = true; this.txtEditValueBar.IsEnabled = true;
btnSaveCurrentPref.IsEnabled = true; this.btnSaveCurrentPref.IsEnabled = true;
btnDeleteCurrentPref.IsEnabled = true; this.btnDeleteCurrentPref.IsEnabled = true;
} }
else else
{ {
lblSelectedKeyName.Text = "(なし)"; this.lblSelectedKeyName.Text = "(なし)";
txtEditValueBar.Text = string.Empty; this.txtEditValueBar.Text = string.Empty;
txtEditValueBar.IsEnabled = false; this.txtEditValueBar.IsEnabled = false;
btnSaveCurrentPref.IsEnabled = false; this.btnSaveCurrentPref.IsEnabled = false;
btnDeleteCurrentPref.IsEnabled = false; this.btnDeleteCurrentPref.IsEnabled = false;
} }
} }
@@ -138,25 +143,25 @@ namespace GameLauncher
{ {
if (e.Key == Key.Enter) if (e.Key == Key.Enter)
{ {
SaveCurrentSelectedPref(); this.SaveCurrentSelectedPref();
} }
} }
private void btnSaveCurrentPref_Click(object sender, RoutedEventArgs e) private void btnSaveCurrentPref_Click(object sender, RoutedEventArgs e)
{ {
SaveCurrentSelectedPref(); this.SaveCurrentSelectedPref();
} }
private void SaveCurrentSelectedPref() private void SaveCurrentSelectedPref()
{ {
if (dgPlayerPrefs.SelectedItem is not PlayerPrefsEntry entry) return; if (this.dgPlayerPrefs.SelectedItem is not PlayerPrefsEntry entry) return;
entry.EditValue = txtEditValueBar.Text; entry.EditValue = this.txtEditValueBar.Text;
bool success = _saveService.SavePlayerPref(Game.RegistryPath, entry); bool success = this._saveService.SavePlayerPref(this.Game.RegistryPath, entry);
if (success) if (success)
{ {
lblStatus.Text = $"キー '{entry.CleanKey}' の値を正常に更新しました。"; this.lblStatus.Text = $"キー '{entry.CleanKey}' の値を正常に更新しました。";
dgPlayerPrefs.Items.Refresh(); this.dgPlayerPrefs.Items.Refresh();
} }
else else
{ {
@@ -167,16 +172,16 @@ namespace GameLauncher
private void btnDeleteCurrentPref_Click(object sender, RoutedEventArgs e) private void btnDeleteCurrentPref_Click(object sender, RoutedEventArgs e)
{ {
if (dgPlayerPrefs.SelectedItem is not PlayerPrefsEntry entry) return; if (this.dgPlayerPrefs.SelectedItem is not PlayerPrefsEntry entry) return;
var res = MessageBox.Show($"キー '{entry.CleanKey}' ({entry.RawKey}) をレジストリから削除しますか?", var res = MessageBox.Show($"キー '{entry.CleanKey}' ({entry.RawKey}) をレジストリから削除しますか?",
"キー削除の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning); "キー削除の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (res != MessageBoxResult.Yes) return; if (res != MessageBoxResult.Yes) return;
if (_saveService.DeletePlayerPref(Game.RegistryPath, entry.RawKey)) if (this._saveService.DeletePlayerPref(this.Game.RegistryPath, entry.RawKey))
{ {
_allPrefs.Remove(entry); this._allPrefs.Remove(entry);
lblStatus.Text = $"キー '{entry.CleanKey}' を削除しました。"; this.lblStatus.Text = $"キー '{entry.CleanKey}' を削除しました。";
} }
else else
{ {
@@ -189,10 +194,10 @@ namespace GameLauncher
var dlg = new AddKeyDialog { Owner = this }; var dlg = new AddKeyDialog { Owner = this };
if (dlg.ShowDialog() == true) if (dlg.ShowDialog() == true)
{ {
if (_saveService.AddPlayerPref(Game.RegistryPath, dlg.KeyName, dlg.KeyType, dlg.KeyValue, out string rawKey)) if (this._saveService.AddPlayerPref(this.Game.RegistryPath, dlg.KeyName, dlg.KeyType, dlg.KeyValue, out string rawKey))
{ {
ReloadPlayerPrefs(); this.ReloadPlayerPrefs();
lblStatus.Text = $"新規キー '{dlg.KeyName}' ({rawKey}) を追加しました。"; this.lblStatus.Text = $"新規キー '{dlg.KeyName}' ({rawKey}) を追加しました。";
} }
else else
{ {
@@ -203,12 +208,12 @@ namespace GameLauncher
private void btnBackupPrefs_Click(object sender, RoutedEventArgs e) private void btnBackupPrefs_Click(object sender, RoutedEventArgs e)
{ {
var backupDir = AppPathHelper.GetGameBackupDirectory(Game.FolderName, Game.RootDirectory); var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory);
var result = _saveService.BackupRegistry(Game.RegistryPath, backupDir); var result = this._saveService.BackupRegistry(this.Game.RegistryPath, backupDir);
if (result != null) if (result != null)
{ {
ReloadBackups(); this.ReloadBackups();
lblStatus.Text = $"レジストリをバックアップしました: {Path.GetFileName(result)}"; this.lblStatus.Text = $"レジストリをバックアップしました: {Path.GetFileName(result)}";
MessageBox.Show($"レジストリをバックアップしました:\n\n{result}", "バックアップ完了", MessageBoxButton.OK, MessageBoxImage.Information); MessageBox.Show($"レジストリをバックアップしました:\n\n{result}", "バックアップ完了", MessageBoxButton.OK, MessageBoxImage.Information);
} }
else else
@@ -219,7 +224,7 @@ namespace GameLauncher
private void btnRestorePrefs_Click(object sender, RoutedEventArgs e) private void btnRestorePrefs_Click(object sender, RoutedEventArgs e)
{ {
var backupDir = AppPathHelper.GetGameBackupDirectory(Game.FolderName, Game.RootDirectory); var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory);
var dlg = new OpenFileDialog var dlg = new OpenFileDialog
{ {
Title = "復元する .reg ファイルを選択", Title = "復元する .reg ファイルを選択",
@@ -233,10 +238,10 @@ namespace GameLauncher
"復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning); "復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (res != MessageBoxResult.Yes) return; if (res != MessageBoxResult.Yes) return;
if (_saveService.RestoreRegistry(dlg.FileName)) if (this._saveService.RestoreRegistry(dlg.FileName))
{ {
ReloadPlayerPrefs(); this.ReloadPlayerPrefs();
lblStatus.Text = "レジストリを正常に復元しました。"; this.lblStatus.Text = "レジストリを正常に復元しました。";
MessageBox.Show("レジストリを正常に復元しました。", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information); MessageBox.Show("レジストリを正常に復元しました。", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
} }
else else
@@ -248,17 +253,17 @@ namespace GameLauncher
private void btnReloadPrefs_Click(object sender, RoutedEventArgs e) private void btnReloadPrefs_Click(object sender, RoutedEventArgs e)
{ {
ReloadPlayerPrefs(); this.ReloadPlayerPrefs();
} }
private void ctxSavePref_Click(object sender, RoutedEventArgs e) private void ctxSavePref_Click(object sender, RoutedEventArgs e)
{ {
SaveCurrentSelectedPref(); this.SaveCurrentSelectedPref();
} }
private void ctxCopyKey_Click(object sender, RoutedEventArgs e) private void ctxCopyKey_Click(object sender, RoutedEventArgs e)
{ {
if (dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry) if (this.dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry)
{ {
Clipboard.SetText(entry.CleanKey); Clipboard.SetText(entry.CleanKey);
} }
@@ -266,7 +271,7 @@ namespace GameLauncher
private void ctxCopyValue_Click(object sender, RoutedEventArgs e) private void ctxCopyValue_Click(object sender, RoutedEventArgs e)
{ {
if (dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry) if (this.dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry)
{ {
Clipboard.SetText(entry.EditValue); Clipboard.SetText(entry.EditValue);
} }
@@ -274,7 +279,7 @@ namespace GameLauncher
private void ctxDeletePref_Click(object sender, RoutedEventArgs e) private void ctxDeletePref_Click(object sender, RoutedEventArgs e)
{ {
btnDeleteCurrentPref_Click(sender, e); this.btnDeleteCurrentPref_Click(sender, e);
} }
// ==================================================================== // ====================================================================
@@ -283,98 +288,98 @@ namespace GameLauncher
public void ReloadSaveFiles() public void ReloadSaveFiles()
{ {
_saveFiles.Clear(); this._saveFiles.Clear();
var files = _saveService.GetSaveFiles(Game); var files = this._saveService.GetSaveFiles(this.Game);
foreach (var f in files) foreach (var f in files)
{ {
_saveFiles.Add(f); this._saveFiles.Add(f);
} }
if (_saveFiles.Count > 0) if (this._saveFiles.Count > 0)
{ {
lstSaveFiles.SelectedIndex = 0; this.lstSaveFiles.SelectedIndex = 0;
} }
else else
{ {
lblCurrentFileName.Text = "セーブファイルは見つかりませんでした"; this.lblCurrentFileName.Text = "セーブファイルは見つかりませんでした";
lblCurrentFilePath.Text = string.Empty; this.lblCurrentFilePath.Text = string.Empty;
txtFileContent.Text = string.Empty; this.txtFileContent.Text = string.Empty;
HideAllEditorPanels(); this.HideAllEditorPanels();
} }
} }
private void HideAllEditorPanels() private void HideAllEditorPanels()
{ {
pnlGuiEditor.Visibility = Visibility.Collapsed; this.pnlGuiEditor.Visibility = Visibility.Collapsed;
pnlTextEditor.Visibility = Visibility.Collapsed; this.pnlTextEditor.Visibility = Visibility.Collapsed;
pnlUnsupportedBinary.Visibility = Visibility.Collapsed; this.pnlUnsupportedBinary.Visibility = Visibility.Collapsed;
btnFormatJson.Visibility = Visibility.Collapsed; this.btnFormatJson.Visibility = Visibility.Collapsed;
btnSaveFileContent.Visibility = Visibility.Collapsed; this.btnSaveFileContent.Visibility = Visibility.Collapsed;
btnSaveGuiProperties.Visibility = Visibility.Collapsed; this.btnSaveGuiProperties.Visibility = Visibility.Collapsed;
badgeCodec.Visibility = Visibility.Collapsed; this.badgeCodec.Visibility = Visibility.Collapsed;
} }
private void lstSaveFiles_SelectionChanged(object sender, SelectionChangedEventArgs e) private void lstSaveFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ {
if (lstSaveFiles.SelectedItem is not SaveFileEntry entry) return; if (this.lstSaveFiles.SelectedItem is not SaveFileEntry entry) return;
_currentSelectedFile = entry; this._currentSelectedFile = entry;
lblCurrentFileName.Text = entry.FileName; this.lblCurrentFileName.Text = entry.FileName;
lblCurrentFilePath.Text = entry.FilePath; this.lblCurrentFilePath.Text = entry.FilePath;
HideAllEditorPanels(); this.HideAllEditorPanels();
// 1. コーデック(対応形式)が存在するか判定 // 1. コーデック(対応形式)が存在するか判定
var codec = SaveDataCodecManager.Instance.FindCodec(Game, entry); var codec = SaveDataCodecManager.Instance.FindCodec(this.Game, entry);
if (codec != null) if (codec != null)
{ {
// GUI エディタモードをアクティブ化 // GUI エディタモードをアクティブ化
_currentCodec = codec; this._currentCodec = codec;
badgeCodec.Visibility = Visibility.Visible; this.badgeCodec.Visibility = Visibility.Visible;
lblCodecName.Text = codec.CodecName; this.lblCodecName.Text = codec.CodecName;
LoadGuiPropertiesFromCodec(codec, entry.FilePath); this.LoadGuiPropertiesFromCodec(codec, entry.FilePath);
pnlGuiEditor.Visibility = Visibility.Visible; this.pnlGuiEditor.Visibility = Visibility.Visible;
btnSaveGuiProperties.Visibility = Visibility.Visible; this.btnSaveGuiProperties.Visibility = Visibility.Visible;
lblStatus.Text = $"{codec.CodecName} で読み込みました: {entry.FileName}"; this.lblStatus.Text = $"{codec.CodecName} で読み込みました: {entry.FileName}";
return; return;
} }
// 2. プレーンテキスト/JSON形式の場合 // 2. プレーンテキスト/JSON形式の場合
if (entry.IsTextOrJson) if (entry.IsTextOrJson)
{ {
pnlTextEditor.Visibility = Visibility.Visible; this.pnlTextEditor.Visibility = Visibility.Visible;
txtFileContent.Text = _saveService.ReadSaveFileText(entry.FilePath); this.txtFileContent.Text = this._saveService.ReadSaveFileText(entry.FilePath);
btnFormatJson.Visibility = Visibility.Visible; this.btnFormatJson.Visibility = Visibility.Visible;
btnSaveFileContent.Visibility = Visibility.Visible; this.btnSaveFileContent.Visibility = Visibility.Visible;
lblStatus.Text = $"テキストとして開きました: {entry.FileName}"; this.lblStatus.Text = $"テキストとして開きました: {entry.FileName}";
return; return;
} }
// 3. 未対応のバイナリセーブデータ形式の場合 // 3. 未対応のバイナリセーブデータ形式の場合
pnlUnsupportedBinary.Visibility = Visibility.Visible; this.pnlUnsupportedBinary.Visibility = Visibility.Visible;
DisplayUnsupportedBinaryInfo(entry); this.DisplayUnsupportedBinaryInfo(entry);
lblStatus.Text = $"未対応のバイナリセーブデータ: {entry.FileName}"; this.lblStatus.Text = $"未対応のバイナリセーブデータ: {entry.FileName}";
} }
private void LoadGuiPropertiesFromCodec(ISaveDataCodec codec, string filePath) private void LoadGuiPropertiesFromCodec(ISaveDataCodec codec, string filePath)
{ {
_guiProperties.Clear(); this._guiProperties.Clear();
var props = codec.LoadProperties(filePath); var props = codec.LoadProperties(filePath);
foreach (var p in props) foreach (var p in props)
{ {
_guiProperties.Add(p); this._guiProperties.Add(p);
} }
lblGuiPropCount.Text = $"{props.Count} 項目"; this.lblGuiPropCount.Text = $"{props.Count} 項目";
if (props.Count > 0) if (props.Count > 0)
{ {
dgGuiProperties.SelectedIndex = 0; this.dgGuiProperties.SelectedIndex = 0;
} }
} }
private bool FilterGuiProperties(object obj) private bool FilterGuiProperties(object obj)
{ {
if (obj is not SaveDataPropertyEntry prop) return false; if (obj is not SaveDataPropertyEntry prop) return false;
var query = txtSearchGuiProps.Text.Trim(); var query = this.txtSearchGuiProps.Text.Trim();
if (string.IsNullOrEmpty(query)) return true; if (string.IsNullOrEmpty(query)) return true;
return prop.Key.Contains(query, StringComparison.OrdinalIgnoreCase) || return prop.Key.Contains(query, StringComparison.OrdinalIgnoreCase) ||
@@ -384,26 +389,26 @@ namespace GameLauncher
private void txtSearchGuiProps_TextChanged(object sender, TextChangedEventArgs e) private void txtSearchGuiProps_TextChanged(object sender, TextChangedEventArgs e)
{ {
_guiPropsView.Refresh(); this._guiPropsView.Refresh();
int visibleCount = _guiPropsView.Cast<object>().Count(); int visibleCount = this._guiPropsView.Cast<object>().Count();
lblGuiPropCount.Text = $"{visibleCount} / {_guiProperties.Count} 項目"; this.lblGuiPropCount.Text = $"{visibleCount} / {this._guiProperties.Count} 項目";
} }
private void dgGuiProperties_SelectionChanged(object sender, SelectionChangedEventArgs e) private void dgGuiProperties_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ {
if (dgGuiProperties.SelectedItem is SaveDataPropertyEntry prop) if (this.dgGuiProperties.SelectedItem is SaveDataPropertyEntry prop)
{ {
lblSelectedPropKey.Text = prop.Key; this.lblSelectedPropKey.Text = prop.Key;
txtEditPropValueBar.Text = prop.EditValue; this.txtEditPropValueBar.Text = prop.EditValue;
txtEditPropValueBar.IsEnabled = true; this.txtEditPropValueBar.IsEnabled = true;
btnApplyPropValue.IsEnabled = true; this.btnApplyPropValue.IsEnabled = true;
} }
else else
{ {
lblSelectedPropKey.Text = "(未選択)"; this.lblSelectedPropKey.Text = "(未選択)";
txtEditPropValueBar.Text = string.Empty; this.txtEditPropValueBar.Text = string.Empty;
txtEditPropValueBar.IsEnabled = false; this.txtEditPropValueBar.IsEnabled = false;
btnApplyPropValue.IsEnabled = false; this.btnApplyPropValue.IsEnabled = false;
} }
} }
@@ -411,28 +416,28 @@ namespace GameLauncher
{ {
if (e.Key == Key.Enter) if (e.Key == Key.Enter)
{ {
btnApplyPropValue_Click(sender, e); this.btnApplyPropValue_Click(sender, e);
} }
} }
private void btnApplyPropValue_Click(object sender, RoutedEventArgs e) private void btnApplyPropValue_Click(object sender, RoutedEventArgs e)
{ {
if (dgGuiProperties.SelectedItem is SaveDataPropertyEntry prop) if (this.dgGuiProperties.SelectedItem is SaveDataPropertyEntry prop)
{ {
prop.EditValue = txtEditPropValueBar.Text; prop.EditValue = this.txtEditPropValueBar.Text;
dgGuiProperties.Items.Refresh(); this.dgGuiProperties.Items.Refresh();
lblStatus.Text = $"項目 '{prop.Key}' の値を変更しました。(「変更を保存」ボタンでファイルへ書き戻せます)"; this.lblStatus.Text = $"項目 '{prop.Key}' の値を変更しました。(「変更を保存」ボタンでファイルへ書き戻せます)";
} }
} }
private void btnSaveGuiProperties_Click(object sender, RoutedEventArgs e) private void btnSaveGuiProperties_Click(object sender, RoutedEventArgs e)
{ {
if (_currentSelectedFile == null || _currentCodec == null) return; if (this._currentSelectedFile == null || this._currentCodec == null) return;
bool success = _currentCodec.SaveProperties(_currentSelectedFile.FilePath, _guiProperties.ToList()); bool success = this._currentCodec.SaveProperties(this._currentSelectedFile.FilePath, [.. this._guiProperties]);
if (success) if (success)
{ {
lblStatus.Text = $"セーブファイルを正常に更新しました (自動バックアップ .bak 作成済み): {_currentSelectedFile.FileName}"; this.lblStatus.Text = $"セーブファイルを正常に更新しました (自動バックアップ .bak 作成済み): {this._currentSelectedFile.FileName}";
MessageBox.Show("セーブファイルを正常に更新・保存しました。\n(元のファイルは同階層に .bak として自動バックアップされています)", MessageBox.Show("セーブファイルを正常に更新・保存しました。\n(元のファイルは同階層に .bak として自動バックアップされています)",
"保存完了", MessageBoxButton.OK, MessageBoxImage.Information); "保存完了", MessageBoxButton.OK, MessageBoxImage.Information);
} }
@@ -455,41 +460,41 @@ namespace GameLauncher
{ {
hexList.Add(bytes[i].ToString("X2")); hexList.Add(bytes[i].ToString("X2"));
} }
lblHexPreview.Text = string.Join(" ", hexList) + (bytes.Length > 32 ? " ..." : ""); this.lblHexPreview.Text = string.Join(" ", hexList) + (bytes.Length > 32 ? " ..." : "");
} }
} }
catch catch
{ {
lblHexPreview.Text = "(読み込み失敗)"; this.lblHexPreview.Text = "(読み込み失敗)";
} }
} }
private void btnCopyIdePrompt_Click(object sender, RoutedEventArgs e) private void btnCopyIdePrompt_Click(object sender, RoutedEventArgs e)
{ {
if (_currentSelectedFile == null) return; if (this._currentSelectedFile == null) return;
string prompt = SaveDataCodecManager.Instance.GenerateAntigravityPrompt(Game, _currentSelectedFile); string prompt = SaveDataCodecManager.Instance.GenerateAntigravityPrompt(this.Game, this._currentSelectedFile);
Clipboard.SetText(prompt); Clipboard.SetText(prompt);
lblStatus.Text = "📋 Antigravity IDE 用の解析依頼プロンプトをクリップボードにコピーしました!"; this.lblStatus.Text = "📋 Antigravity IDE 用の解析依頼プロンプトをクリップボードにコピーしました!";
MessageBox.Show("Antigravity IDE 解析用プロンプトをコピーしました!\n\nAntigravity IDE のチャット欄に貼り付けて送信すると、AIがこのゲームのセーブデータ構造を解析し、GUI編集プラグインを自動で追加してくれます。", MessageBox.Show("Antigravity IDE 解析用プロンプトをコピーしました!\n\nAntigravity IDE のチャット欄に貼り付けて送信すると、AIがこのゲームのセーブデータ構造を解析し、GUI編集プラグインを自動で追加してくれます。",
"プロンプトをコピーしました", MessageBoxButton.OK, MessageBoxImage.Information); "プロンプトをコピーしました", MessageBoxButton.OK, MessageBoxImage.Information);
} }
private void btnForceShowBinary_Click(object sender, RoutedEventArgs e) private void btnForceShowBinary_Click(object sender, RoutedEventArgs e)
{ {
if (_currentSelectedFile == null) return; if (this._currentSelectedFile == null) return;
pnlUnsupportedBinary.Visibility = Visibility.Collapsed; this.pnlUnsupportedBinary.Visibility = Visibility.Collapsed;
pnlTextEditor.Visibility = Visibility.Visible; this.pnlTextEditor.Visibility = Visibility.Visible;
btnSaveFileContent.Visibility = Visibility.Visible; this.btnSaveFileContent.Visibility = Visibility.Visible;
txtFileContent.Text = _saveService.ReadSaveFileText(_currentSelectedFile.FilePath); this.txtFileContent.Text = this._saveService.ReadSaveFileText(this._currentSelectedFile.FilePath);
} }
private void btnFormatJson_Click(object sender, RoutedEventArgs e) private void btnFormatJson_Click(object sender, RoutedEventArgs e)
{ {
try try
{ {
var raw = txtFileContent.Text; var raw = this.txtFileContent.Text;
if (string.IsNullOrWhiteSpace(raw)) return; if (string.IsNullOrWhiteSpace(raw)) return;
using var doc = JsonDocument.Parse(raw); using var doc = JsonDocument.Parse(raw);
@@ -498,8 +503,8 @@ namespace GameLauncher
WriteIndented = true, WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
}); });
txtFileContent.Text = formatted; this.txtFileContent.Text = formatted;
lblStatus.Text = "JSONを整形しました。"; this.lblStatus.Text = "JSONを整形しました。";
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -509,12 +514,12 @@ namespace GameLauncher
private void btnSaveFileContent_Click(object sender, RoutedEventArgs e) private void btnSaveFileContent_Click(object sender, RoutedEventArgs e)
{ {
if (_currentSelectedFile == null) return; if (this._currentSelectedFile == null) return;
bool success = _saveService.WriteSaveFileText(_currentSelectedFile.FilePath, txtFileContent.Text); bool success = this._saveService.WriteSaveFileText(this._currentSelectedFile.FilePath, this.txtFileContent.Text);
if (success) if (success)
{ {
lblStatus.Text = $"ファイルを保存しました (自動バックアップ .bak 作成済み): {_currentSelectedFile.FileName}"; this.lblStatus.Text = $"ファイルを保存しました (自動バックアップ .bak 作成済み): {this._currentSelectedFile.FileName}";
MessageBox.Show("ファイルを保存しました。\n(元のファイルは同階層に .bak としてバックアップされています)", MessageBox.Show("ファイルを保存しました。\n(元のファイルは同階層に .bak としてバックアップされています)",
"保存完了", MessageBoxButton.OK, MessageBoxImage.Information); "保存完了", MessageBoxButton.OK, MessageBoxImage.Information);
} }
@@ -527,14 +532,14 @@ namespace GameLauncher
private void btnBackupSingleFile_Click(object sender, RoutedEventArgs e) private void btnBackupSingleFile_Click(object sender, RoutedEventArgs e)
{ {
if (_currentSelectedFile == null) return; if (this._currentSelectedFile == null) return;
var backupDir = AppPathHelper.GetGameBackupDirectory(Game.FolderName, Game.RootDirectory); var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory);
var result = _saveService.BackupSaveFile(_currentSelectedFile.FilePath, backupDir); var result = this._saveService.BackupSaveFile(this._currentSelectedFile.FilePath, backupDir);
if (result != null) if (result != null)
{ {
ReloadBackups(); this.ReloadBackups();
lblStatus.Text = $"ファイルをバックアップしました: {Path.GetFileName(result)}"; this.lblStatus.Text = $"ファイルをバックアップしました: {Path.GetFileName(result)}";
MessageBox.Show($"ファイルをバックアップしました:\n\n{result}", "バックアップ完了", MessageBoxButton.OK, MessageBoxImage.Information); MessageBox.Show($"ファイルをバックアップしました:\n\n{result}", "バックアップ完了", MessageBoxButton.OK, MessageBoxImage.Information);
} }
else else
@@ -545,7 +550,7 @@ namespace GameLauncher
private void btnReloadSaveFiles_Click(object sender, RoutedEventArgs e) private void btnReloadSaveFiles_Click(object sender, RoutedEventArgs e)
{ {
ReloadSaveFiles(); this.ReloadSaveFiles();
} }
// ==================================================================== // ====================================================================
@@ -554,22 +559,22 @@ namespace GameLauncher
public void ReloadBackups() public void ReloadBackups()
{ {
_backups.Clear(); this._backups.Clear();
var list = _saveService.GetBackupList(Game); var list = this._saveService.GetBackupList(this.Game);
foreach (var b in list) foreach (var b in list)
{ {
_backups.Add(b); this._backups.Add(b);
} }
} }
private void btnReloadBackups_Click(object sender, RoutedEventArgs e) private void btnReloadBackups_Click(object sender, RoutedEventArgs e)
{ {
ReloadBackups(); this.ReloadBackups();
} }
private void btnOpenBackupDir_Click(object sender, RoutedEventArgs e) private void btnOpenBackupDir_Click(object sender, RoutedEventArgs e)
{ {
var backupDir = AppPathHelper.GetGameBackupDirectory(Game.FolderName, Game.RootDirectory); var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory);
UnitySaveManagerService.OpenFolderInExplorer(backupDir); UnitySaveManagerService.OpenFolderInExplorer(backupDir);
} }
@@ -583,9 +588,9 @@ namespace GameLauncher
"復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning); "復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (res == MessageBoxResult.Yes) if (res == MessageBoxResult.Yes)
{ {
if (_saveService.RestoreRegistry(backup.BackupPath)) if (this._saveService.RestoreRegistry(backup.BackupPath))
{ {
ReloadPlayerPrefs(); this.ReloadPlayerPrefs();
MessageBox.Show("レジストリを正常に復元しました。", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information); MessageBox.Show("レジストリを正常に復元しました。", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
} }
else else
@@ -608,29 +613,29 @@ namespace GameLauncher
private void btnOpenLocalLow_Click(object sender, RoutedEventArgs e) private void btnOpenLocalLow_Click(object sender, RoutedEventArgs e)
{ {
if (!string.IsNullOrEmpty(Game.LocalLowPath)) if (!string.IsNullOrEmpty(this.Game.LocalLowPath))
{ {
if (!Directory.Exists(Game.LocalLowPath)) if (!Directory.Exists(this.Game.LocalLowPath))
{ {
var parent = Path.GetDirectoryName(Game.LocalLowPath); var parent = Path.GetDirectoryName(this.Game.LocalLowPath);
if (parent != null && Directory.Exists(parent)) if (parent != null && Directory.Exists(parent))
{ {
UnitySaveManagerService.OpenFolderInExplorer(parent); UnitySaveManagerService.OpenFolderInExplorer(parent);
return; return;
} }
} }
UnitySaveManagerService.OpenFolderInExplorer(Game.LocalLowPath); UnitySaveManagerService.OpenFolderInExplorer(this.Game.LocalLowPath);
} }
} }
private void btnOpenGameFolder_Click(object sender, RoutedEventArgs e) private void btnOpenGameFolder_Click(object sender, RoutedEventArgs e)
{ {
UnitySaveManagerService.OpenFolderInExplorer(Game.RootDirectory); UnitySaveManagerService.OpenFolderInExplorer(this.Game.RootDirectory);
} }
private void btnOpenRegedit_Click(object sender, RoutedEventArgs e) private void btnOpenRegedit_Click(object sender, RoutedEventArgs e)
{ {
_saveService.OpenRegistryEditor(Game.RegistryPath); this._saveService.OpenRegistryEditor(this.Game.RegistryPath);
} }
} }
} }
+101 -28
View File
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
@@ -7,6 +7,7 @@ using System.Text;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
using GameLauncher.Engines.Unity;
using GameLauncher.Models; using GameLauncher.Models;
namespace GameLauncher.Services.Codecs namespace GameLauncher.Services.Codecs
@@ -16,10 +17,19 @@ namespace GameLauncher.Services.Codecs
/// </summary> /// </summary>
public class EasySave3Codec : ISaveDataCodec public class EasySave3Codec : ISaveDataCodec
{ {
/// <summary>
/// コーデックの表示名を取得します。
/// </summary>
public string CodecName => "Easy Save 3 (ES3) コーデック"; public string CodecName => "Easy Save 3 (ES3) コーデック";
/// <summary>
/// パスワード入力が必要かどうかを取得します。
/// </summary>
public bool RequiresPassword => false; public bool RequiresPassword => false;
/// <summary>
/// パスワード入力ダイアログに表示する案内メッセージを取得します。
/// </summary>
public string? PasswordPromptMessage => "暗号化パスワードが設定されている場合は入力してください(未設定・既定の場合は空欄):"; public string? PasswordPromptMessage => "暗号化パスワードが設定されている場合は入力してください(未設定・既定の場合は空欄):";
// キャッシュ用の最新平文JSONノード // キャッシュ用の最新平文JSONノード
@@ -27,6 +37,12 @@ namespace GameLauncher.Services.Codecs
private bool _wasEncrypted; private bool _wasEncrypted;
private string? _usedPassword; private string? _usedPassword;
/// <summary>
/// 指定されたセーブファイルが本コーデックで処理可能かを判定します。
/// </summary>
/// <param name="game">対象のUnityゲーム情報</param>
/// <param name="file">対象のセーブファイル情報</param>
/// <returns>処理可能な場合は true、それ以外は false</returns>
public bool CanHandle(UnityGameItem game, SaveFileEntry file) public bool CanHandle(UnityGameItem game, SaveFileEntry file)
{ {
var ext = Path.GetExtension(file.FilePath).ToLowerInvariant(); var ext = Path.GetExtension(file.FilePath).ToLowerInvariant();
@@ -42,6 +58,12 @@ namespace GameLauncher.Services.Codecs
return false; return false;
} }
/// <summary>
/// セーブファイルからプロパティ一覧を読み込みます。
/// </summary>
/// <param name="filePath">セーブファイルの絶対パス</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>展開されたセーブデータプロパティのリスト</returns>
public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null) public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null)
{ {
var list = new List<SaveDataPropertyEntry>(); var list = new List<SaveDataPropertyEntry>();
@@ -51,8 +73,8 @@ namespace GameLauncher.Services.Codecs
if (fileBytes.Length == 0) return list; if (fileBytes.Length == 0) return list;
string? jsonText = null; string? jsonText = null;
_wasEncrypted = false; this._wasEncrypted = false;
_usedPassword = null; this._usedPassword = null;
// 1. まず平文 JSON または Gzip 解凍を試みる // 1. まず平文 JSON または Gzip 解凍を試みる
try try
@@ -90,12 +112,12 @@ namespace GameLauncher.Services.Codecs
foreach (var pwd in candidatePasswords) foreach (var pwd in candidatePasswords)
{ {
var decrypted = TryDecryptAes(fileBytes, pwd); var decrypted = this.TryDecryptAes(fileBytes, pwd);
if (!string.IsNullOrEmpty(decrypted)) if (!string.IsNullOrEmpty(decrypted))
{ {
jsonText = decrypted; jsonText = decrypted;
_wasEncrypted = true; this._wasEncrypted = true;
_usedPassword = pwd; this._usedPassword = pwd;
break; break;
} }
} }
@@ -104,30 +126,36 @@ namespace GameLauncher.Services.Codecs
if (string.IsNullOrEmpty(jsonText)) if (string.IsNullOrEmpty(jsonText))
{ {
// JSON展開ができなかった場合、バイナリキー・バリュー形式として先頭・重要オフセットを抽出 // JSON展開ができなかった場合、バイナリキー・バリュー形式として先頭・重要オフセットを抽出
return ExtractBinaryPropertiesFallback(fileBytes); return this.ExtractBinaryPropertiesFallback(fileBytes);
} }
// JSON からプロパティを再帰的に展開 // JSON からプロパティを再帰的に展開
try try
{ {
_cachedRootNode = JsonNode.Parse(jsonText); this._cachedRootNode = JsonNode.Parse(jsonText);
if (_cachedRootNode is JsonObject rootObj) if (this._cachedRootNode is JsonObject rootObj)
{ {
FlattenJsonObject(rootObj, "", list); this.FlattenJsonObject(rootObj, "", list);
} }
else if (_cachedRootNode is JsonArray rootArr) else if (this._cachedRootNode is JsonArray rootArr)
{ {
FlattenJsonArray(rootArr, "Array", list); this.FlattenJsonArray(rootArr, "Array", list);
} }
} }
catch catch
{ {
return ExtractBinaryPropertiesFallback(fileBytes); return this.ExtractBinaryPropertiesFallback(fileBytes);
} }
return list; return list;
} }
/// <summary>
/// JSONオブジェクトを再帰的に走査し、プロパティ一覧に追加します。
/// </summary>
/// <param name="obj">対象のJSONオブジェクト</param>
/// <param name="prefix">現在のキー階層プレフィックス</param>
/// <param name="list">追加先のプロパティリスト</param>
private void FlattenJsonObject(JsonObject obj, string prefix, List<SaveDataPropertyEntry> list) private void FlattenJsonObject(JsonObject obj, string prefix, List<SaveDataPropertyEntry> list)
{ {
foreach (var kvp in obj) foreach (var kvp in obj)
@@ -180,14 +208,14 @@ namespace GameLauncher.Services.Codecs
} }
else else
{ {
FlattenJsonObject(childObj, key, list); this.FlattenJsonObject(childObj, key, list);
} }
} }
else if (node is JsonArray childArr) else if (node is JsonArray childArr)
{ {
if (childArr.Count <= 20) if (childArr.Count <= 20)
{ {
FlattenJsonArray(childArr, key, list); this.FlattenJsonArray(childArr, key, list);
} }
else else
{ {
@@ -205,6 +233,12 @@ namespace GameLauncher.Services.Codecs
} }
} }
/// <summary>
/// JSON配列を再帰的に走査し、プロパティ一覧に追加します。
/// </summary>
/// <param name="arr">対象のJSON配列</param>
/// <param name="prefix">現在のキー階層プレフィックス</param>
/// <param name="list">追加先のプロパティリスト</param>
private void FlattenJsonArray(JsonArray arr, string prefix, List<SaveDataPropertyEntry> list) private void FlattenJsonArray(JsonArray arr, string prefix, List<SaveDataPropertyEntry> list)
{ {
for (int i = 0; i < arr.Count; i++) for (int i = 0; i < arr.Count; i++)
@@ -224,22 +258,29 @@ namespace GameLauncher.Services.Codecs
} }
else if (node is JsonObject childObj) else if (node is JsonObject childObj)
{ {
FlattenJsonObject(childObj, key, list); this.FlattenJsonObject(childObj, key, list);
} }
} }
} }
/// <summary>
/// JSON展開に失敗した場合のフォールバックとしてバイナリ値を抽出します。
/// </summary>
/// <param name="bytes">ファイル全体のバイナリデータ</param>
/// <returns>バイナリ情報プロパティのリスト</returns>
private List<SaveDataPropertyEntry> ExtractBinaryPropertiesFallback(byte[] bytes) private List<SaveDataPropertyEntry> ExtractBinaryPropertiesFallback(byte[] bytes)
{ {
var list = new List<SaveDataPropertyEntry>(); var list = new List<SaveDataPropertyEntry>
list.Add(new SaveDataPropertyEntry {
new SaveDataPropertyEntry
{ {
Key = "FileSize", Key = "FileSize",
Category = "ファイル情報", Category = "ファイル情報",
Type = "Int", Type = "Int",
EditValue = bytes.Length.ToString(), EditValue = bytes.Length.ToString(),
Description = "ファイルサイズ (bytes)" Description = "ファイルサイズ (bytes)"
}); }
};
// 先頭 128 バイトから 4 バイト整数と ASCII 文字列を検出してプロパティ化 // 先頭 128 バイトから 4 バイト整数と ASCII 文字列を検出してプロパティ化
int limit = Math.Min(bytes.Length - 4, 128); int limit = Math.Min(bytes.Length - 4, 128);
@@ -260,18 +301,25 @@ namespace GameLauncher.Services.Codecs
return list; return list;
} }
/// <summary>
/// 編集後のプロパティ一覧をセーブファイルへ書き戻して保存します。
/// </summary>
/// <param name="filePath">保存先セーブファイルの絶対パス</param>
/// <param name="properties">編集されたプロパティ一覧</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>保存に成功した場合は true、それ以外は false</returns>
public bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null) public bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null)
{ {
try try
{ {
if (_cachedRootNode != null) if (this._cachedRootNode != null)
{ {
// JSON の値を更新 // JSON の値を更新
foreach (var prop in properties) foreach (var prop in properties)
{ {
if (prop.RawData is string keyPath) if (prop.RawData is string keyPath)
{ {
UpdateJsonNodeByPath(_cachedRootNode, keyPath, prop.EditValue, prop.Type); this.UpdateJsonNodeByPath(this._cachedRootNode, keyPath, prop.EditValue, prop.Type);
} }
} }
@@ -280,15 +328,15 @@ namespace GameLauncher.Services.Codecs
WriteIndented = true, WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
}; };
string updatedJson = _cachedRootNode.ToJsonString(options); string updatedJson = this._cachedRootNode.ToJsonString(options);
byte[] outputBytes = Encoding.UTF8.GetBytes(updatedJson); byte[] outputBytes = Encoding.UTF8.GetBytes(updatedJson);
// もともと暗号化されていた場合は再暗号化 // もともと暗号化されていた場合は再暗号化
if (_wasEncrypted) if (this._wasEncrypted)
{ {
string pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword : (_usedPassword ?? "Moodkie"); string pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword : (this._usedPassword ?? "Moodkie");
outputBytes = EncryptAes(outputBytes, pwd); outputBytes = this.EncryptAes(outputBytes, pwd);
} }
// バックアップ作成 // バックアップ作成
@@ -330,12 +378,19 @@ namespace GameLauncher.Services.Codecs
} }
} }
/// <summary>
/// キーパスに基づいてJSONノードの値を更新します。
/// </summary>
/// <param name="root">ルートのJSONノード</param>
/// <param name="path">ドット区切りのキーパス</param>
/// <param name="newValue">更新後の値文字列</param>
/// <param name="type">値の型名</param>
private void UpdateJsonNodeByPath(JsonNode root, string path, string newValue, string type) private void UpdateJsonNodeByPath(JsonNode root, string path, string newValue, string type)
{ {
try try
{ {
// ドットと角括弧でパスを分割 // ドットと角括弧でパスを分割
var parts = path.Split(new[] { '.', '[', ']' }, StringSplitOptions.RemoveEmptyEntries); var parts = path.Split(['.', '[', ']'], StringSplitOptions.RemoveEmptyEntries);
JsonNode? current = root; JsonNode? current = root;
for (int i = 0; i < parts.Length - 1; i++) for (int i = 0; i < parts.Length - 1; i++)
@@ -357,16 +412,22 @@ namespace GameLauncher.Services.Codecs
string lastKey = parts[^1]; string lastKey = parts[^1];
if (current is JsonObject finalObj) if (current is JsonObject finalObj)
{ {
finalObj[lastKey] = ParseJsonValue(newValue, type); finalObj[lastKey] = this.ParseJsonValue(newValue, type);
} }
else if (current is JsonArray finalArr && int.TryParse(lastKey, out int finalIdx) && finalIdx < finalArr.Count) else if (current is JsonArray finalArr && int.TryParse(lastKey, out int finalIdx) && finalIdx < finalArr.Count)
{ {
finalArr[finalIdx] = ParseJsonValue(newValue, type); finalArr[finalIdx] = this.ParseJsonValue(newValue, type);
} }
} }
catch { } catch { }
} }
/// <summary>
/// 文字列値と型名から対応するJSONノードを生成します。
/// </summary>
/// <param name="value">値文字列</param>
/// <param name="type">型名</param>
/// <returns>生成されたJSONノード</returns>
private JsonNode? ParseJsonValue(string value, string type) private JsonNode? ParseJsonValue(string value, string type)
{ {
if (type == "Int" && int.TryParse(value, out int i)) return JsonValue.Create(i); if (type == "Int" && int.TryParse(value, out int i)) return JsonValue.Create(i);
@@ -388,6 +449,12 @@ namespace GameLauncher.Services.Codecs
return JsonValue.Create(value); return JsonValue.Create(value);
} }
/// <summary>
/// AESアルゴリズムによるセーブデータの復号を試みます。
/// </summary>
/// <param name="data">暗号化バイナリデータ</param>
/// <param name="password">復号パスワード</param>
/// <returns>復号された平文文字列。失敗時は null</returns>
private string? TryDecryptAes(byte[] data, string password) private string? TryDecryptAes(byte[] data, string password)
{ {
try try
@@ -423,6 +490,12 @@ namespace GameLauncher.Services.Codecs
return null; return null;
} }
/// <summary>
/// 平文バイト配列をAESアルゴリズムで暗号化します。
/// </summary>
/// <param name="plainBytes">平文バイナリデータ</param>
/// <param name="password">暗号化パスワード</param>
/// <returns>暗号化されたバイナリデータ</returns>
private byte[] EncryptAes(byte[] plainBytes, string password) private byte[] EncryptAes(byte[] plainBytes, string password)
{ {
byte[] rawUtf8 = Encoding.UTF8.GetBytes(password); byte[] rawUtf8 = Encoding.UTF8.GetBytes(password);
+30 -7
View File
@@ -1,4 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using GameLauncher.Engines.Unity;
using GameLauncher.Models; using GameLauncher.Models;
namespace GameLauncher.Services.Codecs namespace GameLauncher.Services.Codecs
@@ -8,22 +9,44 @@ namespace GameLauncher.Services.Codecs
/// </summary> /// </summary>
public interface ISaveDataCodec public interface ISaveDataCodec
{ {
/// <summary>コーデックの識別名称(例: "Easy Save 3 (ES3)", "YU-RIS セーブデータ")</summary> /// <summary>
/// コーデックの識別名称(例: "Easy Save 3 (ES3)", "YU-RIS セーブデータ")を取得します。
/// </summary>
string CodecName { get; } string CodecName { get; }
/// <summary>このコーデックで指定ファイルを処理可能か判定</summary> /// <summary>
/// このコーデックで指定ファイルを処理可能か判定します。
/// </summary>
/// <param name="game">対象のUnityゲーム情報</param>
/// <param name="file">対象のセーブファイル情報</param>
/// <returns>処理可能な場合は true、それ以外は false</returns>
bool CanHandle(UnityGameItem game, SaveFileEntry file); bool CanHandle(UnityGameItem game, SaveFileEntry file);
/// <summary>セーブファイルからGUI編集用プロパティ一覧をロード・解析</summary> /// <summary>
/// セーブファイルからGUI編集用プロパティ一覧をロード・解析します。
/// </summary>
/// <param name="filePath">セーブファイルの絶対パス</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>展開されたセーブデータプロパティのリスト</returns>
List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null); List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null);
/// <summary>GUI編集されたプロパティ一覧をファイルへ再エンコード・保存</summary> /// <summary>
/// GUI編集されたプロパティ一覧をファイルへ再エンコード・保存します。
/// </summary>
/// <param name="filePath">保存先セーブファイルの絶対パス</param>
/// <param name="properties">編集されたプロパティ一覧</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>保存に成功した場合は true、それ以外は false</returns>
bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null); bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null);
/// <summary>復号にパスワードやキーが必要かどうか</summary> /// <summary>
/// 復号にパスワードやキーが必要かどうかを取得します。
/// </summary>
bool RequiresPassword { get; } bool RequiresPassword { get; }
/// <summary>パスワード入力時の案内メッセージ</summary> /// <summary>
/// パスワード入力時の案内メッセージを取得します。
/// </summary>
string? PasswordPromptMessage { get; } string? PasswordPromptMessage { get; }
} }
} }
+30 -1
View File
@@ -1,7 +1,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using System.Text;
using GameLauncher.Engines.Unity;
using GameLauncher.Models; using GameLauncher.Models;
namespace GameLauncher.Services.Codecs namespace GameLauncher.Services.Codecs
@@ -11,12 +12,27 @@ namespace GameLauncher.Services.Codecs
/// </summary> /// </summary>
public class YurisSaveCodec : ISaveDataCodec public class YurisSaveCodec : ISaveDataCodec
{ {
/// <summary>
/// コーデックの表示名を取得します。
/// </summary>
public string CodecName => "YU-RIS セーブデータ (YSSD) コーデック"; public string CodecName => "YU-RIS セーブデータ (YSSD) コーデック";
/// <summary>
/// パスワード入力が必要かどうかを取得します。
/// </summary>
public bool RequiresPassword => false; public bool RequiresPassword => false;
/// <summary>
/// パスワード入力ダイアログに表示する案内メッセージを取得します。
/// </summary>
public string? PasswordPromptMessage => null; public string? PasswordPromptMessage => null;
/// <summary>
/// 指定されたセーブファイルが本コーデックで処理可能かを判定します。
/// </summary>
/// <param name="game">対象のUnityゲーム情報</param>
/// <param name="file">対象のセーブファイル情報</param>
/// <returns>処理可能な場合は true、それ以外は false</returns>
public bool CanHandle(UnityGameItem game, SaveFileEntry file) public bool CanHandle(UnityGameItem game, SaveFileEntry file)
{ {
if (!File.Exists(file.FilePath)) return false; if (!File.Exists(file.FilePath)) return false;
@@ -38,6 +54,12 @@ namespace GameLauncher.Services.Codecs
} }
} }
/// <summary>
/// セーブファイルからプロパティ一覧を読み込みます。
/// </summary>
/// <param name="filePath">セーブファイルの絶対パス</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>展開されたセーブデータプロパティのリスト</returns>
public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null) public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null)
{ {
var list = new List<SaveDataPropertyEntry>(); var list = new List<SaveDataPropertyEntry>();
@@ -100,6 +122,13 @@ namespace GameLauncher.Services.Codecs
return list; return list;
} }
/// <summary>
/// 編集後のプロパティ一覧をセーブファイルへ書き戻して保存します。
/// </summary>
/// <param name="filePath">保存先セーブファイルの絶対パス</param>
/// <param name="properties">編集されたプロパティ一覧</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>保存に成功した場合は true、それ以外は false</returns>
public bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null) public bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null)
{ {
try try
+312
View File
@@ -0,0 +1,312 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Interop;
namespace GameLauncher.Services
{
/// <summary>
/// 高速検索ソフト「Everything」のIPC (WM_COPYDATA) APIを利用して、
/// 指定フォルダ配下の全ファイルおよびサブディレクトリを0.1秒未満で一括取得するサービス
/// </summary>
public class EverythingSearchService
{
#region □定数(Private)
private const int WM_COPYDATA = 0x004A;
private const int EVERYTHING_IPC_COPYDATA_QUERYW = 2;
private const uint EVERYTHING_IPC_ALLRESULTS = 0xFFFFFFFF;
private const uint EVERYTHING_IPC_FOLDER = 0x00000002;
private const uint EVERYTHING_IPC_DRIVE = 0x00000004;
private const uint PM_REMOVE = 0x0001;
#endregion
#region □構造体(Private)
[StructLayout(LayoutKind.Sequential)]
private struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct EVERYTHING_IPC_QUERYW_HEADER
{
public uint max_results;
public uint offset;
public uint reply_copydata_message;
public uint search_flags;
public IntPtr reply_hwnd;
}
[StructLayout(LayoutKind.Sequential)]
private struct MSG
{
public IntPtr hwnd;
public uint message;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public int pt_x;
public int pt_y;
}
#endregion
#region □メソッド(Public)
/// <summary>
/// Everything が現在システム上で実行中であるか判定します。
/// </summary>
public static bool IsEverythingRunning()
{
try
{
var procs = Process.GetProcessesByName("Everything");
if (procs != null && procs.Length > 0)
{
return true;
}
}
catch { }
try
{
var hwnd = FindWindowW("EVERYTHING_TASKBAR_NOTIFICATION", null);
if (hwnd != IntPtr.Zero)
{
return true;
}
}
catch { }
return false;
}
/// <summary>
/// 指定されたパス群(例: C:\..., Z:\...)に対して、Everything IPCを用いて高速スナップショットを生成します。
/// </summary>
/// <param name="targetDirectories">走査対象のディレクトリルート一覧</param>
/// <param name="timeoutMs">タイムアウト(ミリ秒)</param>
/// <returns>生成されたスナップショット。Everything未稼働または失敗時は null</returns>
public static FastDirectorySnapshot? TryScanTargetsFast(IEnumerable<string> targetDirectories, int timeoutMs = 3000)
{
var everythingHwnd = FindWindowW("EVERYTHING_TASKBAR_NOTIFICATION", null);
if (everythingHwnd == IntPtr.Zero)
{
return null;
}
var snapshot = new FastDirectorySnapshot();
bool anySuccess = false;
foreach (var targetDir in targetDirectories)
{
if (string.IsNullOrWhiteSpace(targetDir)) continue;
string cleanDir = Path.GetFullPath(targetDir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
try
{
bool ok = QueryDirectory(everythingHwnd, cleanDir, snapshot, timeoutMs);
if (ok)
{
anySuccess = true;
}
}
catch
{
// 個別パスのクエリ失敗時はスキップ
}
}
return anySuccess ? snapshot : null;
}
#endregion
#region □メソッド(Private)
/// <summary>
/// Everything IPC を用いて1つのディレクトリ配下のファイル・フォルダ一覧を取得し、スナップショットに格納します。
/// </summary>
private static bool QueryDirectory(IntPtr everythingHwnd, string targetDirectory, FastDirectorySnapshot snapshot, int timeoutMs)
{
bool success = false;
var resetEvent = new ManualResetEvent(false);
// STAスレッド上でメッセージ受信用 HwndSource を作成
var thread = new Thread(() =>
{
HwndSource? source = null;
try
{
var parameters = new HwndSourceParameters("GameLauncher_Everything_Receiver")
{
Width = 0,
Height = 0,
PositionX = -100,
PositionY = -100,
WindowStyle = 0x800000 // WS_BORDER (非表示)
};
source = new HwndSource(parameters);
source.AddHook((IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) =>
{
if (msg == WM_COPYDATA)
{
var cds = Marshal.PtrToStructure<COPYDATASTRUCT>(lParam);
if (cds.lpData != IntPtr.Zero && cds.cbData > 12)
{
ParseEverythingIpcList(cds.lpData, targetDirectory, snapshot);
success = true;
handled = true;
resetEvent.Set();
}
}
return IntPtr.Zero;
});
// Everything への検索文字列構築(指定パス配下の全エントリ)
string searchQuery = $"path:\"{targetDirectory}\"";
byte[] queryBytes = BuildQueryPayload(source.Handle, searchQuery);
GCHandle pinnedQuery = GCHandle.Alloc(queryBytes, GCHandleType.Pinned);
try
{
var cdsSend = new COPYDATASTRUCT
{
dwData = (IntPtr)EVERYTHING_IPC_COPYDATA_QUERYW,
cbData = queryBytes.Length,
lpData = pinnedQuery.AddrOfPinnedObject()
};
SendMessage(everythingHwnd, WM_COPYDATA, source.Handle, ref cdsSend);
// メッセージループを回して結果を待つ
var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < timeoutMs && !success)
{
while (PeekMessage(out var msg, IntPtr.Zero, 0, 0, PM_REMOVE))
{
TranslateMessage(ref msg);
DispatchMessage(ref msg);
}
Thread.Sleep(5);
}
}
finally
{
if (pinnedQuery.IsAllocated) pinnedQuery.Free();
}
}
catch
{
// クエリ処理中の例外
}
finally
{
source?.Dispose();
resetEvent.Set();
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
resetEvent.WaitOne(timeoutMs);
return success;
}
/// <summary>
/// Everything IPC 送信用クエリバイナリペイロードを構築します。
/// </summary>
private static byte[] BuildQueryPayload(IntPtr replyHwnd, string searchQuery)
{
var header = new EVERYTHING_IPC_QUERYW_HEADER
{
max_results = EVERYTHING_IPC_ALLRESULTS,
offset = 0,
reply_copydata_message = 0,
search_flags = 0,
reply_hwnd = replyHwnd
};
int headerSize = Marshal.SizeOf(typeof(EVERYTHING_IPC_QUERYW_HEADER));
byte[] queryStrBytes = Encoding.Unicode.GetBytes(searchQuery + "\0");
byte[] payload = new byte[headerSize + queryStrBytes.Length];
IntPtr headerPtr = Marshal.AllocHGlobal(headerSize);
try
{
Marshal.StructureToPtr(header, headerPtr, false);
Marshal.Copy(headerPtr, payload, 0, headerSize);
}
finally
{
Marshal.FreeHGlobal(headerPtr);
}
Buffer.BlockCopy(queryStrBytes, 0, payload, headerSize, queryStrBytes.Length);
return payload;
}
/// <summary>
/// Everything から返信された EVERYTHING_IPC_LISTW バイナリをパースし、スナップショットに登録します。
/// </summary>
private static void ParseEverythingIpcList(IntPtr pList, string targetDirectory, FastDirectorySnapshot snapshot)
{
int totitems = Marshal.ReadInt32(pList, 0);
int numitems = Marshal.ReadInt32(pList, 4);
int offset = Marshal.ReadInt32(pList, 8);
if (numitems <= 0) return;
int itemHeaderBase = 12; // sizeof(DWORD) * 3
int itemSize = 12; // sizeof(DWORD) * 3 (flags, filename_offset, path_offset)
for (int i = 0; i < numitems; i++)
{
int itemOffset = itemHeaderBase + (i * itemSize);
uint flags = (uint)Marshal.ReadInt32(pList, itemOffset);
int filenameOffset = Marshal.ReadInt32(pList, itemOffset + 4);
int pathOffset = Marshal.ReadInt32(pList, itemOffset + 8);
string filename = Marshal.PtrToStringUni(IntPtr.Add(pList, filenameOffset)) ?? string.Empty;
string dirPath = Marshal.PtrToStringUni(IntPtr.Add(pList, pathOffset)) ?? string.Empty;
bool isFolder = (flags & EVERYTHING_IPC_FOLDER) != 0 || (flags & EVERYTHING_IPC_DRIVE) != 0;
if (isFolder)
{
string fullSubDir = Path.Combine(dirPath, filename);
snapshot.AddDirectory(dirPath, fullSubDir);
}
else
{
snapshot.AddFile(dirPath, filename);
}
}
}
#endregion
#region □P/Invoke(Private)
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindowW(string lpClassName, string? lpWindowName);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
[DllImport("user32.dll")]
private static extern bool TranslateMessage([In] ref MSG lpMsg);
[DllImport("user32.dll")]
private static extern IntPtr DispatchMessage([In] ref MSG lpmsg);
#endregion
}
}
+211
View File
@@ -0,0 +1,211 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace GameLauncher.Services
{
/// <summary>
/// メモリ上に展開されたディレクトリおよびファイル構成の高速インメモリスナップショット
/// </summary>
public class FastDirectorySnapshot
{
#region □プロパティ(Public)
/// <summary>
/// ディレクトリパス -> 直下のファイル名(ファイル名のみ)のハッシュセット
/// </summary>
public Dictionary<string, HashSet<string>> FilesByDir { get; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// ディレクトリパス -> 直下のサブディレクトリのフルパスリスト
/// </summary>
public Dictionary<string, List<string>> SubDirsByDir { get; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// 登録されている総ディレクトリ数
/// </summary>
public int TotalDirectoryCount => this.SubDirsByDir.Count;
/// <summary>
/// 登録されている総ファイル数
/// </summary>
public int TotalFileCount => this.FilesByDir.Values.Sum(set => set.Count);
#endregion
#region □メソッド(Public)
/// <summary>
/// ファイルをスナップショットに登録します。
/// </summary>
public void AddFile(string dirPath, string fileName)
{
var normalizedDir = NormalizePath(dirPath);
if (!this.FilesByDir.TryGetValue(normalizedDir, out var files))
{
files = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
this.FilesByDir[normalizedDir] = files;
}
files.Add(fileName);
if (!this.SubDirsByDir.ContainsKey(normalizedDir))
{
this.SubDirsByDir[normalizedDir] = new List<string>();
}
}
/// <summary>
/// サブディレクトリを親ディレクトリのスナップショットに登録します。
/// </summary>
public void AddDirectory(string parentDirPath, string childDirPath)
{
var normalizedParent = NormalizePath(parentDirPath);
var normalizedChild = NormalizePath(childDirPath);
if (!this.SubDirsByDir.TryGetValue(normalizedParent, out var children))
{
children = new List<string>();
this.SubDirsByDir[normalizedParent] = children;
}
if (!children.Contains(normalizedChild, StringComparer.OrdinalIgnoreCase))
{
children.Add(normalizedChild);
}
if (!this.SubDirsByDir.ContainsKey(normalizedChild))
{
this.SubDirsByDir[normalizedChild] = new List<string>();
}
}
/// <summary>
/// 指定されたディレクトリが存在するかどうかをインメモリで判定します。
/// </summary>
public bool DirectoryExists(string dirPath)
{
var normalized = NormalizePath(dirPath);
return this.SubDirsByDir.ContainsKey(normalized) || this.FilesByDir.ContainsKey(normalized);
}
/// <summary>
/// 指定されたファイルが存在するかどうかをインメモリで判定します。
/// </summary>
public bool FileExists(string filePath)
{
var dir = NormalizePath(Path.GetDirectoryName(filePath) ?? string.Empty);
var name = Path.GetFileName(filePath);
if (this.FilesByDir.TryGetValue(dir, out var files))
{
return files.Contains(name);
}
return false;
}
/// <summary>
/// 指定されたディレクトリ直下のサブディレクトリ一覧を取得します。
/// </summary>
public string[] GetDirectories(string dirPath)
{
var normalized = NormalizePath(dirPath);
if (this.SubDirsByDir.TryGetValue(normalized, out var subDirs))
{
return subDirs.ToArray();
}
return Array.Empty<string>();
}
/// <summary>
/// 指定されたディレクトリ直下のファイルフルパス一覧を取得します。
/// </summary>
public string[] GetFiles(string dirPath, string searchPattern = "*")
{
var normalized = NormalizePath(dirPath);
if (!this.FilesByDir.TryGetValue(normalized, out var files))
{
return Array.Empty<string>();
}
if (string.IsNullOrEmpty(searchPattern) || searchPattern == "*")
{
return files.Select(f => Path.Combine(normalized, f)).ToArray();
}
if (searchPattern.StartsWith("*.") && searchPattern.IndexOf('*', 1) < 0 && searchPattern.IndexOf('?', 1) < 0)
{
string ext = searchPattern.Substring(1);
return files
.Where(f => f.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
.Select(f => Path.Combine(normalized, f))
.ToArray();
}
var regex = WildcardToRegex(searchPattern);
return files
.Where(f => regex.IsMatch(f))
.Select(f => Path.Combine(normalized, f))
.ToArray();
}
/// <summary>
/// 別のスナップショットの内容を現在のスナップショットにマージします。
/// </summary>
/// <param name="other">マージ元のスナップショット</param>
public void MergeFrom(FastDirectorySnapshot other)
{
if (other == null) return;
foreach (var kvp in other.FilesByDir)
{
if (!this.FilesByDir.TryGetValue(kvp.Key, out var files))
{
files = new HashSet<string>(kvp.Value, StringComparer.OrdinalIgnoreCase);
this.FilesByDir[kvp.Key] = files;
}
else
{
files.UnionWith(kvp.Value);
}
}
foreach (var kvp in other.SubDirsByDir)
{
if (!this.SubDirsByDir.TryGetValue(kvp.Key, out var subDirs))
{
subDirs = new List<string>(kvp.Value);
this.SubDirsByDir[kvp.Key] = subDirs;
}
else
{
foreach (var dir in kvp.Value)
{
if (!subDirs.Contains(dir, StringComparer.OrdinalIgnoreCase))
{
subDirs.Add(dir);
}
}
}
}
}
#endregion
#region □メソッド(Private)
/// <summary>
/// パス末尾の区切り文字を除去し、正規化します。
/// </summary>
private static string NormalizePath(string path)
{
if (string.IsNullOrEmpty(path)) return string.Empty;
return path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
/// <summary>
/// ワイルドカードパターンを正規表現に変換します。
/// </summary>
private static Regex WildcardToRegex(string pattern)
{
string escaped = Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".");
return new Regex("^" + escaped + "$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
#endregion
}
}
File diff suppressed because it is too large. Load diff
+399
View File
@@ -0,0 +1,399 @@
using System;
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace GameLauncher.Services
{
/// <summary>
/// NTFS の MFT (USN Journal: FSCTL_ENUM_USN_DATA) を直接読み取り、
/// ドライブ内のファイルおよびディレクトリツリーを爆速で一括抽出するサービス
/// </summary>
public class NtfsMftScanService
{
#region □定数(Private)
private const uint GENERIC_READ = 0x80000000;
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
private const uint OPEN_EXISTING = 3;
private const uint FSCTL_QUERY_USN_JOURNAL = 0x000900f4;
private const uint FSCTL_ENUM_USN_DATA = 0x000900b3;
private const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
/// <summary>
/// MFT読み込みバッファサイズ(2MB)。1回のDeviceIoControl呼び出しで最大効率を引き出します。
/// </summary>
private const int BufferSize = 2048 * 1024;
#endregion
#region □構造体(Private)
[StructLayout(LayoutKind.Sequential)]
private struct USN_JOURNAL_DATA
{
public ulong UsnJournalID;
public long FirstUsn;
public long NextUsn;
public long LowestValidUsn;
public long MaxUsn;
public ulong MaximumSize;
public ulong AllocationDelta;
}
[StructLayout(LayoutKind.Sequential)]
private struct MFT_ENUM_DATA_V0
{
public ulong StartFileReferenceNumber;
public long LowUsn;
public long HighUsn;
}
/// <summary>
/// MFTディレクトリ情報ノード
/// </summary>
private struct DirNode
{
public ulong Id;
public ulong ParentId;
public string Name;
}
#endregion
#region □メソッド(Public)
/// <summary>
/// 指定されたパス群(例: C:\..., Z:\...)に対して、NTFS MFT 直接読み取りを用いて高速スナップショットを生成します。
/// 複数ドライブが存在する場合は、各ドライブを並列処理してディスクアクセス速度を極限まで高めます。
/// </summary>
/// <param name="targetDirectories">走査対象のディレクトリルート一覧</param>
/// <returns>生成されたスナップショット。失敗または非NTFS時は null</returns>
public static FastDirectorySnapshot? TryScanTargetsFast(IEnumerable<string> targetDirectories)
{
var targetsByDrive = new Dictionary<char, List<string>>();
foreach (var dir in targetDirectories)
{
if (string.IsNullOrWhiteSpace(dir)) continue;
var full = Path.GetFullPath(dir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (full.Length >= 2 && full[1] == ':')
{
char driveLetter = char.ToUpperInvariant(full[0]);
if (!targetsByDrive.TryGetValue(driveLetter, out var list))
{
list = new List<string>();
targetsByDrive[driveLetter] = list;
}
list.Add(full);
}
}
if (targetsByDrive.Count == 0) return null;
var snapshots = new ConcurrentBag<FastDirectorySnapshot>();
// ドライブごとに並列処理を実行(物理/論理ドライブ間のI/OおよびCPUを限界まで同時並行化)
Parallel.ForEach(targetsByDrive, kvp =>
{
char driveLetter = kvp.Key;
var targetPaths = kvp.Value;
var driveSnapshot = new FastDirectorySnapshot();
try
{
bool ok = ScanVolumeMft(driveLetter, targetPaths, driveSnapshot);
if (ok && (driveSnapshot.TotalDirectoryCount > 0 || driveSnapshot.TotalFileCount > 0))
{
snapshots.Add(driveSnapshot);
}
}
catch
{
// ドライブスキャン失敗時はスキップ
}
});
if (snapshots.IsEmpty) return null;
var merged = new FastDirectorySnapshot();
foreach (var snap in snapshots)
{
merged.MergeFrom(snap);
}
return merged;
}
#endregion
#region □メソッド(Private)
/// <summary>
/// 1つのドライブボリュームのMFTを読み込み、指定されたターゲットパス配下のファイルをスナップショットに登録します。
/// </summary>
private static bool ScanVolumeMft(char driveLetter, List<string> targetPaths, FastDirectorySnapshot snapshot)
{
string volumePath = @"\\.\" + driveLetter + ":";
using var hVolume = CreateFile(
volumePath,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
IntPtr.Zero,
OPEN_EXISTING,
0,
IntPtr.Zero);
if (hVolume.IsInvalid)
{
return false;
}
// 1. USNジャーナル情報の取得
var journalData = new USN_JOURNAL_DATA();
int journalDataSize = Marshal.SizeOf(typeof(USN_JOURNAL_DATA));
if (!DeviceIoControl(hVolume, FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, out journalData, journalDataSize, out _, IntPtr.Zero))
{
return false;
}
// 2. MFT列挙用パラメータの準備
var enumData = new MFT_ENUM_DATA_V0
{
StartFileReferenceNumber = 0,
LowUsn = 0,
HighUsn = journalData.NextUsn
};
int enumDataSize = Marshal.SizeOf(typeof(MFT_ENUM_DATA_V0));
IntPtr enumDataPtr = Marshal.AllocHGlobal(enumDataSize);
Marshal.StructureToPtr(enumData, enumDataPtr, false);
byte[] buffer = new byte[BufferSize];
GCHandle bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr bufferPtr = bufferHandle.AddrOfPinnedObject();
// 読み込んだ全MFTデータチャンクを保持(I/Oを最優先で一括連続完了させる)
var chunks = new List<(byte[] Buffer, int Length)>();
try
{
while (DeviceIoControl(hVolume, FSCTL_ENUM_USN_DATA, enumDataPtr, enumDataSize, bufferPtr, BufferSize, out uint bytesReturned, IntPtr.Zero))
{
if (bytesReturned <= 8) break;
// 次の開始参照番号を取得
ulong nextId = (ulong)Marshal.ReadInt64(bufferPtr);
Marshal.WriteInt64(enumDataPtr, (long)nextId);
byte[] chunkCopy = new byte[bytesReturned];
Buffer.BlockCopy(buffer, 0, chunkCopy, 0, (int)bytesReturned);
chunks.Add((chunkCopy, (int)bytesReturned));
}
}
finally
{
if (bufferHandle.IsAllocated) bufferHandle.Free();
if (enumDataPtr != IntPtr.Zero) Marshal.FreeHGlobal(enumDataPtr);
}
if (chunks.Count == 0) return false;
// 3. 【第1パス】ディレクトリのみを収集(ディレクトリは全体の数%に過ぎないため極めて高速)
var dirNodes = new Dictionary<ulong, DirNode>(65536);
var childrenByParent = new Dictionary<ulong, List<ulong>>(65536);
foreach (var chunk in chunks)
{
ReadOnlySpan<byte> span = chunk.Buffer.AsSpan(0, chunk.Length);
int offset = 8;
while (offset < chunk.Length)
{
if (offset + 60 > chunk.Length) break;
ReadOnlySpan<byte> record = span.Slice(offset);
int recordLength = BinaryPrimitives.ReadInt32LittleEndian(record);
if (recordLength <= 0 || offset + recordLength > chunk.Length) break;
uint fileAttributes = BinaryPrimitives.ReadUInt32LittleEndian(record.Slice(52));
if ((fileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
ulong fileRef = BinaryPrimitives.ReadUInt64LittleEndian(record.Slice(8)) & 0x0000FFFFFFFFFFFFUL;
ulong parentRef = BinaryPrimitives.ReadUInt64LittleEndian(record.Slice(16)) & 0x0000FFFFFFFFFFFFUL;
ushort fileNameLength = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(56));
ushort fileNameOffset = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(58));
if (fileNameLength > 0 && fileNameOffset + fileNameLength <= recordLength)
{
string dirName = Encoding.Unicode.GetString(record.Slice(fileNameOffset, fileNameLength));
dirNodes[fileRef] = new DirNode { Id = fileRef, ParentId = parentRef, Name = dirName };
if (!childrenByParent.TryGetValue(parentRef, out var childList))
{
childList = new List<ulong>();
childrenByParent[parentRef] = childList;
}
childList.Add(fileRef);
}
}
offset += recordLength;
}
}
// 4. ターゲットパスのNodeId特定と、配下の子孫ディレクトリパスの確定
var targetDirIds = new HashSet<ulong>();
var dirIdToFullPath = new Dictionary<ulong, string>();
foreach (var targetPath in targetPaths)
{
ulong? targetNodeId = FindDirNodeIdByPath(driveLetter, targetPath, dirNodes, childrenByParent);
if (targetNodeId.HasValue)
{
CollectDescendantDirectories(targetNodeId.Value, targetPath, dirNodes, childrenByParent, targetDirIds, dirIdToFullPath, snapshot);
}
}
// 該当するターゲットディレクトリが存在しなければ終了
if (targetDirIds.Count == 0) return true;
// 5. 【第2パス】ターゲット配下のファイルのみを高速抽出
// (ターゲット外の数百万個の無関係なファイルは名前取得やオブジェクト生成を完全にスキップ!)
foreach (var chunk in chunks)
{
ReadOnlySpan<byte> span = chunk.Buffer.AsSpan(0, chunk.Length);
int offset = 8;
while (offset < chunk.Length)
{
if (offset + 60 > chunk.Length) break;
ReadOnlySpan<byte> record = span.Slice(offset);
int recordLength = BinaryPrimitives.ReadInt32LittleEndian(record);
if (recordLength <= 0 || offset + recordLength > chunk.Length) break;
uint fileAttributes = BinaryPrimitives.ReadUInt32LittleEndian(record.Slice(52));
// ディレクトリは第1パスですでに登録済みのためスキップ
if ((fileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
{
ulong parentRef = BinaryPrimitives.ReadUInt64LittleEndian(record.Slice(16)) & 0x0000FFFFFFFFFFFFUL;
// ターゲット配下のディレクトリに属するファイルのみを抽出
if (targetDirIds.Contains(parentRef) && dirIdToFullPath.TryGetValue(parentRef, out string? parentDirPath))
{
ushort fileNameLength = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(56));
ushort fileNameOffset = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(58));
if (fileNameLength > 0 && fileNameOffset + fileNameLength <= recordLength)
{
string fileName = Encoding.Unicode.GetString(record.Slice(fileNameOffset, fileNameLength));
snapshot.AddFile(parentDirPath, fileName);
}
}
}
offset += recordLength;
}
}
return true;
}
/// <summary>
/// パス文字列から対応するディレクトリのノードIDを特定します。
/// </summary>
private static ulong? FindDirNodeIdByPath(
char driveLetter,
string path,
Dictionary<ulong, DirNode> dirNodes,
Dictionary<ulong, List<ulong>> childrenByParent)
{
string rootStr = driveLetter + @":\";
if (path.Equals(rootStr.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase) || path.Equals(rootStr, StringComparison.OrdinalIgnoreCase))
{
return 5UL; // ルートディレクトリID
}
var parts = path.Substring(3).Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);
ulong currentParent = 5UL;
foreach (var part in parts)
{
bool found = false;
if (childrenByParent.TryGetValue(currentParent, out var childIds))
{
foreach (var childId in childIds)
{
if (dirNodes.TryGetValue(childId, out var node) && string.Equals(node.Name, part, StringComparison.OrdinalIgnoreCase))
{
currentParent = node.Id;
found = true;
break;
}
}
}
if (!found) return null;
}
return currentParent;
}
/// <summary>
/// ターゲットディレクトリ配下の子孫ディレクトリIDおよびフルパスを再帰的に収集し、スナップショットに登録します。
/// </summary>
private static void CollectDescendantDirectories(
ulong parentNodeId,
string currentPath,
Dictionary<ulong, DirNode> dirNodes,
Dictionary<ulong, List<ulong>> childrenByParent,
HashSet<ulong> targetDirIds,
Dictionary<ulong, string> dirIdToFullPath,
FastDirectorySnapshot snapshot)
{
targetDirIds.Add(parentNodeId);
dirIdToFullPath[parentNodeId] = currentPath;
if (!childrenByParent.TryGetValue(parentNodeId, out var childIds)) return;
foreach (var childId in childIds)
{
if (!dirNodes.TryGetValue(childId, out var childNode)) continue;
string childPath = Path.Combine(currentPath, childNode.Name);
snapshot.AddDirectory(currentPath, childPath);
CollectDescendantDirectories(childId, childPath, dirNodes, childrenByParent, targetDirIds, dirIdToFullPath, snapshot);
}
}
#endregion
#region □P/Invoke(Private)
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DeviceIoControl(
SafeFileHandle hDevice,
uint dwIoControlCode,
IntPtr lpInBuffer,
int nInBufferSize,
out USN_JOURNAL_DATA lpOutBuffer,
int nOutBufferSize,
out uint lpBytesReturned,
IntPtr lpOverlapped);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DeviceIoControl(
SafeFileHandle hDevice,
uint dwIoControlCode,
IntPtr lpInBuffer,
int nInBufferSize,
IntPtr lpOutBuffer,
int nOutBufferSize,
out uint lpBytesReturned,
IntPtr lpOverlapped);
#endregion
}
}
+20 -5
View File
@@ -1,8 +1,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using GameLauncher.Engines.Unity;
using GameLauncher.Models; using GameLauncher.Models;
using GameLauncher.Services.Codecs; using GameLauncher.Services.Codecs;
@@ -13,23 +14,32 @@ namespace GameLauncher.Services
/// </summary> /// </summary>
public class SaveDataCodecManager public class SaveDataCodecManager
{ {
/// <summary>
/// シングルトンインスタンスを取得します。
/// </summary>
public static readonly SaveDataCodecManager Instance = new(); public static readonly SaveDataCodecManager Instance = new();
private readonly List<ISaveDataCodec> _codecs = []; private readonly List<ISaveDataCodec> _codecs = [];
/// <summary>
/// <see cref="SaveDataCodecManager"/> クラスの新しいインスタンスを初期化します。
/// </summary>
public SaveDataCodecManager() public SaveDataCodecManager()
{ {
// コーデックの登録 // コーデックの登録
_codecs.Add(new EasySave3Codec()); this._codecs.Add(new EasySave3Codec());
_codecs.Add(new YurisSaveCodec()); this._codecs.Add(new YurisSaveCodec());
} }
/// <summary> /// <summary>
/// 指定されたゲームおよびセーブファイルに対応するコーデックを検索します。 /// 指定されたゲームおよびセーブファイルに対応するコーデックを検索します。
/// </summary> /// </summary>
/// <param name="game">対象のUnityゲーム情報</param>
/// <param name="file">対象のセーブファイル情報</param>
/// <returns>対応するコーデック。見つからない場合は null</returns>
public ISaveDataCodec? FindCodec(UnityGameItem game, SaveFileEntry file) public ISaveDataCodec? FindCodec(UnityGameItem game, SaveFileEntry file)
{ {
foreach (var codec in _codecs) foreach (var codec in this._codecs)
{ {
if (codec.CanHandle(game, file)) if (codec.CanHandle(game, file))
{ {
@@ -42,6 +52,9 @@ namespace GameLauncher.Services
/// <summary> /// <summary>
/// 未対応セーブデータについて、Antigravity IDE に依頼できる安全なプロンプトを自動生成します。 /// 未対応セーブデータについて、Antigravity IDE に依頼できる安全なプロンプトを自動生成します。
/// </summary> /// </summary>
/// <param name="game">対象のUnityゲーム情報</param>
/// <param name="file">対象のセーブファイル情報</param>
/// <returns>生成された依頼プロンプト文字列</returns>
public string GenerateAntigravityPrompt(UnityGameItem game, SaveFileEntry file) public string GenerateAntigravityPrompt(UnityGameItem game, SaveFileEntry file)
{ {
// ポリシー配慮: 会社名・タイトル名からセンシティブ表現を除去/安全な別名に変換 // ポリシー配慮: 会社名・タイトル名からセンシティブ表現を除去/安全な別名に変換
@@ -96,8 +109,10 @@ namespace GameLauncher.Services
} }
/// <summary> /// <summary>
/// AIプロンプト向けに文字列を安全・中立的な表現にサニタイズ /// AIプロンプト向けに文字列を安全・中立的な表現にサニタイズします。
/// </summary> /// </summary>
/// <param name="input">元の文字列</param>
/// <returns>サニタイズされた安全な文字列</returns>
private static string SanitizeForPrompt(string input) private static string SanitizeForPrompt(string input)
{ {
if (string.IsNullOrWhiteSpace(input)) return "Game"; if (string.IsNullOrWhiteSpace(input)) return "Game";
+160
View File
@@ -0,0 +1,160 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace GameLauncher.Services
{
/// <summary>
/// ツクールVX / VX Ace のゲームウィンドウを、ディスプレイに収まる最大の整数倍へ拡大する外部連携サービス。
/// ゲーム側は無改造のまま、ランチャーがゲームウィンドウを検出して Win32 API で拡大します。
/// 外部ツールパスが設定されている場合はそちらを優先起動します。
/// </summary>
public class WindowResizeService
{
#region Win32 API
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int nIndex);
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetWindowTextLength(IntPtr hWnd);
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private const uint SWP_NOZORDER = 0x0004;
private const uint SWP_NOACTIVATE = 0x0010;
#endregion
/// <summary>
/// ゲーム起動後にウィンドウ拡大を適用します。
/// 外部ツールパスが設定されていればそれを起動し、無ければ内蔵の Win32 API 方式で拡大します。
/// </summary>
/// <param name="process">起動済みのゲームプロセス</param>
/// <param name="externalToolPath">外部ツール(Sizer等)の実行ファイルパス。空なら内蔵方式。</param>
/// <returns>(成功可否, ログ用メッセージ)</returns>
public async Task<(bool Success, string Message)> ApplyResizeAsync(Process process, string? externalToolPath)
{
if (!string.IsNullOrEmpty(externalToolPath) && File.Exists(externalToolPath))
{
try
{
Process.Start(new ProcessStartInfo
{
FileName = externalToolPath,
UseShellExecute = true
});
return (true, $"外部ツールを起動しました: {Path.GetFileName(externalToolPath)}");
}
catch (Exception ex)
{
// 外部ツール起動失敗時は内蔵方式にフォールバック
var (ok, msg) = await this.ApplyBuiltInResizeAsync(process);
return (ok, $"外部ツール起動に失敗したため内蔵方式を使用: {ex.Message} / {msg}");
}
}
return await this.ApplyBuiltInResizeAsync(process);
}
/// <summary>
/// 内蔵の Win32 API 方式でゲームウィンドウを整数倍に拡大します。
/// </summary>
public async Task<(bool Success, string Message)> ApplyBuiltInResizeAsync(Process process)
{
try
{
IntPtr hWnd = IntPtr.Zero;
// ウィンドウが生成されるまで最大約5秒待機
for (int i = 0; i < 50; i++)
{
process.Refresh();
if (process.HasExited)
{
return (false, "ゲームプロセスが終了しました。");
}
if (process.MainWindowHandle != IntPtr.Zero)
{
hWnd = process.MainWindowHandle;
break;
}
// メインウィンドウが未確定な場合、可視ウィンドウをプロセスIDで探索
hWnd = FindWindowByProcessId((uint)process.Id);
if (hWnd != IntPtr.Zero) break;
await Task.Delay(100);
}
if (hWnd == IntPtr.Zero)
{
return (false, "ゲームウィンドウを検出できませんでした。");
}
int screenW = GetSystemMetrics(SM_CXSCREEN);
int screenH = GetSystemMetrics(SM_CYSCREEN);
// ゲームの既定ウィンドウサイズ(VX/VX Ace 標準)
int baseW = 544;
int baseH = 416;
int scale = Math.Min(screenW / baseW, screenH / baseH);
if (scale < 1) scale = 1;
int newW = baseW * scale;
int newH = baseH * scale;
bool moved = SetWindowPos(hWnd, IntPtr.Zero, 0, 0, newW, newH, SWP_NOZORDER | SWP_NOACTIVATE);
return moved
? (true, $"ウィンドウを {newW}x{newH} ({scale}x) に拡大しました。")
: (false, "ウィンドウサイズの変更に失敗しました。");
}
catch (Exception ex)
{
return (false, $"ウィンドウ拡大中にエラーが発生しました: {ex.Message}");
}
}
/// <summary>
/// 指定プロセスIDに属する可視トップレベルウィンドウを検索します。
/// </summary>
private static IntPtr FindWindowByProcessId(uint processId)
{
IntPtr result = IntPtr.Zero;
EnumWindows((hWnd, lParam) =>
{
GetWindowThreadProcessId(hWnd, out uint pid);
if (pid == processId && IsWindowVisible(hWnd) && GetWindowTextLength(hWnd) > 0)
{
result = hWnd;
return false; // 見つかったので列挙終了
}
return true;
}, IntPtr.Zero);
return result;
}
}
}
+322
View File
@@ -0,0 +1,322 @@
<Window x:Class="GameLauncher.WolfSaveEditorDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:GameLauncher"
mc:Ignorable="d"
Title="WOLF RPGエディター セーブデータエディタ" Height="750" Width="1100"
MinHeight="550" MinWidth="850"
WindowStartupLocation="CenterOwner"
Background="#181820" Foreground="#E0E0E6"
FontFamily="Segoe UI, Meiryo UI, Yu Gothic UI">
<Window.Resources>
<!-- カラーパレット -->
<SolidColorBrush x:Key="BgDark" Color="#181820"/>
<SolidColorBrush x:Key="CardBg" Color="#22222C"/>
<SolidColorBrush x:Key="CardHoverBg" Color="#2C2C3A"/>
<SolidColorBrush x:Key="SidePanelBg" Color="#1F1F2A"/>
<SolidColorBrush x:Key="BorderBrushColor" Color="#38384C"/>
<SolidColorBrush x:Key="TextPrimary" Color="#F2F2F7"/>
<SolidColorBrush x:Key="TextSecondary" Color="#9E9EB4"/>
<SolidColorBrush x:Key="AccentWolf" Color="#4834D4"/>
<SolidColorBrush x:Key="AccentWolfHover" Color="#686DE0"/>
<SolidColorBrush x:Key="AccentGreen" Color="#00B894"/>
<SolidColorBrush x:Key="AccentGreenHover" Color="#10D3AC"/>
<SolidColorBrush x:Key="AccentRed" Color="#D63031"/>
<!-- ボタン標準スタイル -->
<Style x:Key="ModernButton" TargetType="Button">
<Setter Property="Background" Value="#2E2E3E"/>
<Setter Property="Foreground" Value="#E0E0E6"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="#44445A"/>
<Setter Property="Padding" Value="12,6"/>
<Setter Property="FontSize" Value="12"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="6"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#3D3D52"/>
<Setter Property="BorderBrush" Value="{StaticResource AccentWolfHover}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.4"/>
<Setter Property="Cursor" Value="Arrow"/>
</Trigger>
</Style.Triggers>
</Style>
<!-- プライマリ(保存)ボタンスタイル -->
<Style x:Key="PrimaryButton" TargetType="Button" BasedOn="{StaticResource ModernButton}">
<Setter Property="Background" Value="{StaticResource AccentGreen}"/>
<Setter Property="BorderBrush" Value="{StaticResource AccentGreen}"/>
<Setter Property="Foreground" Value="#FFFFFF"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource AccentGreenHover}"/>
<Setter Property="BorderBrush" Value="{StaticResource AccentGreenHover}"/>
</Trigger>
</Style.Triggers>
</Style>
<!-- タブコントロールスタイル -->
<Style x:Key="ModernTabItem" TargetType="TabItem">
<Setter Property="Foreground" Value="{StaticResource TextSecondary}"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Padding" Value="16,8"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
<Border x:Name="TabBorder" Background="Transparent" BorderThickness="0,0,0,2" BorderBrush="Transparent" Padding="{TemplateBinding Padding}" Margin="0,0,8,0" Cursor="Hand">
<ContentPresenter ContentSource="Header"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="TabBorder" Property="BorderBrush" Value="{StaticResource AccentWolfHover}"/>
<Setter Property="Foreground" Value="#FFFFFF"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="#FFFFFF"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<!-- ヘッダーエリア -->
<RowDefinition Height="Auto"/>
<!-- 操作ツールバー -->
<RowDefinition Height="Auto"/>
<!-- メインコンテンツ -->
<RowDefinition Height="*"/>
<!-- ステータスバー -->
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- 1. ヘッダー -->
<Border Grid.Row="0" Background="{StaticResource SidePanelBg}" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="0,0,0,1" Padding="20,14">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<Border Background="{StaticResource AccentWolf}" CornerRadius="4" Padding="6,2" Margin="0,0,10,0">
<TextBlock Text="🐺 ウディタ" FontSize="11" FontWeight="Bold" Foreground="#FFFFFF"/>
</Border>
<TextBlock Text="セーブデータエディタ" FontSize="18" FontWeight="Bold" Foreground="{StaticResource TextPrimary}" VerticalAlignment="Center"/>
<TextBlock x:Name="lblGameTitle" Text="" FontSize="14" Foreground="{StaticResource TextSecondary}" Margin="12,0,0,0" VerticalAlignment="Center"/>
</StackPanel>
<TextBlock x:Name="lblGamePath" Text="" FontSize="11" Foreground="{StaticResource TextSecondary}" Margin="0,4,0,0" TextTrimming="CharacterEllipsis"/>
</StackPanel>
<!-- セーブスロット選択 -->
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="対象セーブ:" VerticalAlignment="Center" Margin="0,0,8,0" Foreground="{StaticResource TextSecondary}" FontSize="12"/>
<ComboBox x:Name="cboSaveFiles" Width="180" Height="28" VerticalContentAlignment="Center"
SelectionChanged="cboSaveFiles_SelectionChanged" Margin="0,0,8,0"/>
<Button Content="🔄 再読み込み" Style="{StaticResource ModernButton}" Click="btnReload_Click" Margin="0,0,8,0"/>
</StackPanel>
</Grid>
</Border>
<!-- 2. 操作ツールバー -->
<Border Grid.Row="1" Background="{StaticResource CardBg}" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="0,0,0,1" Padding="20,10">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!-- 数値ピンポイント検索(所持金・ステータス特定) -->
<StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center" Margin="0,0,16,0">
<TextBlock Text="🎯 数値検索 (所持金等):" VerticalAlignment="Center" Foreground="{StaticResource TextSecondary}" FontSize="12" Margin="0,0,6,0"/>
<TextBox x:Name="txtTargetValue" Width="110" Height="26" VerticalContentAlignment="Center" Padding="4,0"
Background="#14141C" Foreground="#FFFFFF" BorderBrush="{StaticResource BorderBrushColor}" Text=""/>
<Button Content="検索" Style="{StaticResource ModernButton}" Click="btnSearchValue_Click" Margin="6,0,4,0"/>
<Button Content="MAX(9999999)化" Style="{StaticResource ModernButton}" Click="btnSetMaxTarget_Click" Margin="0,0,4,0" ToolTip="検索された数値を 9,999,999 に書き換えます"/>
</StackPanel>
<!-- リアルタイムフィルター -->
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" Margin="0,0,16,0">
<TextBlock Text="🔍 絞り込み:" VerticalAlignment="Center" Foreground="{StaticResource TextSecondary}" FontSize="12" Margin="0,0,6,0"/>
<TextBox x:Name="txtFilter" Width="150" Height="26" VerticalContentAlignment="Center" Padding="4,0"
Background="#14141C" Foreground="#FFFFFF" BorderBrush="{StaticResource BorderBrushColor}"
TextChanged="txtFilter_TextChanged"/>
</StackPanel>
<!-- アクションボタン群 -->
<StackPanel Grid.Column="3" Orientation="Horizontal" VerticalAlignment="Center">
<Button Content="📤 JSONエクスポート" Style="{StaticResource ModernButton}" Click="btnExportJson_Click" Margin="0,0,8,0"/>
<Button Content="📥 JSONインポート" Style="{StaticResource ModernButton}" Click="btnImportJson_Click" Margin="0,0,8,0"/>
<Button Content="📁 バックアップを開く" Style="{StaticResource ModernButton}" Click="btnOpenBackups_Click" Margin="0,0,12,0"/>
<Button Content="💾 上書き保存 (自動バックアップ)" Style="{StaticResource PrimaryButton}" Click="btnSave_Click" Padding="16,6"/>
</StackPanel>
</Grid>
</Border>
<!-- 3. メインコンテンツ -->
<TabControl Grid.Row="2" Background="Transparent" BorderThickness="0" Margin="16,10,16,10">
<!-- 変数・数値データタブ -->
<TabItem Header="📊 通常変数・ステータス数値" Style="{StaticResource ModernTabItem}">
<DataGrid x:Name="dgVariables" AutoGenerateColumns="False" CanUserAddRows="False"
Background="{StaticResource CardBg}" BorderBrush="{StaticResource BorderBrushColor}"
RowBackground="#22222C" AlternatingRowBackground="#1D1D26"
Foreground="#FFFFFF" GridLinesVisibility="Horizontal" HorizontalGridLinesBrush="#333344"
HeadersVisibility="Column" SelectionMode="Single"
CellEditEnding="dgVariables_CellEditEnding">
<DataGrid.Resources>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#2A2A38"/>
<Setter Property="Foreground" Value="#E0E0E6"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Padding" Value="10,6"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrushColor}"/>
<Setter Property="BorderThickness" Value="0,0,1,1"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="分類" Binding="{Binding Category}" Width="120" IsReadOnly="True"/>
<DataGridTextColumn Header="項目名" Binding="{Binding DisplayName}" Width="180" IsReadOnly="True"/>
<DataGridTextColumn Header="オフセット" Binding="{Binding Offset, StringFormat=0x{0:X5}}" Width="110" IsReadOnly="True"/>
<DataGridTextColumn Header="現在の値 (ダブルクリックで編集)" Binding="{Binding Value, UpdateSourceTrigger=LostFocus}" Width="200">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="#55EFC4"/>
<Setter Property="Padding" Value="8,3"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTemplateColumn Header="クイック操作" Width="140">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="MAX(9999999)" Style="{StaticResource ModernButton}" Padding="8,2" FontSize="11"
Click="btnQuickMax_Click" Tag="{Binding}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</TabItem>
<!-- 文字列データタブ -->
<TabItem Header="💬 文字列データ" Style="{StaticResource ModernTabItem}">
<DataGrid x:Name="dgStrings" AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True"
Background="{StaticResource CardBg}" BorderBrush="{StaticResource BorderBrushColor}"
RowBackground="#22222C" AlternatingRowBackground="#1D1D26"
Foreground="#FFFFFF" GridLinesVisibility="Horizontal" HorizontalGridLinesBrush="#333344"
HeadersVisibility="Column" SelectionMode="Single">
<DataGrid.Resources>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#2A2A38"/>
<Setter Property="Foreground" Value="#E0E0E6"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Padding" Value="10,6"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrushColor}"/>
<Setter Property="BorderThickness" Value="0,0,1,1"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="オフセット" Binding="{Binding Offset, StringFormat=0x{0:X5}}" Width="120"/>
<DataGridTextColumn Header="バイト長" Binding="{Binding Length}" Width="90"/>
<DataGridTextColumn Header="文字列内容" Binding="{Binding Value}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
</TabItem>
<!-- セーブ詳細情報タブ -->
<TabItem Header="ℹ️ セーブ情報" Style="{StaticResource ModernTabItem}">
<Border Background="{StaticResource CardBg}" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="1" CornerRadius="8" Padding="20">
<StackPanel>
<TextBlock Text="セーブデータ詳細メタ情報" FontSize="14" FontWeight="Bold" Foreground="#FFFFFF" Margin="0,0,0,12"/>
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="ゲームタイトル:" Foreground="{StaticResource TextSecondary}"/>
<TextBlock x:Name="txtInfoTitle" Grid.Column="1" Foreground="#FFFFFF" FontWeight="SemiBold"/>
</Grid>
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="セーブバージョン:" Foreground="{StaticResource TextSecondary}"/>
<TextBlock x:Name="txtInfoVersion" Grid.Column="1" Foreground="#FFFFFF"/>
</Grid>
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="エンコーディング:" Foreground="{StaticResource TextSecondary}"/>
<TextBlock x:Name="txtInfoEncoding" Grid.Column="1" Foreground="#FFFFFF"/>
</Grid>
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="復号後データサイズ:" Foreground="{StaticResource TextSecondary}"/>
<TextBlock x:Name="txtInfoSize" Grid.Column="1" Foreground="#FFFFFF"/>
</Grid>
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="暗号化方式:" Foreground="{StaticResource TextSecondary}"/>
<TextBlock Text="WOLF RPG LCG XOR暗号化 (チェックサム自動計算対応)" Grid.Column="1" Foreground="#00B894"/>
</Grid>
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="バックアップ先:" Foreground="{StaticResource TextSecondary}"/>
<TextBlock x:Name="txtInfoBackupDir" Grid.Column="1" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap"/>
</Grid>
</StackPanel>
</Border>
</TabItem>
</TabControl>
<!-- 4. ステータスバー -->
<Border Grid.Row="3" Background="#14141C" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="0,1,0,0" Padding="16,8">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="lblStatus" Text="準備完了" Foreground="{StaticResource TextSecondary}" FontSize="12" VerticalAlignment="Center"/>
<TextBlock x:Name="lblSaveCount" Grid.Column="1" Text="" Foreground="{StaticResource TextSecondary}" FontSize="12" VerticalAlignment="Center"/>
</Grid>
</Border>
</Grid>
</Window>
+334
View File
@@ -0,0 +1,334 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using GameLauncher.Helpers;
using GameLauncher.Models;
using GameLauncher.Services;
using GameLauncher.Engines.Wolf;
using GameLauncher.Engines.Tkool;
namespace GameLauncher
{
/// <summary>
/// ウディタ用セーブデータエディタの画面ロジック
/// </summary>
public partial class WolfSaveEditorDialog : Window
{
private readonly TkoolGameItem _game;
private readonly WolfSaveService _saveService;
private WolfSaveData? _currentSaveData;
private List<WolfVariableItem> _allVariables = [];
private List<WolfStringItem> _allStrings = [];
public WolfSaveEditorDialog(TkoolGameItem game, WolfSaveService saveService)
{
this.InitializeComponent();
this._game = game;
this._saveService = saveService;
this.lblGameTitle.Text = this._game.Title;
this.lblGamePath.Text = this._game.RootDirectory;
this.txtInfoBackupDir.Text = AppPathHelper.GetGameBackupDirectory(this._game.FolderName, this._game.RootDirectory);
this.LoadSaveFileList();
}
/// <summary>
/// セーブファイル一覧の読み込みとコンボボックス設定
/// </summary>
private void LoadSaveFileList()
{
try
{
var files = this._saveService.GetSaveFiles(this._game.RootDirectory);
this.cboSaveFiles.Items.Clear();
foreach (var f in files)
{
this.cboSaveFiles.Items.Add(Path.GetFileName(f));
}
if (this.cboSaveFiles.Items.Count > 0)
{
this.cboSaveFiles.SelectedIndex = 0;
}
else
{
this.lblStatus.Text = "セーブデータ(*.sav)が見つかりませんでした。";
}
}
catch (Exception ex)
{
this.lblStatus.Text = $"セーブファイル列挙エラー: {ex.Message}";
}
}
private void cboSaveFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.cboSaveFiles.SelectedItem == null) return;
var fileName = this.cboSaveFiles.SelectedItem.ToString();
if (string.IsNullOrEmpty(fileName)) return;
this.LoadSaveFile(fileName);
}
/// <summary>
/// 指定されたセーブファイルの読み込み・解析
/// </summary>
private void LoadSaveFile(string fileName)
{
try
{
var files = this._saveService.GetSaveFiles(this._game.RootDirectory);
var fullPath = files.FirstOrDefault(f => string.Equals(Path.GetFileName(f), fileName, StringComparison.OrdinalIgnoreCase));
if (string.IsNullOrEmpty(fullPath) || !File.Exists(fullPath))
{
this.lblStatus.Text = $"ファイルが存在しません: {fileName}";
return;
}
this._currentSaveData = this._saveService.LoadSave(fullPath);
this._allVariables = [.. this._currentSaveData.Variables];
this._allStrings = [.. this._currentSaveData.Strings];
// メタ情報表示
this.txtInfoTitle.Text = string.IsNullOrEmpty(this._currentSaveData.GameTitle) ? "(不明)" : this._currentSaveData.GameTitle;
this.txtInfoVersion.Text = $"0x{this._currentSaveData.FileVersion:X4}";
this.txtInfoEncoding.Text = this._currentSaveData.IsUtf8 ? "UTF-8" : "Shift-JIS (CP932)";
this.txtInfoSize.Text = $"{this._currentSaveData.RawDecryptedBytes.Length:N0} バイト";
this.ApplyFilter();
this.lblStatus.Text = $"'{fileName}' を正常に読み込みました。";
this.lblSaveCount.Text = $"変数項目: {this._allVariables.Count}件, 文字列項目: {this._allStrings.Count}件";
}
catch (Exception ex)
{
MessageBox.Show($"セーブデータの読み込みに失敗しました:\n{ex.Message}", "読み込みエラー", MessageBoxButton.OK, MessageBoxImage.Error);
this.lblStatus.Text = $"読み込みエラー: {ex.Message}";
}
}
private void btnReload_Click(object sender, RoutedEventArgs e)
{
if (this.cboSaveFiles.SelectedItem != null)
{
this.LoadSaveFile(this.cboSaveFiles.SelectedItem.ToString()!);
}
else
{
this.LoadSaveFileList();
}
}
/// <summary>
/// フィルターの適用
/// </summary>
private void ApplyFilter()
{
var filter = this.txtFilter.Text?.Trim() ?? string.Empty;
if (string.IsNullOrEmpty(filter))
{
this.dgVariables.ItemsSource = this._allVariables;
this.dgStrings.ItemsSource = this._allStrings;
}
else
{
this.dgVariables.ItemsSource = this._allVariables
.Where(v => v.DisplayName.Contains(filter, StringComparison.OrdinalIgnoreCase) ||
v.Category.Contains(filter, StringComparison.OrdinalIgnoreCase) ||
v.Value.ToString().Contains(filter, StringComparison.OrdinalIgnoreCase) ||
v.Offset.ToString("X").Contains(filter, StringComparison.OrdinalIgnoreCase))
.ToList();
this.dgStrings.ItemsSource = this._allStrings
.Where(s => s.Value.Contains(filter, StringComparison.OrdinalIgnoreCase) ||
s.Offset.ToString("X").Contains(filter, StringComparison.OrdinalIgnoreCase))
.ToList();
}
}
private void txtFilter_TextChanged(object sender, TextChangedEventArgs e)
{
this.ApplyFilter();
}
/// <summary>
/// 数値ピンポイント検索(所持金・ステータス等)
/// </summary>
private void btnSearchValue_Click(object sender, RoutedEventArgs e)
{
if (!int.TryParse(this.txtTargetValue.Text.Trim(), out int target))
{
MessageBox.Show("検索する数値を半角数字で入力してください。(例: 現在の所持金やステータス)", "入力エラー", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
var matches = this._allVariables.Where(v => v.Value == target).ToList();
if (matches.Count == 0)
{
MessageBox.Show($"値が {target:N0} と一致する変数が見つかりませんでした。", "検索結果", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
this.dgVariables.ItemsSource = matches;
this.lblStatus.Text = $"値 {target:N0} に一致する候補が {matches.Count} 件見つかりました。";
}
/// <summary>
/// 検索された数値を一括で 9,999,999 に設定
/// </summary>
private void btnSetMaxTarget_Click(object sender, RoutedEventArgs e)
{
if (this.dgVariables.ItemsSource is not IEnumerable<WolfVariableItem> currentList) return;
var list = currentList.ToList();
if (list.Count == 0) return;
var result = MessageBox.Show(
$"現在一覧に表示されている {list.Count} 件の数値をすべて 9,999,999 に変更しますか?\n(所持金やステータスの一括MAX化に便利です)",
"一括変更の確認", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
foreach (var item in list)
{
item.Value = 9999999;
}
this.dgVariables.Items.Refresh();
this.lblStatus.Text = $"{list.Count} 件の値を 9,999,999 に変更しました。保存ボタンを押すと反映されます。";
}
}
/// <summary>
/// 単一行のクイックMAX化
/// </summary>
private void btnQuickMax_Click(object sender, RoutedEventArgs e)
{
if (sender is Button btn && btn.Tag is WolfVariableItem item)
{
item.Value = 9999999;
this.dgVariables.Items.Refresh();
this.lblStatus.Text = $"{item.DisplayName} の値を 9,999,999 に設定しました。";
}
}
private void dgVariables_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
this.lblStatus.Text = "値を編集しました。「上書き保存」を押すとバックアップを作成して保存されます。";
}
/// <summary>
/// セーブデータの上書き保存(Backupsへの完全自動退避付き)
/// </summary>
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (this._currentSaveData == null)
{
MessageBox.Show("保存対象のセーブデータがありません。", "エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
try
{
// 変数リストの最新値をモデルへ反映
this._currentSaveData.Variables = this._allVariables;
// 保存実行 (自動バックアップ)
string backupPath = this._saveService.SaveToFile(this._currentSaveData, this._game.FolderName, this._game.RootDirectory);
var msg = $"セーブデータ '{this._currentSaveData.FileName}' を安全に上書き保存しました!\n\n【バックアップ保存先】\n{backupPath}";
MessageBox.Show(msg, "保存完了", MessageBoxButton.OK, MessageBoxImage.Information);
this.lblStatus.Text = $"保存完了 (バックアップ: {Path.GetFileName(backupPath)})";
}
catch (Exception ex)
{
MessageBox.Show($"保存中にエラーが発生しました:\n{ex.Message}", "保存エラー", MessageBoxButton.OK, MessageBoxImage.Error);
this.lblStatus.Text = $"保存エラー: {ex.Message}";
}
}
/// <summary>
/// JSON エクスポート
/// </summary>
private void btnExportJson_Click(object sender, RoutedEventArgs e)
{
if (this._currentSaveData == null) return;
var sfd = new SaveFileDialog
{
Title = "セーブデータを JSON としてエクスポート",
Filter = "JSON ファイル (*.json)|*.json",
FileName = $"{Path.GetFileNameWithoutExtension(this._currentSaveData.FileName)}_export.json"
};
if (sfd.ShowDialog() == true)
{
try
{
this._saveService.ExportToJson(this._currentSaveData, sfd.FileName);
MessageBox.Show($"JSON ファイルをエクスポートしました:\n{sfd.FileName}", "エクスポート完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show($"エクスポートに失敗しました:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
/// <summary>
/// JSON インポート
/// </summary>
private void btnImportJson_Click(object sender, RoutedEventArgs e)
{
if (this._currentSaveData == null) return;
var ofd = new OpenFileDialog
{
Title = "編集済み JSON ファイルを選択してください",
Filter = "JSON ファイル (*.json)|*.json"
};
if (ofd.ShowDialog() == true)
{
try
{
this._saveService.ImportFromJson(this._currentSaveData, ofd.FileName);
this._allVariables = [.. this._currentSaveData.Variables];
this.ApplyFilter();
MessageBox.Show("JSON データを正常に取り込みました。「上書き保存」を押すとファイルへ反映されます。", "インポート完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show($"インポートに失敗しました:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
/// <summary>
/// バックアップフォルダを開く
/// </summary>
private void btnOpenBackups_Click(object sender, RoutedEventArgs e)
{
try
{
var dir = AppPathHelper.GetGameBackupDirectory(this._game.FolderName, this._game.RootDirectory);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
Process.Start(new ProcessStartInfo { FileName = dir, UseShellExecute = true });
}
catch (Exception ex)
{
MessageBox.Show($"バックアップフォルダを開けませんでした:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
}
}
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="GameLauncher.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- 常に管理者権限で実行する -->
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 / Windows 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
</windowsSettings>
</application>
</assembly>
+74
View File
@@ -0,0 +1,74 @@
/*:
* @target MZ
* @plugindesc プリンセスシナジー専用: 主人公のHPを常時最大に固定する
* @author GameLauncher
*
* @help
* プリンセスシナジー(RPGツクールMZ/カードバトル)専用プラグインです。
*
* 【分析結果】
* 本作の戦闘は標準の Game_BattlerBase / Game_Actor のHP APIを一切使わず、
* 独自のプレイヤー配列 NPlayer[] の _hp を直接書き換える実装になっています
* (JsScript100Set.js で NPlayer[0] = $gameActors._data[1] を参照)。
* ダメージは JsScript79Set.js:710 で NPlayer[0]._hp -= value と直接減算され、
* 描画は JsScript87Set.js で NPlayer[i]._hp を読みます。
* 戦闘の毎フレーム処理は Game_Interpreter.prototype.update
* (JsScript54Set.js:91)から呼ばれる NUpdate() が担っています。
*
* 【方式】
* 本プラグインは戦闘の毎フレーム入口 Game_Interpreter.prototype.update を
* フックし、主人公(NPlayer[0])の _hp を毎フレーム mhp へクランプします。
* どの経路で書き換えられても、描画前に必ず最大値へ戻ります。
*
* 【対象範囲】
* NPlayer[0](主人公ロマーシャ)のみ。敵(NEnemy)・他の味方(NPlayer[1]以降)
* には一切影響しません。
*
* 【適用/解除】
* ランチャーの改造チェック(PrincessAlwaysMaxHp)でこのプラグインの
* 適用/解除を切り替えられます(plugins.js への登録/解除)。
*/
(() => {
'use strict';
// 主人公(NPlayer[0])のHPを最大値へクランプする
function clampHeroHp() {
if (typeof NPlayer === 'undefined' || !NPlayer || !NPlayer[0]) return;
const hero = NPlayer[0];
const mhp = hero.mhp;
if (typeof mhp === 'number' && mhp > 0 && hero._hp !== mhp) {
hero._hp = mhp;
}
}
// 戦闘中、毎フレーム呼ばれる Game_Interpreter.update をフック
if (Game_Interpreter.prototype.update) {
const _Game_Interpreter_update = Game_Interpreter.prototype.update;
Game_Interpreter.prototype.update = function() {
const result = _Game_Interpreter_update.apply(this, arguments);
clampHeroHp();
return result;
};
}
// 毎フレームの戦闘更新(ダメージ等の直接書き換えを毎回打ち消す)
if (Game_Interpreter.prototype.DmgEffectUpdate) {
const _DmgEffectUpdate = Game_Interpreter.prototype.DmgEffectUpdate;
Game_Interpreter.prototype.DmgEffectUpdate = function() {
const result = _DmgEffectUpdate.apply(this, arguments);
clampHeroHp();
return result;
};
}
// プレイヤーターン開始時の保険
if (Game_Interpreter.prototype.BtlPLTurnSetup_Update) {
const _BtlPLTurnSetup_Update = Game_Interpreter.prototype.BtlPLTurnSetup_Update;
Game_Interpreter.prototype.BtlPLTurnSetup_Update = function() {
const result = _BtlPLTurnSetup_Update.apply(this, arguments);
clampHeroHp();
return result;
};
}
})();
+84
View File
@@ -0,0 +1,84 @@
/*:
* @target MZ
* @plugindesc プリンセスシナジー専用: 主人公のMPを常時最大に固定する
* @author GameLauncher
*
* @help
* プリンセスシナジー(RPGツクールMZ/カードバトル)専用プラグインです。
*
* 【分析結果】
* 本作の戦闘は標準の Game_BattlerBase / Game_Actor のMP APIを一切使わず、
* 独自のプレイヤー配列 NPlayer[] の _mp を直接書き換える実装になっています
* (JsScript100Set.js で NPlayer[0] = $gameActors._data[1] を参照)。
* カードコストは JsScript72Set.js:119 で NPlayer[0]._mp -= Cost と直接減算
* され、毎ターン減少や回復(上限9クランプ)も直接書き換えです。
* 戦闘の毎フレーム処理は Game_Interpreter.prototype.update
* (JsScript54Set.js:91)から呼ばれる NUpdate() が担っています。
*
* 【方式】
* 本プラグインは戦闘の毎フレーム入口 Game_Interpreter.prototype.update を
* フックし、主人公(NPlayer[0])の _mp を毎フレーム mmp へクランプします。
* どの経路で書き換えられても、描画前に必ず最大値へ戻ります。
*
* 【対象範囲】
* NPlayer[0](主人公ロマーシャ)のみ。敵(NEnemy)・他の味方(NPlayer[1]以降)
* には一切影響しません。
*
* 【適用/解除】
* ランチャーの改造チェック(PrincessAlwaysMaxMp)でこのプラグインの
* 適用/解除を切り替えられます(plugins.js への登録/解除)。
*/
(() => {
'use strict';
// 主人公(NPlayer[0])のMPを最大値へクランプする
function clampHeroMp() {
if (typeof NPlayer === 'undefined' || !NPlayer || !NPlayer[0]) return;
const hero = NPlayer[0];
const mmp = hero.mmp;
if (typeof mmp === 'number' && mmp > 0 && hero._mp !== mmp) {
hero._mp = mmp;
}
}
// 戦闘中、毎フレーム呼ばれる Game_Interpreter.update をフック
if (Game_Interpreter.prototype.update) {
const _Game_Interpreter_update = Game_Interpreter.prototype.update;
Game_Interpreter.prototype.update = function() {
const result = _Game_Interpreter_update.apply(this, arguments);
clampHeroMp();
return result;
};
}
// 毎フレームの戦闘更新(カードコスト等の直接書き換えを毎回打ち消す)
if (Game_Interpreter.prototype.DmgEffectUpdate) {
const _DmgEffectUpdate = Game_Interpreter.prototype.DmgEffectUpdate;
Game_Interpreter.prototype.DmgEffectUpdate = function() {
const result = _DmgEffectUpdate.apply(this, arguments);
clampHeroMp();
return result;
};
}
// プレイヤーターン開始時の保険
if (Game_Interpreter.prototype.BtlPLTurnSetup_Update) {
const _BtlPLTurnSetup_Update = Game_Interpreter.prototype.BtlPLTurnSetup_Update;
Game_Interpreter.prototype.BtlPLTurnSetup_Update = function() {
const result = _BtlPLTurnSetup_Update.apply(this, arguments);
clampHeroMp();
return result;
};
}
// 本作のMP回復は上限9でクランプされるため、回復後にも最大値へ戻す
if (Game_Interpreter.prototype.MPKaihuku) {
const _MPKaihuku = Game_Interpreter.prototype.MPKaihuku;
Game_Interpreter.prototype.MPKaihuku = function() {
const result = _MPKaihuku.apply(this, arguments);
clampHeroMp();
return result;
};
}
})();
+1 -2
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ * @target MZ
* @plugindesc 戦闘高速化・ウェイト削除・アニメーション早送り * @plugindesc 戦闘高速化・ウェイト削除・アニメーション早送り
* @author Antigravity * @author Antigravity
@@ -207,4 +207,3 @@
}; };
})(); })();
+1 -2
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ MV * @target MZ MV
* @plugindesc 戦闘ターン開始時およびコマンド選択時に味方全員のHPを全回復します。 * @plugindesc 戦闘ターン開始時およびコマンド選択時に味方全員のHPを全回復します。
* @author GameLauncher * @author GameLauncher
@@ -28,4 +28,3 @@
_BattleManager_startInput.call(this); _BattleManager_startInput.call(this);
}; };
})(); })();
+1 -2
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ MV * @target MZ MV
* @plugindesc 戦闘ターン開始時およびコマンド選択時に味方全員のMPを全回復します。 * @plugindesc 戦闘ターン開始時およびコマンド選択時に味方全員のMPを全回復します。
* @author GameLauncher * @author GameLauncher
@@ -28,4 +28,3 @@
_BattleManager_startInput.call(this); _BattleManager_startInput.call(this);
}; };
})(); })();
+1 -2
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ MV * @target MZ MV
* @plugindesc 戦闘ターン開始時およびコマンド選択時に味方全員のTPを全回復します。 * @plugindesc 戦闘ターン開始時およびコマンド選択時に味方全員のTPを全回復します。
* @author GameLauncher * @author GameLauncher
@@ -28,4 +28,3 @@
_BattleManager_startInput.call(this); _BattleManager_startInput.call(this);
}; };
})(); })();
+1 -1
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ MV * @target MZ MV
* @plugindesc マップ移動時のダッシュ速度を通常より大幅に高速化します。 * @plugindesc マップ移動時のダッシュ速度を通常より大幅に高速化します。
* @author GameLauncher * @author GameLauncher
+1 -1
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ MV * @target MZ MV
* @plugindesc 経験値を獲得した際、即座に最大レベル(99)まで成長させます。 * @plugindesc 経験値を獲得した際、即座に最大レベル(99)まで成長させます。
* @author GameLauncher * @author GameLauncher
+1 -1
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ MV * @target MZ MV
* @plugindesc お金(ゴールド)を入手した際、所持金を即座に最大値(9999999)にします。 * @plugindesc お金(ゴールド)を入手した際、所持金を即座に最大値(9999999)にします。
* @author GameLauncher * @author GameLauncher
+1 -1
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ MV * @target MZ MV
* @plugindesc アイテム・武器・防具を入手した際、自動的に所持数を最大値(99個)にします。 * @plugindesc アイテム・武器・防具を入手した際、自動的に所持数を最大値(99個)にします。
* @author GameLauncher * @author GameLauncher
+1 -1
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ MV * @target MZ MV
* @plugindesc 通常アイテム使用時の消費を無効化します(減らずに何度でも使用可能)。 * @plugindesc 通常アイテム使用時の消費を無効化します(減らずに何度でも使用可能)。
* @author GameLauncher * @author GameLauncher
+1 -1
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ MV * @target MZ MV
* @plugindesc メッセージを常に瞬間表示し、文章中のウェイトを無効化します。 * @plugindesc メッセージを常に瞬間表示し、文章中のウェイトを無効化します。
* @author GameLauncher * @author GameLauncher
+263
View File
@@ -0,0 +1,263 @@
/*:
* @target MZ MV
* @plugindesc 日本語・URLエンコード・文字化け・機種依存文字(丸数字等)の素材読み込み失敗を自動修復・救済します。
* @author GameLauncher
*
* @help
* 日本語ファイル名がURLエンコード(%E3%...)されたり、ファイル名と要求パスが
* 一致せず「Loading Error Failed to load」で停止してしまう現象を自動的に修復・救済します。
* 丸数字(①②...)と通常数字(1, 2...)の表記揺れやNW.jsのファイルシステム探索に対応しています。
*/
(() => {
'use strict';
const hasNode = typeof require === 'function' && typeof process === 'object';
const fs = hasNode ? require('fs') : null;
const path = hasNode ? require('path') : null;
// 1x1 透明 PNG (Data URL) - 万が一ファイルが見つからない場合のフォールバック用
const BLANK_PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
// 丸数字・ローマ数字・全角数字のマッピングテーブル
const CIRCLE_NUMBERS = ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩', '⑪', '⑫', '⑬', '⑭', '⑮', '⑯', '⑰', '⑱', '⑲', '⑳'];
/**
* 文字列内の丸数字や全角数字、波ダッシュ等を正規化して比較用キーを生成します。
* @param {string} str - 対象文字列
* @returns {string} 正規化文字列
*/
function normalizeFuzzy(str) {
if (!str) return '';
let res = str.normalize('NFC').toLowerCase();
// 丸数字 -> 通常数字
for (let i = 0; i < CIRCLE_NUMBERS.length; i++) {
res = res.replaceAll(CIRCLE_NUMBERS[i], String(i + 1));
}
// 全角数字 -> 半角数字
res = res.replace(/[0-9]/g, s => String.fromCharCode(s.charCodeAt(0) - 0xFEE0));
// 波ダッシュ・チルダ
res = res.replaceAll('\u301C', '\uFF5E');
// 全角カッコ -> 半角カッコ
res = res.replaceAll('(', '(').replaceAll(')', ')');
return res;
}
/**
* URLからファイルシステム上の実ファイルを探索します。
* @param {string} url - 読み込み対象のURL/相対パス
* @returns {string|null} 実ファイルの絶対パスまたは相対パス(見つからない場合はnull)
*/
function findActualFile(url) {
if (!fs || !path || !url) return null;
// クエリパラメータやハッシュを除去
const cleanUrl = url.split('?')[0].split('#')[0];
let decodedUrl = cleanUrl;
try {
decodedUrl = decodeURIComponent(cleanUrl);
} catch (e) { }
// 中途半端に % が残っている場合の再デコード
if (decodedUrl.includes('%')) {
try {
decodedUrl = decodedUrl.replace(/(%[0-9A-Fa-f]{2})+/g, match => {
try { return decodeURIComponent(match); } catch (e) { return match; }
});
} catch (e) { }
}
let encodedUrl = cleanUrl;
try {
const parts = cleanUrl.split('/');
encodedUrl = parts.map(p => encodeURIComponent(decodeURIComponent(p))).join('/');
} catch (e) { }
// 1. そのままのパスで存在するか
if (fs.existsSync(cleanUrl)) return cleanUrl;
// 2. URLデコードしたパスで存在するか
if (fs.existsSync(decodedUrl)) return decodedUrl;
// 3. URLエンコードしたパスで存在するか
if (fs.existsSync(encodedUrl)) return encodedUrl;
// 4. ディレクトリ内の実ファイルを走査して柔軟に検索(丸数字・表記揺れ対応)
try {
const dir = path.dirname(decodedUrl);
const targetBase = path.basename(decodedUrl);
const targetExt = path.extname(decodedUrl);
const targetNameWithoutExt = path.basename(decodedUrl, targetExt);
if (fs.existsSync(dir)) {
const files = fs.readdirSync(dir);
const fuzzyTarget = normalizeFuzzy(targetBase);
const fuzzyTargetWithoutExt = normalizeFuzzy(targetNameWithoutExt);
for (const file of files) {
const fileExt = path.extname(file);
const fileNameWithoutExt = path.basename(file, fileExt);
// A. 通常比較
if (file.toLowerCase() === targetBase.toLowerCase()) {
return path.join(dir, file);
}
// B. 表記揺れ(丸数字①⇔1、全角数字等)のファジーマッチ
const fuzzyFile = normalizeFuzzy(file);
const fuzzyFileWithoutExt = normalizeFuzzy(fileNameWithoutExt);
if (fuzzyFile === fuzzyTarget) {
return path.join(dir, file);
}
if (fuzzyFileWithoutExt === fuzzyTargetWithoutExt && fileExt.toLowerCase() === targetExt.toLowerCase()) {
return path.join(dir, file);
}
// C. URLエンコード/デコードされたファイル名との比較
try {
const decodedFile = decodeURIComponent(file);
if (normalizeFuzzy(decodedFile) === fuzzyTarget) {
return path.join(dir, file);
}
} catch (e) { }
}
}
} catch (e) { }
return null;
}
/**
* 実ファイルをBase64 DataURLとして読み込みます。
* @param {string} filePath - 実ファイルのパス
* @param {string} mimeType - MIMEタイプ
* @returns {string|null} DataURL
*/
function readFileAsDataUrl(filePath, mimeType = 'image/png') {
if (!fs || !filePath) return null;
try {
const buf = fs.readFileSync(filePath);
return `data:${mimeType};base64,${buf.toString('base64')}`;
} catch (e) {
return null;
}
}
// =========================================================================
// 1. Bitmap ロードの救済 (ツクールMV / MZ)
// =========================================================================
if (typeof Bitmap !== 'undefined') {
const _Bitmap_load = Bitmap.load;
Bitmap.load = function(url) {
if (fs && url) {
const actual = findActualFile(url);
if (actual && actual !== url) {
try {
const actualUrl = actual.replace(/\\/g, '/');
return _Bitmap_load.call(this, actualUrl);
} catch (e) { }
}
}
return _Bitmap_load.call(this, url);
};
const _Bitmap_prototype_onError = Bitmap.prototype._onError;
Bitmap.prototype._onError = function() {
if (!this._recoveryAttempted && this._url) {
this._recoveryAttempted = true;
const actualFile = findActualFile(this._url);
if (actualFile) {
const dataUrl = readFileAsDataUrl(actualFile, 'image/png');
if (dataUrl && this._image) {
console.log(`[GameLauncher] 画像の実ファイルを特定して自動救済: ${this._url} -> ${actualFile}`);
this._isLoading = true;
this._hasError = false;
this._image.src = dataUrl;
return;
}
}
// URLデコード版を直接 image.src に設定してリトライ
try {
const decoded = decodeURIComponent(this._url);
if (decoded !== this._url && this._image) {
this._isLoading = true;
this._hasError = false;
this._url = decoded;
this._image.src = decoded;
return;
}
} catch (e) { }
// 最終手段: ゲーム停止・クラッシュを回避するため透明PNGで代替
if (this._image) {
console.warn(`[GameLauncher] 未存在画像の透過代替を適用(エラー停止回避): ${this._url}`);
this._isLoading = false;
this._hasError = false;
this._image.src = BLANK_PNG;
if (typeof this._onLoad === 'function') {
try { this._onLoad(); } catch (e) { }
}
return;
}
}
_Bitmap_prototype_onError.call(this);
};
}
// =========================================================================
// 2. WebAudio / AudioManager ロードの救済 (ツクールMV / MZ)
// =========================================================================
if (typeof WebAudio !== 'undefined') {
const _WebAudio_prototype_load = WebAudio.prototype._load;
WebAudio.prototype._load = function(url) {
let targetUrl = url;
if (fs && url) {
const actual = findActualFile(url);
if (actual) {
targetUrl = actual.replace(/\\/g, '/');
}
}
return _WebAudio_prototype_load.call(this, targetUrl);
};
}
// =========================================================================
// 3. Graphics.printLoadingError のエラー停止緩和
// =========================================================================
if (typeof Graphics !== 'undefined' && Graphics.printLoadingError) {
const _Graphics_printLoadingError = Graphics.printLoadingError;
Graphics.printLoadingError = function(url) {
console.warn(`[GameLauncher] Loading Error が検出されました: ${url}`);
_Graphics_printLoadingError.call(this, url);
};
}
// =========================================================================
// 4. PluginManager スクリプト読み込みの救済
// =========================================================================
if (typeof PluginManager !== 'undefined' && PluginManager.loadScript) {
const _PluginManager_loadScript = PluginManager.loadScript;
PluginManager.loadScript = function(name) {
if (fs && name) {
const target = 'js/plugins/' + name;
const actual = findActualFile(target);
if (actual) {
const baseName = path.basename(actual);
return _PluginManager_loadScript.call(this, baseName);
}
}
return _PluginManager_loadScript.call(this, name);
};
}
console.log('[GameLauncher] ResourceLoaderFix プラグインが正常にロードされました。');
})();
+1 -1
View File
@@ -1,4 +1,4 @@
/*: /*:
* @target MZ MV * @target MZ MV
* @plugindesc ショップでのアイテム購入時、個数入力の初期値を最大購入可能数にします。 * @plugindesc ショップでのアイテム購入時、個数入力の初期値を最大購入可能数にします。
* @author GameLauncher * @author GameLauncher
-5
View File
@@ -1,5 +0,0 @@
@echo off
chcp 65001 > nul
echo === GameLauncher 発行処理を開始します ===
powershell -ExecutionPolicy Bypass -File "%~dp0publish.ps1"
pause
+28 -5
View File
@@ -1,20 +1,20 @@
# GameLauncher 単一ファイル発行スクリプト # GameLauncher 単一ファイル発行スクリプト
# 公開先: Z:\自作ソフト\GameLauncher\ # 公開先: Z:\自作ソフト\GameLauncher\
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$projectDir = $PSScriptRoot $projectDir = $PSScriptRoot
$publishDir = 'Z:\自作ソフト\GameLauncher' $publishDir = "Z:\自作ソフト\GameLauncher"
Write-Host '=== GameLauncher 発行処理開始 ===' -ForegroundColor Cyan Write-Host "=== GameLauncher 発行処理開始 (発行先: $publishDir) ===" -ForegroundColor Cyan
if (!(Test-Path $publishDir)) { if (!(Test-Path $publishDir)) {
New-Item -ItemType Directory -Path $publishDir -Force | Out-Null New-Item -ItemType Directory -Path $publishDir -Force | Out-Null
} }
Write-Host 'プロジェクトのビルドおよび単一ファイル発行中...' -ForegroundColor Yellow Write-Host "プロジェクトのビルドおよび単一ファイル発行中..." -ForegroundColor Yellow
dotnet publish "$projectDir\GameLauncher.csproj" -c Release -r win-x64 --self-contained false -o $publishDir dotnet publish "$projectDir\GameLauncher.csproj" -c Release -r win-x64 --self-contained false -p:PublishSingleFile=true -o "$publishDir"
if ($LASTEXITCODE -eq 0) { if ($LASTEXITCODE -eq 0) {
# プラグインおよび設定ファイルの配置 # プラグインおよび設定ファイルの配置
@@ -27,6 +27,29 @@ if ($LASTEXITCODE -eq 0) {
if (Test-Path "$projectDir\Config.tjs") { if (Test-Path "$projectDir\Config.tjs") {
Copy-Item -Path "$projectDir\Config.tjs" -Destination "$publishDir\Config.tjs" -Force Copy-Item -Path "$projectDir\Config.tjs" -Destination "$publishDir\Config.tjs" -Force
} }
# エンジン別の外部ツール(Engines\<Engine>\Tools 配下)を配置する。
# 各エンジンは自身のツールフォルダのみを参照するため、エンジン間で干渉しない。
$enginesRoot = Join-Path $projectDir "Engines"
if (Test-Path $enginesRoot) {
foreach ($engineDir in Get-ChildItem -Path $enginesRoot -Directory) {
$srcTools = Join-Path $engineDir.FullName "Tools"
if (Test-Path $srcTools) {
$dstTools = Join-Path (Join-Path $publishDir "Engines") (Join-Path $engineDir.Name "Tools")
if (!(Test-Path $dstTools)) {
New-Item -ItemType Directory -Path $dstTools -Force | Out-Null
}
robocopy $srcTools $dstTools /E /NP /R:1 /W:1 | Out-Null
}
}
}
# Enigma Virtual Box (EVB) 用の解凍ツール(evbunpack.exe)はリポジトリ同梱(自動取得は行わない)。
# 未配置の場合は警告のみ出し、Evb エンジンは解凍をスキップして起動対応に留める。
$evbToolDir = Join-Path (Join-Path $publishDir "Engines") "Evb\Tools\evbunpack"
if (!(Test-Path "$evbToolDir\evbunpack.exe")) {
Write-Host "警告: EVB 解凍ツールが見つかりません: $evbToolDir\evbunpack.exe" -ForegroundColor Yellow
Write-Host " Engines\Evb\Tools\evbunpack\README.md の手順で evbunpack.exe を配置してください。" -ForegroundColor Yellow
}
Write-Host "発行成功: $publishDir\GameLauncher.exe" -ForegroundColor Green Write-Host "発行成功: $publishDir\GameLauncher.exe" -ForegroundColor Green
} else { } else {
Write-Host "発行失敗 (終了コード: $LASTEXITCODE)" -ForegroundColor Red Write-Host "発行失敗 (終了コード: $LASTEXITCODE)" -ForegroundColor Red