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/ の再帰配置に対応
This commit is contained in:
armonica committed 2026-10-07 02:30:49 +09:00
1 parent 0d11039ee9
commit 8cea2a147d
47 files changed
+2976 -176

No files matched your search

+193
View File
@@ -0,0 +1,193 @@
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 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;
}
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)
{
// 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;
}
var packageJson = Path.Combine(gameDirectory, "package.json");
if (File.Exists(packageJson) && Directory.Exists(Path.Combine(gameDirectory, "nwjs")))
{
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);
}
}
+610
View File
@@ -0,0 +1,610 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using GameLauncher.Models;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Unity;
namespace GameLauncher.Engines.Nwjs
{
/// <summary>
/// ASAR アーカイブ内のファイルエントリ情報
/// </summary>
public class AsarFileEntry
{
public string RelativePath { get; set; } = string.Empty;
public long Offset { get; set; }
public long Size { get; set; }
}
/// <summary>
/// ASAR の解析結果情報
/// </summary>
public class AsarInspectResult
{
public bool IsValid { get; set; }
public bool IsTkoolGame { get; set; }
public bool IsTyranoGame { get; set; }
public TkoolEngineType EngineType { get; set; } = TkoolEngineType.Unknown;
public string Title { get; set; } = string.Empty;
public string? RelativePluginsJsPath { get; set; }
public string? RelativeIndexPath { get; set; }
public long TotalFilesCount { get; set; }
public long TotalUnpackedBytes { get; set; }
public List<AsarFileEntry> FileEntries { get; set; } = [];
}
/// <summary>
/// Electron 等で利用される app.asar 形式アーカイブの解析・解凍・復元を
/// 外部ツール不要かつ純粋な C# のみで安全・高速に行うサービス
/// </summary>
public class AsarArchiveService
{
/// <summary>ASARバックアップファイルの拡張子</summary>
public const string AsarBackupSuffix = ".original_launcher_backup";
/// <summary>
/// 指定されたゲームフォルダ配下に app.asar または解凍済みバックアップが存在するか検索します。
/// </summary>
/// <param name="gameRootDir">ゲームのルートディレクトリ</param>
/// <param name="asarPath">見つかった asar ファイルパス(または元の asar パス)</param>
/// <param name="isExtracted">現在解凍済み状態かどうか</param>
/// <returns>ASARパッケージが存在するかどうか</returns>
public static bool FindAsarPackage(string gameRootDir, out string? asarPath, out bool isExtracted, out string? extractedDirPath)
{
asarPath = null;
isExtracted = false;
extractedDirPath = null;
if (string.IsNullOrEmpty(gameRootDir) || !Directory.Exists(gameRootDir))
{
return false;
}
// 検索候補パス: resources\app.asar または 直下の app.asar
var candidate1 = Path.Combine(gameRootDir, "resources", "app.asar");
var candidate2 = Path.Combine(gameRootDir, "app.asar");
// 1. 未解凍の app.asar が存在する場合
if (File.Exists(candidate1))
{
asarPath = candidate1;
extractedDirPath = Path.Combine(gameRootDir, "resources", "app");
isExtracted = Directory.Exists(extractedDirPath) && File.Exists(Path.Combine(extractedDirPath, "package.json"));
return true;
}
if (File.Exists(candidate2))
{
asarPath = candidate2;
extractedDirPath = Path.Combine(gameRootDir, "app");
isExtracted = Directory.Exists(extractedDirPath) && File.Exists(Path.Combine(extractedDirPath, "package.json"));
return true;
}
// 2. 既に解凍済みで、app.asar がリネームバックアップされている場合
var backup1 = candidate1 + AsarBackupSuffix;
var appDir1 = Path.Combine(gameRootDir, "resources", "app");
if (File.Exists(backup1) && Directory.Exists(appDir1))
{
asarPath = candidate1;
extractedDirPath = appDir1;
isExtracted = true;
return true;
}
var backup2 = candidate2 + AsarBackupSuffix;
var appDir2 = Path.Combine(gameRootDir, "app");
if (File.Exists(backup2) && Directory.Exists(appDir2))
{
asarPath = candidate2;
extractedDirPath = appDir2;
isExtracted = true;
return true;
}
return false;
}
/// <summary>
/// ASAR ファイルのヘッダを解析し、ツクールゲームであるかの判定やタイトル・plugins.js位置を抽出します。
/// </summary>
/// <param name="asarFilePath">app.asar ファイルの物理パス(またはバックアップパス)</param>
/// <param name="includeFileList">全ファイルエントリの収集を行うかどうか(解凍時用)</param>
public AsarInspectResult InspectAsar(string asarFilePath, bool includeFileList = false)
{
var result = new AsarInspectResult();
// バックアップファイルが指定された場合も対応
var targetFile = asarFilePath;
if (!File.Exists(ToExtendedPath(targetFile)) && File.Exists(ToExtendedPath(targetFile + AsarBackupSuffix)))
{
targetFile = asarFilePath + AsarBackupSuffix;
}
if (!File.Exists(ToExtendedPath(targetFile)))
{
return result;
}
try
{
using var fs = new FileStream(ToExtendedPath(targetFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var br = new BinaryReader(fs);
if (fs.Length < 16) return result;
uint u1 = br.ReadUInt32();
uint headerSize = br.ReadUInt32();
uint u3 = br.ReadUInt32();
uint jsonSize = br.ReadUInt32();
// 妥当性チェック
if (u1 != 4 || jsonSize == 0 || jsonSize > 100_000_000 || jsonSize > fs.Length)
{
return result;
}
long dataOffset = 8 + (long)headerSize;
byte[] jsonBytes = br.ReadBytes((int)jsonSize);
string jsonStr = Encoding.UTF8.GetString(jsonBytes);
using var doc = JsonDocument.Parse(jsonStr);
if (!doc.RootElement.TryGetProperty("files", out var filesRoot))
{
return result;
}
result.IsValid = true;
// ツクール特有ファイルを探す
string? systemJsonRelative = null;
long systemJsonOffset = -1;
long systemJsonSize = -1;
string? packageJsonRelative = null;
long packageJsonOffset = -1;
long packageJsonSize = -1;
TraverseFiles(filesRoot, "", dataOffset, fs.Length, result, includeFileList,
ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize,
ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize);
if (!string.IsNullOrEmpty(result.RelativePluginsJsPath))
{
result.IsTkoolGame = true;
}
else if (result.IsTyranoGame)
{
result.EngineType = TkoolEngineType.Tyrano;
result.RelativePluginsJsPath = result.RelativeIndexPath ?? "index.html";
}
// タイトルの抽出(System.json または package.json から)
if (systemJsonOffset >= 0 && systemJsonSize > 0 && systemJsonSize < 5_000_000)
{
try
{
fs.Seek(dataOffset + systemJsonOffset, SeekOrigin.Begin);
byte[] sBytes = new byte[systemJsonSize];
fs.ReadExactly(sBytes, 0, (int)systemJsonSize);
string sJson = Encoding.UTF8.GetString(sBytes);
var match = Regex.Match(sJson, @"""gameTitle""\s*:\s*""([^""]+)""");
if (match.Success && !string.IsNullOrWhiteSpace(match.Groups[1].Value))
{
result.Title = match.Groups[1].Value.Trim();
}
}
catch { }
}
if (string.IsNullOrEmpty(result.Title) && packageJsonOffset >= 0 && packageJsonSize > 0 && packageJsonSize < 5_000_000)
{
try
{
fs.Seek(dataOffset + packageJsonOffset, SeekOrigin.Begin);
byte[] pBytes = new byte[packageJsonSize];
fs.ReadExactly(pBytes, 0, (int)packageJsonSize);
string pJson = Encoding.UTF8.GetString(pBytes);
var matchTitle = Regex.Match(pJson, @"""title""\s*:\s*""([^""]+)""");
if (matchTitle.Success && !string.IsNullOrWhiteSpace(matchTitle.Groups[1].Value) &&
!matchTitle.Groups[1].Value.Contains("ティラノスタジオ", StringComparison.OrdinalIgnoreCase))
{
result.Title = matchTitle.Groups[1].Value.Trim();
}
else
{
var matchDesc = Regex.Match(pJson, @"""description""\s*:\s*""([^""]+)""");
if (matchDesc.Success && !string.IsNullOrWhiteSpace(matchDesc.Groups[1].Value) &&
!matchDesc.Groups[1].Value.Contains("Electron for RPG", StringComparison.OrdinalIgnoreCase) &&
!matchDesc.Groups[1].Value.Contains("TyranoScript", StringComparison.OrdinalIgnoreCase) &&
!matchDesc.Groups[1].Value.Contains("ティラノスクリプト", StringComparison.OrdinalIgnoreCase))
{
result.Title = matchDesc.Groups[1].Value.Trim();
}
else
{
var matchName = Regex.Match(pJson, @"""name""\s*:\s*""([^""]+)""");
if (matchName.Success && !string.IsNullOrWhiteSpace(matchName.Groups[1].Value) &&
!matchName.Groups[1].Value.Equals("aigisfull", StringComparison.OrdinalIgnoreCase) &&
!matchName.Groups[1].Value.Contains("tyrano", StringComparison.OrdinalIgnoreCase))
{
result.Title = matchName.Groups[1].Value.Trim();
}
}
}
}
catch { }
}
}
catch
{
// 解析失敗時は無効
result.IsValid = false;
}
return result;
}
private void TraverseFiles(
JsonElement element,
string currentPath,
long dataOffset,
long fileLength,
AsarInspectResult result,
bool includeFileList,
ref string? systemJsonRelative,
ref long systemJsonOffset,
ref long systemJsonSize,
ref string? packageJsonRelative,
ref long packageJsonOffset,
ref long packageJsonSize)
{
if (element.ValueKind != JsonValueKind.Object) return;
foreach (var prop in element.EnumerateObject())
{
string name = prop.Name;
string path = string.IsNullOrEmpty(currentPath) ? name : $"{currentPath}/{name}";
var val = prop.Value;
if (val.TryGetProperty("files", out var subFiles))
{
TraverseFiles(subFiles, path, dataOffset, fileLength, result, includeFileList,
ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize,
ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize);
}
else
{
// ファイルエントリ
long offset = 0;
if (val.TryGetProperty("offset", out var offProp))
{
if (offProp.ValueKind == JsonValueKind.String && long.TryParse(offProp.GetString(), out var o))
offset = o;
else if (offProp.ValueKind == JsonValueKind.Number && offProp.TryGetInt64(out var oNum))
offset = oNum;
}
long size = 0;
if (val.TryGetProperty("size", out var sizeProp) && sizeProp.ValueKind == JsonValueKind.Number)
{
sizeProp.TryGetInt64(out size);
}
// 異常値チェック(ダミーエントリや破損エントリのガード)
if (offset < 0 || size < 0 || dataOffset + offset + size > fileLength)
{
continue;
}
result.TotalFilesCount++;
result.TotalUnpackedBytes += size;
if (includeFileList)
{
result.FileEntries.Add(new AsarFileEntry
{
RelativePath = path,
Offset = offset,
Size = size
});
}
// plugins.js の検出
if (name.Equals("plugins.js", StringComparison.OrdinalIgnoreCase))
{
result.RelativePluginsJsPath = path;
}
// エンジン種別判定 (rmmz_core.js -> MZ, rpg_core.js -> MV, tyrano -> Tyrano)
if (name.Equals("rmmz_core.js", StringComparison.OrdinalIgnoreCase))
{
result.EngineType = TkoolEngineType.MZ;
}
else if (name.Equals("rpg_core.js", StringComparison.OrdinalIgnoreCase) && result.EngineType == TkoolEngineType.Unknown)
{
result.EngineType = TkoolEngineType.MV;
}
else if (name.Equals("tyrano.js", StringComparison.OrdinalIgnoreCase) ||
path.Contains("data/scenario", StringComparison.OrdinalIgnoreCase) ||
name.Equals("KeyConfig.js", StringComparison.OrdinalIgnoreCase))
{
result.IsTyranoGame = true;
}
if (name.Equals("index.html", StringComparison.OrdinalIgnoreCase) && result.RelativeIndexPath == null)
{
result.RelativeIndexPath = path;
}
// タイトル抽出用
if (name.Equals("System.json", StringComparison.OrdinalIgnoreCase) && systemJsonOffset < 0)
{
systemJsonRelative = path;
systemJsonOffset = offset;
systemJsonSize = size;
}
else if (name.Equals("package.json", StringComparison.OrdinalIgnoreCase) &&
!path.Contains("node_modules", StringComparison.OrdinalIgnoreCase))
{
// ルートの package.json または project/package.json を最優先
if (packageJsonOffset < 0 || path.Equals("package.json", StringComparison.OrdinalIgnoreCase))
{
packageJsonRelative = path;
packageJsonOffset = offset;
packageJsonSize = size;
}
}
}
}
}
/// <summary>
/// Windowsの260文字制限(MAX_PATH)や予約デバイス名(CON, PRN, AUX, NUL, COM1-9, LPT1-9等)による
/// Win32例外(ハンドルが無効です。: '\\.\con' 等)を回避するため、拡張パスプレフィックス \\?\ を付与します。
/// </summary>
public static string ToExtendedPath(string path)
{
if (string.IsNullOrEmpty(path)) return path;
// Windows 環境以外はそのまま
if (!OperatingSystem.IsWindows()) return path;
// 既に \\?\ または \\.\ で始まっている場合はそのまま
if (path.StartsWith(@"\\?\", StringComparison.Ordinal) || path.StartsWith(@"\\.\", StringComparison.Ordinal))
{
return path;
}
// 区切り文字を Windows 標準のバックスラッシュに統一
string normalized = path.Replace('/', '\\');
// ドライブ文字付き絶対パス (例: C:\..., Z:\...) の場合
// ※ここで Path.GetFullPath を通すと、ファイル名が con.png などの場合に Win32 が '\\.\con' に解決してしまうため、
//  直接 \\?\ を前置することで予約デバイス名の解決を完全にバイパスします。
if (normalized.Length >= 2 && char.IsLetter(normalized[0]) && normalized[1] == ':')
{
return @"\\?\" + normalized;
}
// UNC パス (例: \\server\share\...) の場合
if (normalized.StartsWith(@"\\", StringComparison.Ordinal))
{
return @"\\?\UNC\" + normalized.Substring(2);
}
// 相対パスの場合は安全に絶対パスを取得してからプレフィックスを付与
try
{
string full = Path.GetFullPath(normalized);
if (full.StartsWith(@"\\?\", StringComparison.Ordinal) || full.StartsWith(@"\\.\", StringComparison.Ordinal))
{
return full;
}
if (full.StartsWith(@"\\", StringComparison.Ordinal))
{
return @"\\?\UNC\" + full.Substring(2);
}
return @"\\?\" + full;
}
catch
{
return path;
}
}
/// <summary>
/// ASAR ファイルを解凍し、outputDir に展開します。
/// 展開成功後、元の app.asar を app.asar.original_launcher_backup にリネームして
/// Electron が確実に解凍先 app フォルダを読み込んで起動するように準備します。
/// </summary>
public async Task<(bool Success, string Message)> ExtractAsarAsync(
string asarPath,
string outputDir,
IProgress<(long extractedBytes, long totalBytes, int currentFileIndex, int totalFiles, string currentFileName)>? progress = null,
CancellationToken ct = default)
{
return await Task.Run(() =>
{
var targetAsar = asarPath;
var backupAsar = asarPath + AsarBackupSuffix;
if (!File.Exists(ToExtendedPath(targetAsar)))
{
if (File.Exists(ToExtendedPath(backupAsar)))
{
targetAsar = backupAsar;
}
else
{
return (false, $"解凍対象の asar ファイルが見つかりません: {asarPath}");
}
}
// ヘッダ詳細解析
var inspect = InspectAsar(targetAsar, includeFileList: true);
if (!inspect.IsValid || inspect.FileEntries.Count == 0)
{
return (false, "asar ファイルのヘッダ解析に失敗したか、ファイルが含まれていません。");
}
try
{
// 拡張パス(\\?\)を適用した出力先ルートディレクトリ
string extOutputDir = ToExtendedPath(Path.GetFullPath(outputDir));
if (!Directory.Exists(extOutputDir))
{
Directory.CreateDirectory(extOutputDir);
}
byte[] buffer = new byte[128 * 1024]; // 128KB バッファ
long extractedBytes = 0;
long totalBytes = inspect.TotalUnpackedBytes;
int totalFiles = inspect.FileEntries.Count;
int skippedFilesCount = 0;
List<string> errorDetails = [];
using (var fs = new FileStream(ToExtendedPath(targetAsar), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var br = new BinaryReader(fs))
{
uint u1 = br.ReadUInt32();
uint headerSize = br.ReadUInt32();
long dataOffset = 8 + (long)headerSize;
for (int i = 0; i < inspect.FileEntries.Count; i++)
{
if (ct.IsCancellationRequested)
{
return (false, "解凍処理が中断されました。");
}
var entry = inspect.FileEntries[i];
// extOutputDir (\\?\C:\...) と entry.RelativePath を結合
// ※先頭に \\?\ が付いているため、con.png や aux.mp3 などの予約デバイス名があっても
//  Win32 による \\.\con への置換が発生せず、正常にファイル作成が可能
string destFilePath = Path.Combine(extOutputDir, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar));
string? parentDir = Path.GetDirectoryName(destFilePath);
if (!string.IsNullOrEmpty(parentDir) && !Directory.Exists(parentDir))
{
Directory.CreateDirectory(parentDir);
}
// ファイル書き込み
try
{
fs.Seek(dataOffset + entry.Offset, SeekOrigin.Begin);
long remaining = entry.Size;
using (var outFs = new FileStream(destFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
while (remaining > 0)
{
int toRead = (int)Math.Min(remaining, buffer.Length);
int read = fs.Read(buffer, 0, toRead);
if (read == 0) break;
outFs.Write(buffer, 0, read);
remaining -= read;
extractedBytes += read;
progress?.Report((extractedBytes, totalBytes, i + 1, totalFiles, Path.GetFileName(entry.RelativePath)));
}
}
}
catch (Exception fileEx)
{
// 予約文字や排他ロック等の例外が発生した場合、解凍全体を止めずに警告として記録
skippedFilesCount++;
if (errorDetails.Count < 5)
{
errorDetails.Add($"{entry.RelativePath} ({fileEx.Message})");
}
}
}
} // ここで fs と br が確実に Dispose されてファイルハンドルが解放される
// 展開が正常完了したら、元の app.asar をリネームバックアップする
// (これにより Electron は同階層の解凍 app フォルダを最優先で読み込み、改造プラグインが確実に動作する)
string extAsarPath = ToExtendedPath(asarPath);
string extBackupAsar = ToExtendedPath(backupAsar);
if (File.Exists(extAsarPath) && !asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase))
{
if (File.Exists(extBackupAsar))
{
File.Delete(extBackupAsar);
}
File.Move(extAsarPath, extBackupAsar);
}
string summary = $"ASARの解凍が完了しました。(全 {totalFiles} ファイル展開完了)";
if (skippedFilesCount > 0)
{
summary += $" ※一部ファイル({skippedFilesCount}件)の展開をスキップ: {string.Join(", ", errorDetails)}";
}
return (true, summary);
}
catch (Exception ex)
{
return (false, $"ASAR解凍中にエラーが発生しました: {ex.Message}");
}
}, ct);
}
/// <summary>
/// 解凍された app フォルダを安全に削除し、バックアップされていた app.asar を元の名前に復元します。
/// これによりゲームは完全にオリジナルの app.asar 実行状態へ戻ります。
/// </summary>
public async Task<(bool Success, string Message)> RestoreAsarAsync(string asarPath, string extractedDir, CancellationToken ct = default)
{
return await Task.Run(() =>
{
var backupAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase)
? asarPath
: asarPath + AsarBackupSuffix;
var originalAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase)
? asarPath.Substring(0, asarPath.Length - AsarBackupSuffix.Length)
: asarPath;
string extExtractedDir = ToExtendedPath(extractedDir);
string extBackupAsar = ToExtendedPath(backupAsar);
string extOriginalAsar = ToExtendedPath(originalAsar);
try
{
// 1. 解凍ディレクトリの削除(con.png等の特殊名を含むフォルダも拡張パスで安全に削除)
if (!string.IsNullOrEmpty(extExtractedDir) && Directory.Exists(extExtractedDir))
{
Directory.Delete(extExtractedDir, true);
}
// 2. バックアップした asar を元の名前に戻す
if (File.Exists(extBackupAsar))
{
if (File.Exists(extOriginalAsar))
{
File.Delete(extOriginalAsar);
}
File.Move(extBackupAsar, extOriginalAsar);
}
return (true, "ゲームを元の app.asar 形式に復元しました。(解凍フォルダは綺麗に削除されました)");
}
catch (Exception ex)
{
return (false, $"復元処理中にエラーが発生しました: {ex.Message}");
}
}, ct);
}
}
}
+378
View File
@@ -0,0 +1,378 @@
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
namespace GameLauncher.Engines.Nwjs
{
/// <summary>
/// nw.js 系(boxed / FOSSIL 等の単体exe梱包)ツクールゲームから、
/// 埋め込まれた package.nw 相当のコンテナを抽出する汎用アンパッカー。
///
/// 方針(恒久・再利用可能):
/// - 特定ゲーム専用ではなく、共通の署名探索アルゴリズムで「埋め込みZIPコンテナ」を探す。
/// - exe 全体を一括読みしない。ブロック単位の逐次走査で PK ローカルヘッダ→EOCD を確定する。
/// - 抽出先はゲームフォルダ内 `_extracted` のみ(他ゲームへ一切影響しない)。
/// - 冪等: 既に展開済み(plugins.js が解決できる)なら再展開しない。
///
/// 抽出戦略は <see cref="INwjsUnpackStrategy"/> として差し替え可能にしてあり、
/// 将来新しい梱包形式が出た場合は戦略を追加するだけで拡張できる。
/// </summary>
public static class NwjsPackageUnpacker
{
/// <summary>ゲームフォルダ内の展開先フォルダ名(Asar/SRPG の慣習に合わせる)</summary>
public const string ExtractedDirName = "_extracted";
/// <summary>走査ブロックサイズ(1ブロックあたりの読み込み量)</summary>
private const int ScanBlockSize = 4 * 1024 * 1024;
/// <summary>単一のPKローカルヘッダから読み込める最大ウィンドウ(EOCD 探索用)</summary>
private const int MaxSingleZipScan = 256 * 1024 * 1024;
/// <summary>ゲームフォルダ内の展開先ディレクトリ(物理パス)</summary>
public static string GetExtractedDir(string gameRootDir)
=> Path.Combine(gameRootDir, ExtractedDirName);
/// <summary>
/// 展開先 `_extracted` に js/plugins.js(または www/js/plugins.js)が存在するか判定します。
/// </summary>
public static bool IsExtractionComplete(string extractedDir, out string? pluginsJsPath, out string? relativePlugins)
{
pluginsJsPath = null;
relativePlugins = null;
try
{
var candidates = new[]
{
new { Abs = Path.Combine(extractedDir, "js", "plugins.js"), Rel = "js/plugins.js" },
new { Abs = Path.Combine(extractedDir, "js", "plugins", "plugins.js"), Rel = "js/plugins/plugins.js" },
new { Abs = Path.Combine(extractedDir, "www", "js", "plugins.js"), Rel = "www/js/plugins.js" },
};
foreach (var c in candidates)
{
if (File.Exists(c.Abs))
{
pluginsJsPath = c.Abs;
relativePlugins = c.Rel;
return true;
}
}
}
catch { }
return false;
}
/// <summary>
/// 指定パス直下から js/plugins.js を解決します(_extracted 配下優先)。
/// </summary>
public static string? ResolvePluginsJs(string rootDir)
{
try
{
var candidates = new[]
{
Path.Combine(rootDir, "js", "plugins.js"),
Path.Combine(rootDir, "js", "plugins", "plugins.js"),
Path.Combine(rootDir, "www", "js", "plugins.js"),
Path.Combine(rootDir, "package.nw", "js", "plugins.js"),
};
return candidates.FirstOrDefault(File.Exists);
}
catch
{
return null;
}
}
/// <summary>
/// 判定に必要な署名情報。汎用の埋め込みZIPコンテナ有無を表します。
/// </summary>
public sealed class EmbeddedZipProbeResult
{
/// <summary>PK ローカルヘッダ(PK\x03\x04)の先頭オフセット(見つかった場合)</summary>
public long? LocalHeaderOffset { get; init; }
/// <summary>EOCD(PK\x05\x06)の末尾オフセット(見つかった場合)</summary>
public long? EocdOffset { get; init; }
/// <summary>コンテナ内に package.json 文字列が見つかったか</summary>
public bool HasPackageJson { get; init; }
/// <summary>標準ZIPとして展開可能そうか</summary>
public bool IsZipExtractable => LocalHeaderOffset.HasValue && EocdOffset.HasValue;
}
/// <summary>
/// 埋め込みコンテナ(package.nw = 標準ZIP)を逐次走査で探索します。全走査でも
/// exe を一括メモリへ載せないため、1.14GB級でも安全です。
/// </summary>
/// <param name="exePath">対象の単体exeパス</param>
/// <param name="progress">進捗通知(任意)</param>
/// <param name="maxScanBytes">先頭から走査する最大バイト数(既定は末尾まで)</param>
public static EmbeddedZipProbeResult ProbeEmbeddedZip(string exePath, IProgress<string>? progress = null, long maxScanBytes = long.MaxValue)
{
if (!File.Exists(exePath))
{
return new EmbeddedZipProbeResult();
}
long? localHeader = null;
bool hasPackageJson = false;
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
long fileSize = fs.Length;
long scanLimit = Math.Min(fileSize, maxScanBytes);
var buf = new byte[ScanBlockSize];
long pos = 0;
// ブロック境界をまたぐPK検出のため、直前3バイトを保持する
int carry = 0;
byte b1 = 0, b2 = 0, b3 = 0;
progress?.Report($"埋め込みZIPコンテナを走査中... ({fileSize:N0} bytes)");
while (pos < scanLimit)
{
int toRead = (int)Math.Min(buf.Length, scanLimit - pos);
fs.Seek(pos, SeekOrigin.Begin);
int read = fs.Read(buf, 0, toRead);
if (read <= 0)
{
break;
}
for (int i = 0; i < read; i++)
{
byte cur = buf[i];
if (carry == 3 && b1 == 0x50 && b2 == 0x4B && b3 == 0x03 && cur == 0x04 && localHeader == null)
{
// ローカルヘッダ先頭位置 = (今回ブロック開始 - 3) + (i - 3)
long abs = pos + i - 3;
if (abs >= 0)
{
localHeader = abs;
progress?.Report($"埋め込みZIPローカルヘッダを検出: offset={abs:N0}");
}
}
if (b1 == 0x50 && b2 == 0x4B && b3 == 0x03 && cur == 0x04)
{
b1 = b2; b2 = b3; b3 = cur;
}
else
{
b1 = b2; b2 = b3; b3 = cur;
}
if (carry < 3)
{
carry++;
}
}
// ブロック内で package.json 文字列を軽く探索(タイトル推定用・厳密性は不要)
if (!hasPackageJson)
{
var ascii = System.Text.Encoding.ASCII.GetString(buf, 0, read);
if (ascii.IndexOf("package.json", StringComparison.Ordinal) >= 0)
{
hasPackageJson = true;
}
}
pos += read;
progress?.Report($"走査中... {pos:N0} / {fileSize:N0} bytes");
}
// EOCD(PK\x05\x06)は末尾近傍にある。末尾 64KB を走査。
long? eocd = null;
if (localHeader.HasValue)
{
int tailLen = (int)Math.Min(64 * 1024, fileSize);
var tail = new byte[tailLen];
fs.Seek(fileSize - tailLen, SeekOrigin.Begin);
int tr = fs.Read(tail, 0, tailLen);
for (int i = tr - 4; i >= 0; i--)
{
if (tail[i] == 0x50 && tail[i + 1] == 0x4B && tail[i + 2] == 0x05 && tail[i + 3] == 0x06)
{
eocd = (fileSize - tailLen) + i;
break;
}
}
// 末尾64KBに無ければローカルヘッダ以降の限定ウィンドウも確認(巨大な付加データ対策)
if (eocd == null)
{
eocd = FindEocdNearOffset(fs, localHeader.Value, fileSize);
}
}
return new EmbeddedZipProbeResult
{
LocalHeaderOffset = localHeader,
EocdOffset = eocd,
HasPackageJson = hasPackageJson
};
}
/// <summary>
/// ローカルヘッダ以降を(最大<see cref="MaxSingleZipScan"/>まで)限定走査し、EOCD 位置を探します。
/// </summary>
private static long? FindEocdNearOffset(FileStream fs, long start, long fileSize)
{
long limit = Math.Min(fileSize, start + MaxSingleZipScan);
// 末尾から逆方向に少しずつ探す方が現実的だが、境界が読めない場合は後方優先で探す
long window = 4 * 1024 * 1024;
for (long end = limit; end > start; end -= window)
{
long begin = Math.Max(start, end - window);
int len = (int)(end - begin);
if (len <= 4)
{
continue;
}
var buf = new byte[len];
fs.Seek(begin, SeekOrigin.Begin);
int read = fs.Read(buf, 0, len);
for (int i = read - 4; i >= 0; i--)
{
if (buf[i] == 0x50 && buf[i + 1] == 0x4B && buf[i + 2] == 0x05 && buf[i + 3] == 0x06)
{
return begin + i;
}
}
}
return null;
}
/// <summary>
/// exe 内に埋め込まれた ZIP(package.nw)を、指定の展開先へ冪等に全展開します。
/// 標準ZIPとして解釈できる場合のみ成功します。
/// </summary>
/// <returns>展開後の js/plugins.js の相対パス(/区切り)。解決できなければ null。</returns>
public static string? ExtractEmbeddedZip(string exePath, string destDir, IProgress<string>? progress = null)
{
try
{
var probe = ProbeEmbeddedZip(exePath, progress);
if (!probe.IsZipExtractable)
{
progress?.Report("埋め込みZIPコンテナを確定できませんでした(非標準コンテナの可能性)。");
return null;
}
Directory.CreateDirectory(destDir);
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
long zipLength = probe.EocdOffset!.Value + 22 - probe.LocalHeaderOffset!.Value;
fs.Seek(probe.LocalHeaderOffset!.Value, SeekOrigin.Begin);
// EOCD を含む範囲だけを ZipArchive へ渡す(exe 末尾の付加データを切り離す)
using var slice = new SubStream(fs, probe.LocalHeaderOffset!.Value, zipLength);
using var zip = new ZipArchive(slice, ZipArchiveMode.Read);
foreach (var entry in zip.Entries)
{
var entryRel = entry.FullName.Replace('/', Path.DirectorySeparatorChar);
var dest = Path.Combine(destDir, entryRel);
// ディレクトリエントリ
if (string.IsNullOrEmpty(entry.Name))
{
Directory.CreateDirectory(dest);
continue;
}
var parent = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(parent))
{
Directory.CreateDirectory(parent);
}
using (var src = entry.Open())
using (var outFs = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None))
{
src.CopyTo(outFs);
}
}
progress?.Report("埋め込みZIPコンテナの展開が完了しました。");
return IsExtractionComplete(destDir, out _, out var rel) ? rel : null;
}
catch (Exception ex)
{
progress?.Report($"埋め込みZIP展開中にエラーが発生しました: {ex.Message}");
return null;
}
}
/// <summary>
/// 指定範囲のみを読み出す読み取り専用ストリーム(ZIP末尾の付加データ分離用)。
/// </summary>
private sealed class SubStream : Stream
{
private readonly Stream _base;
private readonly long _start;
private readonly long _length;
private long _pos;
public SubStream(Stream baseStream, long start, long length)
{
_base = baseStream;
_start = start;
_length = length;
}
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override long Length => _length;
public override long Position
{
get => _pos;
set => _pos = value;
}
public override int Read(byte[] buffer, int offset, int count)
{
long remaining = _length - _pos;
if (remaining <= 0)
{
return 0;
}
int toRead = (int)Math.Min(count, remaining);
_base.Seek(_start + _pos, SeekOrigin.Begin);
int read = _base.Read(buffer, offset, toRead);
_pos += read;
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
_pos = origin switch
{
SeekOrigin.Begin => offset,
SeekOrigin.Current => _pos + offset,
SeekOrigin.End => _length + offset,
_ => _pos
};
return _pos;
}
public override void Flush() { }
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
/// <summary>
/// 抽出戦略の抽象。標準ZIP以外の独自コンテナが出た場合に差し替え可能にするための骨組み。
/// </summary>
public interface INwjsUnpackStrategy
{
string Name { get; }
bool CanHandle(string exePath);
string? Extract(string exePath, string destDir, IProgress<string>? progress);
}
}
}
+341
View File
@@ -0,0 +1,341 @@
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using GameLauncher.Helpers;
namespace GameLauncher.Engines.Nwjs
{
/// <summary>
/// nw.js 埋め込み package.nw を抽出する外部アンパッカーツールの供給・呼び出しを担う汎用プロバイダ。
///
/// 設計方針(恒久・再利用可能):
/// - ツールは `Engines\Nwjs\Tools\` 配下に配置する(エンジン別のツールフォルダ)。
/// - 未配置の場合は初回利用時に自動ダウンロードして同フォルダへ展開する(ユーザー確認なし)。
/// - ネット未接続等で入手できない場合は、例外を投げず null を返して「起動のみ」にフォールバックさせる。
/// - 特定ゲーム専用の決め打ちは禁止。呼び出し規約(引数・出力ディレクトリ)は汎用に扱う。
///
/// 外部ツールは「7-Zip 互換のコマンドライン(-o/-y で展開)」を持つものを第一候補とし、
/// 追加の抽出戦略が増えた場合も同じ呼び出しインターフェースで扱えるようにしてある。
/// </summary>
public static class NwjsUnpackerToolProvider
{
/// <summary>Engine identifier used to resolve the per-engine tools folder.</summary>
public const string EngineName = "Nwjs";
/// <summary>Fallback tools folder name (legacy layout).</summary>
public const string ToolsDirName = "Tools";
/// <summary>外部アンパッカーの実行ファイル名(Tools 配下へ配置する想定)</summary>
public const string DefaultToolExeName = "7z.exe";
/// <summary>
/// 外部ツールの入手元 URL(7-Zip 公式・Windows x64 版)。ダウンロード後に展開して
/// 7z.exe / 7z.dll のみを Tools 配下へ配置します。
/// </summary>
private static readonly string[] ToolArchiveUrls =
{
"https://www.7-zip.org/a/7zr.exe", // 単体実行版(依存 DLL 不要)
"https://www.7-zip.org/a/7z2408-extra.7z", // 予備(extra パッケージ)
};
/// <summary>
/// Returns the engine-specific tools directory (Engines\Nwjs\Tools).
/// Each engine references only its own tools folder, so the NW.js
/// unpacker never depends on another engine's files.
/// </summary>
public static string GetToolsDirectory()
{
return AppPathHelper.GetEngineToolsDirectory(EngineName);
}
/// <summary>配置済みの外部アンパッカー exe のフルパスを取得します(無ければ null)。</summary>
public static string? GetToolPath()
{
try
{
var tools = GetToolsDirectory();
// 優先順: 7zr(単体)→ 7z → 汎用名
var candidates = new[]
{
Path.Combine(tools, "7zr.exe"),
Path.Combine(tools, DefaultToolExeName),
Path.Combine(tools, "nwjs-unpack.exe"),
};
return candidates.FirstOrDefault(File.Exists);
}
catch
{
return null;
}
}
/// <summary>
/// 外部アンパッカーの可用性を判定します。
/// </summary>
public static bool IsToolAvailable() => GetToolPath() != null;
/// <summary>
/// 外部アンパッカーが未配置の場合、初回利用時に自動ダウンロードして Tools 配下へ配置します。
/// 失敗(ネット未接続等)時は例外を投げず false を返します。
/// </summary>
public static async Task<bool> EnsureToolAvailableAsync(IProgress<string>? progress = null, CancellationToken ct = default)
{
if (IsToolAvailable())
{
return true;
}
try
{
var tools = GetToolsDirectory();
Directory.CreateDirectory(tools);
foreach (var url in ToolArchiveUrls)
{
try
{
progress?.Report($"外部アンパッカーを取得中: {url}");
var fileName = Path.GetFileName(new Uri(url).LocalPath);
var dest = Path.Combine(tools, fileName);
if (!await DownloadFileAsync(url, dest, progress, ct).ConfigureAwait(false))
{
continue;
}
// 単体実行版(7zr.exe)はそのまま配置
if (fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
progress?.Report($"外部アンパッカーを配置しました: {dest}");
return IsToolAvailable();
}
// .7z アーカイブの場合は 7zr で本体を抽出(可能な範囲で)
// 7zr.exe が既に同梱されていればそれを使い、無ければ諦めて次URLへ。
progress?.Report("アーカイブを展開して本体を配置します...");
if (TryExpandArchive(dest, tools, progress))
{
return IsToolAvailable();
}
}
catch (Exception ex)
{
progress?.Report($"取得元の処理に失敗しました(次候補を試行): {ex.Message}");
}
}
}
catch (Exception ex)
{
progress?.Report($"外部アンパッカーの取得に失敗しました: {ex.Message}");
}
return IsToolAvailable();
}
private static async Task<bool> DownloadFileAsync(string url, string dest, IProgress<string>? progress, CancellationToken ct)
{
try
{
using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
using var resp = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode)
{
progress?.Report($"ダウンロード失敗 (HTTP {(int)resp.StatusCode}): {url}");
return false;
}
var total = resp.Content.Headers.ContentLength ?? -1;
await using var src = await resp.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
await using var outFs = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None);
var buf = new byte[81920];
long written = 0;
int read;
while ((read = await src.ReadAsync(buf, ct).ConfigureAwait(false)) > 0)
{
await outFs.WriteAsync(buf.AsMemory(0, read), ct).ConfigureAwait(false);
written += read;
if (total > 0)
{
progress?.Report($"ダウンロード中... {written * 100 / total}%");
}
}
return File.Exists(dest) && new FileInfo(dest).Length > 0;
}
catch (Exception ex)
{
progress?.Report($"ダウンロードに失敗しました: {ex.Message}");
return false;
}
}
/// <summary>
/// ダウンロードした .7z / .zip アーカイブから 7z.exe / 7zr.exe を Tools へ配置します。
/// ZIP は .NET 標準で、.7z は既存 7zr.exe がある場合のみ実行します。
/// </summary>
private static bool TryExpandArchive(string archivePath, string toolsDir, IProgress<string>? progress)
{
try
{
if (archivePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
{
using var zip = ZipFile.OpenRead(archivePath);
foreach (var entry in zip.Entries)
{
var name = Path.GetFileName(entry.FullName);
if (name.Equals("7zr.exe", StringComparison.OrdinalIgnoreCase) ||
name.Equals("7z.exe", StringComparison.OrdinalIgnoreCase) ||
name.Equals("7z.dll", StringComparison.OrdinalIgnoreCase))
{
var dest = Path.Combine(toolsDir, name);
entry.ExtractToFile(dest, overwrite: true);
}
}
return IsToolAvailable();
}
// .7z は既存の 7zr.exe がある場合のみ展開を試みる
var existing = Path.Combine(toolsDir, "7zr.exe");
if (!File.Exists(existing))
{
return false;
}
var psi = new ProcessStartInfo
{
FileName = existing,
Arguments = $"x \"{archivePath}\" -o\"{toolsDir}\" -y",
WorkingDirectory = toolsDir,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using var proc = Process.Start(psi);
if (proc == null)
{
return false;
}
proc.StandardOutput.ReadToEnd();
proc.StandardError.ReadToEnd();
proc.WaitForExit();
return IsToolAvailable();
}
catch (Exception ex)
{
progress?.Report($"アーカイブ展開に失敗しました: {ex.Message}");
return false;
}
}
/// <summary>
/// 外部アンパッカーで exe 内の埋め込みコンテナ(package.nw 等)を destDir へ全展開します。
/// 呼び出し規約は「7-Zip 互換: &lt;tool&gt; x &lt;archive&gt; -o&lt;out&gt; -y」を第一候補、
/// 対応しない場合は 2 番目の規約(&lt;tool&gt; &lt;archive&gt; -o &lt;out&gt;)へフォールバックします。
/// </summary>
/// <returns>成功時 true(destDir に何らかのファイルが展開された場合)。</returns>
public static bool ExtractWithExternalTool(string toolPath, string sourceExePath, string destDir, IProgress<string>? progress = null, int timeoutMs = 30 * 60 * 1000)
{
try
{
Directory.CreateDirectory(destDir);
// 規約1: 7-Zip 互換
if (RunTool(toolPath, $"x \"{sourceExePath}\" -o\"{destDir}\" -y", destDir, progress, timeoutMs, out var code1))
{
if (HasAnyExtractedFile(destDir))
{
return true;
}
}
progress?.Report($"外部ツール規約1の出力が空でした (code={code1})。規約2を試行します。");
// 規約2: <tool> <archive> -o <out>
if (RunTool(toolPath, $"\"{sourceExePath}\" -o \"{destDir}\"", destDir, progress, timeoutMs, out var code2))
{
if (HasAnyExtractedFile(destDir))
{
return true;
}
}
progress?.Report($"外部ツールでの展開に失敗しました (code1={code1}, code2={code2})。");
return false;
}
catch (Exception ex)
{
progress?.Report($"外部ツール実行中にエラーが発生しました: {ex.Message}");
return false;
}
}
private static bool RunTool(string toolPath, string args, string workDir, IProgress<string>? progress, int timeoutMs, out int exitCode)
{
exitCode = -1;
try
{
var psi = new ProcessStartInfo
{
FileName = toolPath,
Arguments = args,
WorkingDirectory = workDir,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using var proc = Process.Start(psi);
if (proc == null)
{
return false;
}
// 出力を読み切ってから待機(デッドロック回避)
var stdout = proc.StandardOutput.ReadToEnd();
var stderr = proc.StandardError.ReadToEnd();
if (!proc.WaitForExit(timeoutMs))
{
try { proc.Kill(entireProcessTree: true); } catch { }
progress?.Report("外部ツールがタイムアウトしました。");
return false;
}
exitCode = proc.ExitCode;
if (!string.IsNullOrWhiteSpace(stdout))
{
progress?.Report(stdout.Trim());
}
if (!string.IsNullOrWhiteSpace(stderr))
{
progress?.Report($"[stderr] {stderr.Trim()}");
}
return exitCode == 0;
}
catch (Exception ex)
{
progress?.Report($"外部ツール起動に失敗しました: {ex.Message}");
return false;
}
}
private static bool HasAnyExtractedFile(string dir)
{
try
{
return Directory.Exists(dir) && Directory.EnumerateFileSystemEntries(dir).Any();
}
catch
{
return false;
}
}
}
}
@@ -0,0 +1,33 @@
# nw.js boxed 解凍用 外部アンパッカー
このフォルダには、GameLauncher が **nw.js boxed 系ツクールゲーム**(例: `Game_boxed.exe` のように
ゲーム本体を exe へ内包した形態)の埋め込みコンテナ(`package.nw` = 標準ZIP)を展開するために
利用する外部アンパッカーを配置します。
## 対象
- `*boxed*.exe`(nw.js 埋め込み。`package.nw` / `package.json` を含む)
- その他、単体exeへ `package.nw` 相当の埋め込みZIPを持つツクール MZ/MV ゲーム
## 使用するツール
- `7zr.exe`(7-Zip 公式の単体実行版・依存DLL不要)を第一候補とします。
- 代替として `7z.exe`(+ `7z.dll`)も検出対象です。
## 配置方法
- **同梱されている場合**: この `Tools\` フォルダに `7zr.exe` を置いてください。
`publish.ps1` 実行時に `Z:\自作ソフト\GameLauncher\Tools\` へコピーされます。
- **未配置の場合**: GameLauncher 実行時、boxed 解凍が必要になった時点で
7-Zip 公式(https://www.7-zip.org/a/7zr.exe)から自動ダウンロードし、配置を試みます
(ネット未接続などで取得に失敗した場合は「起動のみ」にフォールバックし、ゲーム自体は起動できます)。
## 実装上の参照
- 取得・呼び出し: `Services\NwjsUnpackerToolProvider.cs`
- 埋め込みZIP検出・展開: `Services\NwjsPackageUnpacker.cs`
- オーケストレーター(戦略: 組み込みZIP → 外部ツール): `Services\TkoolPackagedExtractionService.cs`
## 呼び出し規約
- 第一候補: `7zr.exe x "<exe>" -o"<out>" -y`
- フォールバック: `7zr.exe "<exe>" -o "<out>"`
## ライセンス
7-Zip は GNU LGPL + unRAR restriction の下で配布されています。
再頒布する場合は 7-Zip のライセンス条項(https://www.7-zip.org/license.txt)に従ってください。
@@ -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.Substring(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 Array.Empty<string>();
byte[] bytes = File.ReadAllBytes(filePath);
if (bytes.Length == 0) return Array.Empty<string>();
// 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(new[] { "\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(new[] { "\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(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
}
catch
{
return Array.Empty<string>();
}
}
}
}
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.Substring(0, 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 _archiveService.UnpackDataDtsAsync(gameDir, progress);
if (!unpackRes.Success)
{
return unpackRes;
}
}
var extractedDir = SrpgArchiveService.GetExtractedDirectory(gameDir);
progress?.Report("Modスクリプトを生成中...");
var modBody = 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 _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 revertRes = await _archiveService.RevertBackupAsync(gameDir);
if (revertRes.Success)
{
item.IsModded = false;
return (true, "改造プラグインを解除し、元のアーカイブへ復元しました。");
}
// バックアップが無い場合は Mod解除状態で再パック
progress?.Report("Mod解除状態でアーカイブを再構築中...");
var repackRes = await _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))
{
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 revertRes = await _archiveService.RevertBackupAsync(gameDir);
if (revertRes.Success)
{
logs.Add($"・{revertRes.Message}");
}
else
{
logs.Add("・元の data.dts バックアップは適用不要または存在しませんでした");
}
// 4. 解凍フォルダの退避
var restoreExtractedRes = _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);
}
}
}
+722
View File
@@ -0,0 +1,722 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using GameLauncher.Models;
using GameLauncher.Engines.Unity;
namespace GameLauncher.Engines.Tkool
{
/// <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;
// ================= 単体exe梱包(FOSSIL / boxed)関連プロパティ =================
// js/plugins.js がディスク上に無く、exeへ埋め込まれている形態を識別します。
private bool _isFossilSingleExe;
private bool _isBoxedExe;
private bool _isStandaloneExeExtracted;
private string? _standaloneExtractedDirPath;
private string? _standaloneBackupPath;
private string? _boxedPayloadEntryPath;
private bool _canExtractViaExternalTool;
/// <summary>FOSSIL形態(FOSSILindex.html + 単体Game.exe、data/System.json はディスク上)かどうか</summary>
public bool IsFossilSingleExe
{
get => _isFossilSingleExe;
set { if (_isFossilSingleExe != value) { _isFossilSingleExe = value; OnPropertyChanged(); } }
}
/// <summary>boxed形態(ゲーム本体をexeへ内包、例: Game_boxed.exe)かどうか</summary>
public bool IsBoxedExe
{
get => _isBoxedExe;
set { if (_isBoxedExe != value) { _isBoxedExe = value; OnPropertyChanged(); } }
}
/// <summary>いずれかの単体exe梱包形態(FOSSIL / boxed)かどうか</summary>
public bool IsStandaloneExePackage => IsFossilSingleExe || IsBoxedExe;
/// <summary>単体exe梱包ゲームを _extracted へ展開済みかどうか</summary>
public bool IsStandaloneExeExtracted
{
get => _isStandaloneExeExtracted;
set { if (_isStandaloneExeExtracted != value) { _isStandaloneExeExtracted = value; OnPropertyChanged(); } }
}
/// <summary>展開先ディレクトリ(ゲームフォルダ内 _extracted)</summary>
public string? StandaloneExtractedDirPath
{
get => _standaloneExtractedDirPath;
set { if (_standaloneExtractedDirPath != value) { _standaloneExtractedDirPath = value; OnPropertyChanged(); } }
}
/// <summary>exe内コンテナ改変時のバックアップパス(*.glbak)</summary>
public string? StandaloneBackupPath
{
get => _standaloneBackupPath;
set { if (_standaloneBackupPath != value) { _standaloneBackupPath = value; OnPropertyChanged(); } }
}
/// <summary>boxed exe内で注入対象とするコンテナ内エントリ(例: js/plugins.js)</summary>
public string? BoxedPayloadEntryPath
{
get => _boxedPayloadEntryPath;
set { if (_boxedPayloadEntryPath != value) { _boxedPayloadEntryPath = value; OnPropertyChanged(); } }
}
/// <summary>
/// 外部アンパッカー(Tools\7zr.exe 等)による展開を試行できる可能性があるか。
/// 標準ZIP署名が未確定でも、boxed命名exeが存在する場合に true となり「展開試行可」を示す。
/// 実際に展開可能かは実行時(ExtractPackageNw)に確定する。
/// </summary>
public bool CanExtractViaExternalTool
{
get => _canExtractViaExternalTool;
set { if (_canExtractViaExternalTool != value) { _canExtractViaExternalTool = value; OnPropertyChanged(); } }
}
public override GameEngineKind EngineKind => EngineType switch
{
TkoolEngineType.Tyrano => GameEngineKind.Tyrano,
TkoolEngineType.Wolf => GameEngineKind.Wolf,
TkoolEngineType.SrpgStudio => GameEngineKind.SrpgStudio,
_ => 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 override bool IsVX => EngineType == TkoolEngineType.VX;
public override bool IsVXAce => EngineType == TkoolEngineType.VXAce;
public override bool IsWolf => EngineType == TkoolEngineType.Wolf;
public override bool IsSrpgStudio => EngineType == TkoolEngineType.SrpgStudio;
public override bool IsRgss => EngineType is TkoolEngineType.VX or TkoolEngineType.VXAce;
/// <summary>
/// 「プリンセスシナジー」(ツクールMZ製・専用改造対象ゲーム)かどうか。
/// タイトルまたはフォルダ名に "プリンセスシナジー" を含み、エンジンがMZの場合のみ true。
/// これにより当該機能が他ゲームに表示・適用されるのを防ぎます。
/// </summary>
public override bool IsPrincessSynergy =>
!string.IsNullOrEmpty(Title) && Title.Contains("プリンセスシナジー");
// SRPG Studio アーカイブ関連プロパティ
private bool _hasSrpgArchive;
private bool _isSrpgExtracted;
private string? _srpgArchivePath;
public override bool HasSrpgArchive
{
get => _hasSrpgArchive;
set
{
if (_hasSrpgArchive != value)
{
_hasSrpgArchive = value;
OnPropertyChanged();
OnPropertyChanged(nameof(SrpgBadgeVisibility));
OnPropertyChanged(nameof(SrpgBadgeText));
OnPropertyChanged(nameof(SrpgBadgeBackground));
OnPropertyChanged(nameof(SrpgDetailStatusText));
}
}
}
public override bool IsSrpgExtracted
{
get => _isSrpgExtracted;
set
{
if (_isSrpgExtracted != value)
{
_isSrpgExtracted = value;
OnPropertyChanged();
OnPropertyChanged(nameof(SrpgBadgeText));
OnPropertyChanged(nameof(SrpgBadgeBackground));
OnPropertyChanged(nameof(SrpgDetailStatusText));
}
}
}
public string? SrpgArchivePath
{
get => _srpgArchivePath;
set { if (_srpgArchivePath != value) { _srpgArchivePath = value; OnPropertyChanged(); } }
}
public override Visibility SrpgBadgeVisibility => HasSrpgArchive ? Visibility.Visible : Visibility.Collapsed;
public override string SrpgBadgeText => !HasSrpgArchive ? string.Empty : (IsSrpgExtracted ? "SRPG (抽出済)" : "SRPG (暗号化)");
public override Brush SrpgBadgeBackground => IsSrpgExtracted
? new SolidColorBrush(Color.FromRgb(0x00, 0x89, 0x7B))
: new SolidColorBrush(Color.FromRgb(0x09, 0x84, 0xE3));
public override string SrpgDetailStatusText => !HasSrpgArchive
? string.Empty
: (IsSrpgExtracted ? "📦 SRPGアーカイブ(スクリプト/リソース抽出済み・改造可能)" : "🔒 SRPG暗号化アーカイブ(ボタンで抽出・改造・再構築可能)");
// RGSS (VX / VX Ace) アーカイブ関連プロパティ
private bool _hasRgssArchive;
private bool _isRgssExtracted;
private string? _rgssArchivePath;
public override bool HasRgssArchive
{
get => _hasRgssArchive;
set
{
if (_hasRgssArchive != value)
{
_hasRgssArchive = value;
OnPropertyChanged();
OnPropertyChanged(nameof(RgssBadgeVisibility));
OnPropertyChanged(nameof(RgssBadgeText));
OnPropertyChanged(nameof(RgssBadgeBackground));
OnPropertyChanged(nameof(RgssDetailStatusText));
}
}
}
public override bool IsRgssExtracted
{
get => _isRgssExtracted;
set
{
if (_isRgssExtracted != value)
{
_isRgssExtracted = value;
OnPropertyChanged();
OnPropertyChanged(nameof(RgssBadgeText));
OnPropertyChanged(nameof(RgssBadgeBackground));
OnPropertyChanged(nameof(RgssDetailStatusText));
}
}
}
public string? RgssArchivePath
{
get => _rgssArchivePath;
set { if (_rgssArchivePath != value) { _rgssArchivePath = value; OnPropertyChanged(); } }
}
public override Visibility RgssBadgeVisibility => HasRgssArchive ? Visibility.Visible : Visibility.Collapsed;
public override string RgssBadgeText => !HasRgssArchive ? string.Empty : (IsRgssExtracted ? "RGSS (抽出済)" : "RGSS (暗号化)");
public override Brush RgssBadgeBackground => IsRgssExtracted
? new SolidColorBrush(Color.FromRgb(0x00, 0x89, 0x7B))
: new SolidColorBrush(Color.FromRgb(0xD3, 0x54, 0x00));
public override string RgssDetailStatusText => !HasRgssArchive
? string.Empty
: (IsRgssExtracted ? "📦 RGSSアーカイブ(スクリプト抽出済み・改造可能)" : "🔒 RGSS暗号化アーカイブ(起動時またはボタンでスクリプト抽出可能)");
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));
OnPropertyChanged(nameof(IsVX));
OnPropertyChanged(nameof(IsVXAce));
OnPropertyChanged(nameof(IsWolf));
OnPropertyChanged(nameof(IsSrpgStudio));
OnPropertyChanged(nameof(IsRgss));
}
}
}
// ================= WOLF RPGエディター関連プロパティ =================
private bool _wolfProxyDll = false;
private double _wolfSpeedMultiplier = 3.0;
private bool _hasWolfArchive = false;
private bool _isWolfExtracted = false;
/// <summary>プロキシDLL(version.dll 倍速/メモリフック)を適用するか</summary>
public bool WolfProxyDll
{
get => _wolfProxyDll;
set { if (_wolfProxyDll != value) { _wolfProxyDll = value; OnPropertyChanged(); } }
}
/// <summary>プロキシDLLのスピード倍率</summary>
public double WolfSpeedMultiplier
{
get => _wolfSpeedMultiplier;
set { if (_wolfSpeedMultiplier != value) { _wolfSpeedMultiplier = value; OnPropertyChanged(); } }
}
/// <summary>Data.wolf アーカイブが存在するか</summary>
public override bool HasWolfArchive
{
get => _hasWolfArchive;
set
{
if (_hasWolfArchive != value)
{
_hasWolfArchive = value;
OnPropertyChanged();
OnPropertyChanged(nameof(WolfArchiveBadgeVisibility));
OnPropertyChanged(nameof(WolfArchiveBadgeText));
OnPropertyChanged(nameof(WolfArchiveBadgeBackground));
OnPropertyChanged(nameof(WolfArchiveDetailStatusText));
}
}
}
/// <summary>Data.wolf が解凍済み(Dataフォルダが存在)か</summary>
public override bool IsWolfExtracted
{
get => _isWolfExtracted;
set
{
if (_isWolfExtracted != value)
{
_isWolfExtracted = value;
OnPropertyChanged();
OnPropertyChanged(nameof(WolfArchiveBadgeVisibility));
OnPropertyChanged(nameof(WolfArchiveBadgeText));
OnPropertyChanged(nameof(WolfArchiveBadgeBackground));
OnPropertyChanged(nameof(WolfArchiveDetailStatusText));
}
}
}
public Visibility WolfArchiveBadgeVisibility => IsWolf && HasWolfArchive ? Visibility.Visible : Visibility.Collapsed;
public string WolfArchiveBadgeText => IsWolfExtracted ? "Data解凍済" : "Data.wolf保護";
public string WolfArchiveBadgeBackground => IsWolfExtracted ? "#00B894" : "#636E72";
public string WolfArchiveDetailStatusText => IsWolfExtracted
? "Data フォルダに解凍・抽出済みです。ウディタは Data フォルダのマップ・イベント・データベース等を優先して読み込みます。直接ファイルを改造できます。"
: "Data.wolf アーカイブで暗号化・保護されています。下の「Data.wolf を解凍」を実行すると、全データを展開して直接編集・改造可能になります。";
// ================= SRPG Studio関連プロパティ =================
private bool _srpgProxyDll = false;
private double _srpgSpeedMultiplier = 3.0;
/// <summary>SRPG Studio プロキシDLL(version.dll 倍速機能)を適用するか</summary>
public bool SrpgProxyDll
{
get => _srpgProxyDll;
set { if (_srpgProxyDll != value) { _srpgProxyDll = value; OnPropertyChanged(); } }
}
/// <summary>SRPG Studio プロキシDLLのスピード倍率</summary>
public double SrpgSpeedMultiplier
{
get => _srpgSpeedMultiplier;
set { if (_srpgSpeedMultiplier != value) { _srpgSpeedMultiplier = value; OnPropertyChanged(); } }
}
/// <summary>SRPG Studio プラグイン改造オプション(PluginOptionsのエイリアス)</summary>
public ObservableCollection<ModPluginOptionItem> SrpgModOptions => PluginOptions;
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(); } }
}
/// <summary>
/// プリンセスシナジー専用: HP常時MAX(プラグイン "AlwaysMaxHp")の有効状態。
/// PluginSettings に直接マッピングされ、既存の改造適用パイプラインで反映されます。
/// </summary>
public bool PrincessAlwaysMaxHp
{
get => IsPluginEnabled("AlwaysMaxHp", fallbackVal: false);
set => SetPrincessPluginSetting("AlwaysMaxHp", value);
}
/// <summary>
/// プリンセスシナジー専用: MP常時MAX(プラグイン "AlwaysMaxMp")の有効状態。
/// </summary>
public bool PrincessAlwaysMaxMp
{
get => IsPluginEnabled("AlwaysMaxMp", fallbackVal: false);
set => SetPrincessPluginSetting("AlwaysMaxMp", value);
}
/// <summary>
/// プラグイン設定を更新し、関連プロパティの変更通知を発行します。
/// </summary>
private void SetPrincessPluginSetting(string pluginId, bool value)
{
if (_pluginSettings.TryGetValue(pluginId, out var cur) && cur == value)
{
return;
}
_pluginSettings[pluginId] = value;
OnPropertyChanged(pluginId == "AlwaysMaxHp" ? nameof(PrincessAlwaysMaxHp) : nameof(PrincessAlwaysMaxMp));
// 連動して独自の改造設定であることを示す
HasCustomApplyMod = true;
}
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 = "画面右上にボタンを配置し、ゲーム内変数・フラグの閲覧と直接書き換えができるメニューを表示します。" }
];
/// <summary>ツクールVX / VX Ace用スクリプト改造定義一覧</summary>
public static readonly ModPluginDefinition[] DefaultRgssPlugins =
[
new() { Id = "RgssDashSpeedUp", Name = "⚡ 移動速度高速化&常時オートダッシュ", Description = "キャラクターの移動速度を高速化し、Shiftキーを押さなくても常時ダッシュ状態にします。" },
new() { Id = "RgssItemGainMax", Name = "🎁 アイテム入手時 99個固定化", Description = "宝箱・イベント・戦闘等で通常アイテムを入手した際、入手個数を99個にします。" },
new() { Id = "RgssItemNoConsume", Name = "♾️ アイテム消費なし", Description = "アイテムを使用しても所持個数を減少しないようにします。" },
new() { Id = "RgssGoldGainMax", Name = "💰 獲得ゴールド最大化 (999,999G)", Description = "戦闘勝利時の獲得ゴールドを999,999Gにします。" },
new() { Id = "RgssExpGainMax", Name = "📈 獲得経験値最大化 (999,999Exp)", Description = "戦闘勝利時の獲得経験値を999,999Expにします。" },
new() { Id = "RgssBattleTurnRecoverHp", Name = "💖 ターン開始時 全回復 (HP)", Description = "戦闘中の毎ターン開始時にパーティ全員のHPを全回復します。" },
new() { Id = "RgssBattleTurnRecoverMp", Name = "🔷 ターン開始時 全回復 (MP)", Description = "戦闘中の毎ターン開始時にパーティ全員のMPを全回復します。" },
new() { Id = "RgssBattleTurnRecoverTp", Name = "⚡ ターン開始時 全回復 (TP)", Description = "戦闘中の毎ターン開始時にパーティ全員のTPを最大(100)にします。(VX Ace)" },
new() { Id = "RgssMessageInstant", Name = "⏩ メッセージ瞬間表示・高速スキップ", Description = "会話ウィンドウの文字送りウェイトをカットし、瞬間表示します。" },
new() { Id = "RgssCommandMemory", Name = "🧠 コマンド位置記憶 (ツクールMV風)", Description = "メニュー画面や戦闘中のアクターコマンドのカーソル選択位置を記憶して次回遷移時に復元します。" },
new() { Id = "RgssWindowResizeFull", Name = "🖥 ウィンドウをディスプレイに合わせて整数倍拡大 (スクリプト注入)", Description = "ゲーム起動時に論理解像度をディスプレイに収まる最大の整数倍(1x/2x/3x...)へ拡大し、ウィンドウを追従させます。VX AceはGraphics.resize_screen、VX(RGSS2)はWin32APIフォールバックで拡大します。解除で完全復元されます。" },
new() { Id = "RgssWindowResizeExternal", Name = "🪟 外部ツールでウィンドウ拡大 (Win32 API / Sizer等)", Description = "ゲーム側は無改造のまま、ランチャーがゲームウィンドウを検出してディスプレイに収まる最大の整数倍へ拡大します。外部ツールパス設定があればそちらを優先起動します。(既定OFF)" }
];
/// <summary>SRPG Studio用スクリプト改造定義一覧</summary>
public static readonly ModPluginDefinition[] DefaultSrpgPlugins =
[
new() { Id = "SrpgExpBoost", Name = "📈 獲得経験値最大化 (即LvUP / 100Exp固定)", Description = "戦闘やアイテム使用時の獲得経験値を最大(100Exp)にして毎回即座にレベルアップします。" },
new() { Id = "SrpgMaxGold", Name = "💰 所持金最大化 (999,999G)", Description = "自軍ターン開始時および戦闘勝利時に所持金を常に最大(999,999G)に設定します。" },
new() { Id = "SrpgInfDurability", Name = "♾️ 武器・アイテム耐久度無限", Description = "武器やアイテムを使用しても耐久度が減少しないようにします。" },
new() { Id = "SrpgTurnRecoverHp", Name = "💖 自軍ターン開始時 全味方HP全回復", Description = "プレイヤーのターン開始時に生存している全味方ユニットのHPを満タンまで回復します。" },
new() { Id = "SrpgMoveBoost", Name = "👟 味方移動力大幅強化 (+5)", Description = "自軍味方ユニットの基本移動力を+5加算し、広大なマップでも自在に行動できるようにします。" },
new() { Id = "SrpgItemAllDrop", Name = "🎁 敵撃破時アイテム100%ドロップ", Description = "敵ユニットが所持しているドロップ可能アイテムのドロップ率を100%にします。" }
];
public void SyncPluginOptions(IEnumerable<ModPluginDefinition> availablePlugins, Dictionary<string, bool>? defaultSettings = null)
{
_pluginOptions.Clear();
if (EngineType == TkoolEngineType.Wolf)
{
return;
}
IEnumerable<ModPluginDefinition> targetDefs;
if (EngineType == TkoolEngineType.Tyrano)
{
targetDefs = DefaultTyranoPlugins;
}
else if (IsRgss)
{
targetDefs = DefaultRgssPlugins;
}
else if (IsSrpgStudio)
{
targetDefs = DefaultSrpgPlugins;
}
else
{
targetDefs = 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 => "ティラノスクリプト",
TkoolEngineType.VX => "RPGツクールVX",
TkoolEngineType.VXAce => "RPGツクールVX Ace",
TkoolEngineType.Wolf => "WOLF RPGエディター",
TkoolEngineType.SrpgStudio => "SRPG Studio",
_ => "ツクール/ティラノ"
};
}
}
+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.Substring(0, arrayStart + 1);
var inner = content.Substring(arrayStart + 1, arrayEnd - arrayStart - 1);
var suffix = content.Substring(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.Substring(0, cutStart) + content.Substring(end);
}
while (content != prev);
return content;
}
}
}
+482
View File
@@ -0,0 +1,482 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using GameLauncher.Helpers;
using GameLauncher.Models;
namespace GameLauncher.Engines.Tkool
{
/// <summary>
/// ツクールスクリプト改造プラグインの動的検出・適用・復元・管理を行うサービス
/// </summary>
public class TkoolModService
{
/// <summary>バックアップファイルのサフィックス</summary>
public const string BackupSuffix = ".original_launcher_backup";
/// <summary>
/// 過去のバージョンで使用されていたレガシープラグイン名一覧(完全削除・復元互換用)
/// 以前改造されたゲームの検知、復元時のクリーンアップ、新改造適用時の旧ゴミ削除に使用します。
/// </summary>
public static readonly string[] LegacyPluginNames =
[
"SpeedUp",
"Antigravity_GameTweaks",
"DropItem99",
"TurnStartFullRecover",
"BattleTurnRecover",
"MaxGainGold",
"MaxGainExp",
"InstantMessage"
];
private List<ModPluginDefinition> _availablePlugins = [];
/// <summary>現在認識されている利用可能なプラグイン一覧</summary>
public IReadOnlyList<ModPluginDefinition> AvailablePlugins => _availablePlugins;
public TkoolModService()
{
LoadAvailablePlugins();
}
/// <summary>
/// exe と同一階層にある plugins フォルダの物理パスを取得します。
/// </summary>
public static string GetPluginsDirectory()
{
// 1. 実行ファイルと同じ物理ディレクトリ
var exeDir = AppPathHelper.GetExeDirectory();
var primary = Path.Combine(exeDir, "plugins");
if (Directory.Exists(primary))
{
return primary;
}
// 2. 本番配置フォルダ(Z:\自作ソフト\GameLauncher\plugins)
const string prodPath = @"Z:\自作ソフト\GameLauncher\plugins";
if (Directory.Exists(prodPath))
{
return prodPath;
}
// 3. AppContext.BaseDirectory 配下のフォールバック
var baseDir = AppContext.BaseDirectory;
var cand1 = Path.Combine(baseDir, "plugins");
if (Directory.Exists(cand1)) return cand1;
return primary;
}
/// <summary>
/// exe と同階層の plugins フォルダから動的にプラグイン一覧を読み込みます。
/// </summary>
public List<ModPluginDefinition> LoadAvailablePlugins()
{
var list = new List<ModPluginDefinition>();
var pluginsDir = GetPluginsDirectory();
if (Directory.Exists(pluginsDir))
{
foreach (var file in Directory.EnumerateFiles(pluginsDir, "*.js"))
{
try
{
list.Add(ModPluginDefinition.FromFile(file));
}
catch { }
}
}
_availablePlugins = list;
return list;
}
/// <summary>
/// 現在有効なプラグイン名と旧レガシープラグイン名のすべてを合算した除去対象プラグイン名セットを取得します。
/// </summary>
public static HashSet<string> GetAllManagedPluginNames(IEnumerable<ModPluginDefinition>? currentPlugins = null)
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// 過去のレガシープラグイン名をすべて含める
foreach (var leg in LegacyPluginNames)
{
set.Add(leg);
}
// 現在のプラグイン群を含める
if (currentPlugins != null)
{
foreach (var p in currentPlugins)
{
set.Add(p.Id);
}
}
else
{
var dir = GetPluginsDirectory();
if (Directory.Exists(dir))
{
foreach (var file in Directory.EnumerateFiles(dir, "*.js"))
{
set.Add(Path.GetFileNameWithoutExtension(file));
}
}
}
return set;
}
/// <summary>
/// 指定されたゲームに対して、現在のチェック状態に応じた改造の適用または復元を行います。
/// </summary>
public (bool Success, string Message) ApplyOrRestoreMod(TkoolGameItem game, Dictionary<string, bool>? defaultSettings = null)
{
if (string.IsNullOrEmpty(game.PluginsJsPath) || !File.Exists(game.PluginsJsPath))
{
return (false, "plugins.js が見つかりません。");
}
try
{
if (game.ApplyMod)
{
return ApplyMod(game, defaultSettings);
}
else
{
return RestoreOriginal(game);
}
}
catch (Exception ex)
{
return (false, $"スクリプト処理中にエラーが発生しました: {ex.Message}");
}
}
/// <summary>
/// 改造プラグインを適用します。
/// </summary>
public (bool Success, string Message) ApplyMod(TkoolGameItem game, Dictionary<string, bool>? defaultSettings = null)
{
var pluginsJsPath = game.PluginsJsPath;
var pluginsDir = game.PluginsDirPath;
if (string.IsNullOrEmpty(pluginsDir))
{
pluginsDir = Path.Combine(Path.GetDirectoryName(pluginsJsPath)!, "plugins");
game.PluginsDirPath = pluginsDir;
}
if (!Directory.Exists(pluginsDir))
{
Directory.CreateDirectory(pluginsDir);
}
var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var backupPath = Path.Combine(gameBackupDir, "plugins.js" + BackupSuffix);
var legacyBackupPath = pluginsJsPath + BackupSuffix;
// 1. バックアップが存在しない場合、バックアップを作成する (Backups フォルダに保存)
if (!File.Exists(backupPath))
{
if (File.Exists(legacyBackupPath))
{
// 既存のゲーム内バックアップがあれば Backups フォルダへコピー
File.Copy(legacyBackupPath, backupPath, true);
}
else
{
string currentContent = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
// 既に改造プラグイン(新旧問わず)が埋め込まれている場合はクリーンアップしたものをバックアップとして保持
string cleanContent = CleanManagedPluginsFromContent(currentContent);
File.WriteAllText(backupPath, cleanContent, new UTF8Encoding(false));
}
}
// 2. バックアップ(クリーン状態)を元に編集を開始
string baseContent = File.ReadAllText(backupPath, Encoding.UTF8);
// 最新の動的プラグイン一覧を取得
if (_availablePlugins.Count == 0)
{
LoadAvailablePlugins();
}
// 有効化対象のプラグインを取得
var pluginsToEnable = _availablePlugins
.Where(p => game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: true))
.ToList();
// 3. ゲーム側の plugins ディレクトリから不要な旧プラグインや無効プラグインを安全に掃除
var allManaged = GetAllManagedPluginNames(_availablePlugins);
var enabledIds = new HashSet<string>(pluginsToEnable.Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
foreach (var pluginId in allManaged)
{
// 有効対象ではないプラグインファイル(旧プラグインや今回OFFにしたプラグイン)を削除
if (!enabledIds.Contains(pluginId))
{
var targetFile = Path.Combine(pluginsDir, $"{pluginId}.js");
if (File.Exists(targetFile))
{
try { File.Delete(targetFile); } catch { }
}
}
}
// 4. 有効対象のプラグインファイルをゲーム側へ配置
foreach (var plugin in pluginsToEnable)
{
CopyPluginToGame(plugin, pluginsDir);
}
// 5. plugins.js をパース・再構築して有効プラグインを追加
var pluginNamesToAdd = pluginsToEnable.Select(p => p.Id).ToList();
string updatedContent = RebuildPluginsJs(baseContent, pluginNamesToAdd);
// 6. 保存
File.WriteAllText(pluginsJsPath, updatedContent, new UTF8Encoding(false));
game.IsModded = true;
return (true, $"ツクールスクリプト改造を正常に適用しました。(有効プラグイン: {pluginsToEnable.Count}個)");
}
/// <summary>
/// 改造を解除し、ゲームを改造前のオリジナル状態に復元します。
/// 旧レガシープラグインも含めて完全にクリーンアップします。
/// </summary>
public (bool Success, string Message) RestoreOriginal(TkoolGameItem game)
{
var pluginsJsPath = game.PluginsJsPath;
var pluginsDir = game.PluginsDirPath;
var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var backupPath = Path.Combine(gameBackupDir, "plugins.js" + BackupSuffix);
var legacyBackupPath = pluginsJsPath + BackupSuffix;
// 1. バックアップが存在する場合はバックアップから復元(再構築を通すことで壊れたバックアップも修復)
if (File.Exists(backupPath))
{
string backupContent = File.ReadAllText(backupPath, Encoding.UTF8);
string cleanContent = RebuildPluginsJs(backupContent, null);
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
{
// バックアップがなくても、現在の plugins.js から新旧すべての管理プラグインを綺麗に除去
string currentContent = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
string cleanContent = RebuildPluginsJs(currentContent, null);
File.WriteAllText(pluginsJsPath, cleanContent, new UTF8Encoding(false));
}
// 2. ゲーム側の plugins フォルダから新旧すべてのプラグインファイルを安全に削除(ゴミを残さない)
if (!string.IsNullOrEmpty(pluginsDir) && Directory.Exists(pluginsDir))
{
var allManaged = GetAllManagedPluginNames(_availablePlugins);
foreach (var pluginName in allManaged)
{
var targetFile = Path.Combine(pluginsDir, $"{pluginName}.js");
if (File.Exists(targetFile))
{
try { File.Delete(targetFile); } catch { /* 削除不可時は無視 */ }
}
}
}
// 3. ゲームフォルダ内の旧バックアップファイルがあれば削除してBackupsフォルダに一本化
if (File.Exists(legacyBackupPath))
{
try { File.Delete(legacyBackupPath); } catch { }
}
game.IsModded = false;
return (true, "ゲームを改造前のオリジナル状態に正常に復元しました。(旧プラグインも完全削除済み)");
}
/// <summary>
/// plugins.js のテキストから新旧すべての管理対象プラグインの登録記述を除去します。
/// </summary>
public static string CleanManagedPluginsFromContent(string content)
{
return RebuildPluginsJs(content, null);
}
/// <summary>
/// plugins.js の内容を構文レベルで解析し、新旧管理対象プラグインの完全除去および新規追加を行って
/// 正常な JavaScript 配列構文として再構築します。
/// </summary>
public static string RebuildPluginsJs(string content, IReadOnlyList<string>? pluginsToAdd = null)
{
if (string.IsNullOrWhiteSpace(content))
{
return content;
}
int arrayStart = content.IndexOf('[');
int arrayEnd = content.LastIndexOf(']');
if (arrayStart == -1 || arrayEnd == -1 || arrayEnd <= arrayStart)
{
return content;
}
string prefix = content.Substring(0, arrayStart + 1);
string inner = content.Substring(arrayStart + 1, arrayEnd - arrayStart - 1);
string suffix = content.Substring(arrayEnd);
// 新旧すべてのプラグイン名を除去対象とする
var managedSet = GetAllManagedPluginNames();
var keptObjects = new List<string>();
int i = 0;
while (i < inner.Length)
{
// 次のオブジェクト開始 '{' を探す
while (i < inner.Length && inner[i] != '{')
{
i++;
}
if (i >= inner.Length) break;
int objStart = i;
int depth = 0;
bool inString = false;
bool isEscaped = false;
while (i < inner.Length)
{
char c = inner[i];
if (isEscaped)
{
isEscaped = false;
}
else if (c == '\\')
{
if (inString) isEscaped = true;
}
else if (c == '"')
{
inString = !inString;
}
else if (!inString)
{
if (c == '{') depth++;
else if (c == '}')
{
depth--;
if (depth == 0)
{
i++; // '}' を含める
break;
}
}
}
i++;
}
if (depth == 0)
{
string objText = inner.Substring(objStart, i - objStart).Trim();
// このオブジェクトが新旧管理対象プラグインかどうか判定
var match = Regex.Match(objText, @"""name""\s*:\s*""([^""]+)""");
if (match.Success && managedSet.Contains(match.Groups[1].Value))
{
// 管理対象プラグインのため除外
continue;
}
keptObjects.Add(objText);
}
}
// 追加対象のプラグインを登録
if (pluginsToAdd != null)
{
foreach (var pluginName in pluginsToAdd)
{
keptObjects.Add($"{{\"name\":\"{pluginName}\",\"status\":true,\"description\":\"\",\"parameters\":{{}}}}");
}
}
// 綺麗な JavaScript 配列として再構築
var sb = new StringBuilder();
sb.Append(prefix.TrimEnd()).AppendLine();
for (int k = 0; k < keptObjects.Count; k++)
{
sb.Append(keptObjects[k]);
if (k < keptObjects.Count - 1)
{
sb.Append(",");
}
sb.AppendLine();
}
sb.Append(suffix.TrimStart());
return sb.ToString();
}
/// <summary>
/// プラグインファイルをゲーム側の plugins ディレクトリへコピーします。
/// </summary>
private void CopyPluginToGame(ModPluginDefinition plugin, string targetDir)
{
var destinationPath = Path.Combine(targetDir, plugin.FileName);
// 1. 指定ファイルの物理パスからコピー
if (!string.IsNullOrEmpty(plugin.FilePath) && File.Exists(plugin.FilePath))
{
File.Copy(plugin.FilePath, destinationPath, true);
return;
}
// 2. plugins ディレクトリからのコピーを試行
var localPluginPath = Path.Combine(GetPluginsDirectory(), plugin.FileName);
if (File.Exists(localPluginPath))
{
File.Copy(localPluginPath, destinationPath, true);
return;
}
throw new FileNotFoundException($"プラグインファイルが見つかりません: {plugin.FileName} (参照先: {GetPluginsDirectory()})");
}
/// <summary>
/// 現在 plugins.js に改造プラグイン(新旧問わず)が記述されているか判定します。
/// </summary>
public static bool CheckIsModded(string pluginsJsPath)
{
if (string.IsNullOrEmpty(pluginsJsPath) || !File.Exists(pluginsJsPath))
return false;
try
{
string content = File.ReadAllText(pluginsJsPath);
var allManaged = GetAllManagedPluginNames();
foreach (var pluginName in allManaged)
{
if (content.Contains($"\"name\":\"{pluginName}\""))
{
return true;
}
}
}
catch
{
// 読み取り失敗時は false
}
return false;
}
}
}
@@ -0,0 +1,249 @@
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GameLauncher.Engines.Nwjs;
namespace GameLauncher.Engines.Tkool
{
/// <summary>
/// nw.js boxed(exe埋め込み package.nw)等の単体exe梱包ツクールゲームの解析と
/// ゲームフォルダ内 `_extracted` への冪等展開を行うオーケストレーター。
///
/// 役割分担(恒久・再利用可能を目的とした汎用設計):
/// - 本サービス = 抽出の「進行役(オーケストレーター)」。
/// - <see cref="NwjsPackageUnpacker"/> = 組み込みの埋め込みZIPコンテナ検出・展開。
/// - <see cref="NwjsUnpackerToolProvider"/> = 外部アンパッカーの取得・呼び出し。
///
/// 展開戦略(順に試行):
/// 1. 組み込みZIP展開: exe内の標準ZIPコンテナ(package.nw)を検出して展開。
/// 2. 外部ツール委譲: Tools\ 配下の外部アンパッカー(未配置なら自動取得)へ委譲。
///
/// 設計方針:
/// - 1.14GB級exeを対象に含むため、組み込み検出は限定/逐次走査で行う。
/// - 展開はゲームフォルダ内 `_extracted` のみ。他ゲームへは一切影響しない。
/// - 冪等: 展開済み(plugins.js 存在)なら再展開しない。
/// - 既存公開API(GetExtractedDir / ContainsPackageNwMarker / IsExtractionComplete /
/// ExeBackupSuffix / ExtractPackageNw)のシグネチャは維持し、後方互換を壊さない。
/// </summary>
public sealed class TkoolPackagedExtractionService
{
/// <summary>ゲームフォルダ内の展開先フォルダ名(Asar/SRPG の慣習に合わせる)</summary>
public const string ExtractedDirName = NwjsPackageUnpacker.ExtractedDirName;
/// <summary>exe内コンテナ改変時のバックアップ拡張子</summary>
public const string ExeBackupSuffix = ".glbak";
/// <summary>展開戦略の種別。将来の新形式追加を見据え、列挙型で差し替え可能にする。</summary>
public enum UnpackStrategy
{
/// <summary>組み込みの埋め込みZIPコンテナ検出・展開</summary>
BuiltInZip = 0,
/// <summary>外部アンパッカーへの委譲</summary>
ExternalTool = 1,
}
/// <summary>ゲームフォルダ内の展開先ディレクトリ(物理パス)</summary>
public static string GetExtractedDir(string gameRootDir)
=> NwjsPackageUnpacker.GetExtractedDir(gameRootDir);
/// <summary>
/// exeに package.nw マーカーが含まれるかを限定部分読み(4MB窓×数点)で判定します。
/// 全走査は行いません(1.14GB級exe対策)。
/// </summary>
public static bool ContainsPackageNwMarker(string exePath)
{
try
{
const int windowSize = 4 * 1024 * 1024;
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
long size = fs.Length;
if (size < 1024)
{
return false;
}
double[] fractions = { 0.25, 0.5, 0.75, 0.9 };
foreach (var frac in fractions)
{
long start = (long)(size * frac);
int readLen = (int)Math.Min(windowSize, size - start);
if (readLen <= 0)
{
continue;
}
var buf = new byte[readLen];
fs.Seek(start, SeekOrigin.Begin);
int read = fs.Read(buf, 0, buf.Length);
var text = System.Text.Encoding.ASCII.GetString(buf, 0, read);
if (text.IndexOf("package.nw", StringComparison.Ordinal) >= 0 ||
text.IndexOf("package.json", StringComparison.Ordinal) >= 0)
{
return true;
}
}
}
catch { }
return false;
}
/// <summary>
/// exe内ZIPのローカルヘッダ(PK\x03\x04)offsetを限定ウィンドウで検出します。
/// exe先頭の自己展開部を除いた中盤以降のみを対象にし、全走査を避けます。
/// </summary>
public static long? FindEmbeddedZipOffset(string exePath, long searchStart = 0, int windowBytes = 8 * 1024 * 1024)
{
try
{
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
long size = fs.Length;
// searchStart が 0 の場合は中盤〜後半(package.nw は後半に置かれる傾向)のみを走査
double[] fractions = searchStart > 0 ? new[] { (double)searchStart / Math.Max(1, size) } : new[] { 0.5, 0.65, 0.8, 0.9 };
foreach (var frac in fractions)
{
long start = (long)(size * frac);
int readLen = (int)Math.Min(windowBytes, size - start);
if (readLen <= 4)
{
continue;
}
var buf = new byte[readLen];
fs.Seek(start, SeekOrigin.Begin);
int read = fs.Read(buf, 0, buf.Length);
for (int i = 0; i < read - 3; i++)
{
if (buf[i] == 0x50 && buf[i + 1] == 0x4B && buf[i + 2] == 0x03 && buf[i + 3] == 0x04)
{
return start + i;
}
}
}
}
catch { }
return null;
}
/// <summary>
/// 既存 `_extracted` が完全か(plugins.js が存在するか)を判定します。
/// </summary>
public static bool IsExtractionComplete(string extractedDir, out string? pluginsJsPath)
=> NwjsPackageUnpacker.IsExtractionComplete(extractedDir, out pluginsJsPath, out _);
/// <summary>
/// exe内ZIP(package.nw 等)をゲームフォルダ内 `_extracted` へ冪等に全展開し、
/// 展開後の js/plugins.js(相対パス)を返します。展開できなければ null。
///
/// 展開戦略を順に試行します: 組み込みZIP展開 → 外部ツール委譲。
/// 後方互換のため同期シグネチャを維持します(外部ツールの自動取得は内部で同期待機)。
/// </summary>
public string? ExtractPackageNw(string exePath, string gameRoot, out string extractedDir, IProgress<string>? progress = null)
{
extractedDir = GetExtractedDir(gameRoot);
try
{
if (!File.Exists(exePath))
{
return null;
}
// 冪等: 展開済みならスキップ
if (Directory.Exists(extractedDir) && IsExtractionComplete(extractedDir, out _))
{
progress?.Report("既に展開済みです(_extracted を再利用)。");
return NwjsPackageUnpacker.IsExtractionComplete(extractedDir, out _, out var rel) ? rel : "js/plugins.js";
}
// 戦略1: 組み込みZIP展開
progress?.Report("展開戦略: 組み込みZIP展開を試行します。");
var relBuiltin = NwjsPackageUnpacker.ExtractEmbeddedZip(exePath, extractedDir, progress);
if (relBuiltin != null)
{
return relBuiltin;
}
// 戦略2: 外部ツール委譲
progress?.Report("展開戦略: 外部アンパッカーへの委譲を試行します。");
var relExternal = ExtractViaExternalTool(exePath, extractedDir, progress);
if (relExternal != null)
{
return relExternal;
}
progress?.Report("展開できませんでした(起動のみ対応)。");
return null;
}
catch (Exception ex)
{
progress?.Report($"展開処理中にエラーが発生しました: {ex.Message}");
return null;
}
}
/// <summary>
/// 外部アンパッカー(未配置なら自動取得)で exe 内コンテナを `_extracted` へ展開します。
/// 失敗(ネット未接続等)時は例外を投げず null を返し、呼び出し側で「起動のみ」へフォールバックさせます。
/// </summary>
private static string? ExtractViaExternalTool(string exePath, string extractedDir, IProgress<string>? progress)
{
try
{
// 外部ツールの可用性確保(初回は自動ダウンロード)。同期待機で取得。
var available = NwjsUnpackerToolProvider.IsToolAvailable()
|| Task.Run(() => NwjsUnpackerToolProvider.EnsureToolAvailableAsync(progress)).GetAwaiter().GetResult();
if (!available)
{
progress?.Report("外部アンパッカーを取得できませんでした(ネット未接続等)。起動のみ対応へフォールバックします。");
return null;
}
var tool = NwjsUnpackerToolProvider.GetToolPath();
if (tool == null)
{
return null;
}
// 展開先を一旦クリーンにする(部分展開の混在を避ける)
try
{
if (Directory.Exists(extractedDir))
{
Directory.Delete(extractedDir, recursive: true);
}
}
catch { }
if (!NwjsUnpackerToolProvider.ExtractWithExternalTool(tool, exePath, extractedDir, progress))
{
return null;
}
// 展開結果から plugins.js を解決
var plugins = NwjsPackageUnpacker.ResolvePluginsJs(extractedDir);
if (plugins == null)
{
progress?.Report("展開は完了しましたが、js/plugins.js が見つかりませんでした。");
return null;
}
var rel = Path.GetRelativePath(extractedDir, plugins).Replace(Path.DirectorySeparatorChar, '/');
progress?.Report($"外部アンパッカーでの展開が完了しました: {rel}");
return rel;
}
catch (Exception ex)
{
progress?.Report($"外部アンパッカー委譲でエラーが発生しました: {ex.Message}");
return null;
}
}
}
}
+378
View File
@@ -0,0 +1,378 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using GameLauncher.Helpers;
using GameLauncher.Models;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Nwjs;
using GameLauncher.Engines.Unity;
namespace GameLauncher.Engines.Tyrano
{
/// <summary>
/// ティラノスクリプトゲームの個別改造設定オプション
/// </summary>
public class TyranoModOptions
{
public bool UnlockAllCg { get; set; } = true;
public bool FastMessage { get; set; } = true;
public bool EnableDevTools { get; set; } = true;
public bool ShowCheatMenu { get; set; } = true;
}
/// <summary>
/// ティラノスクリプト(TyranoScript)ゲームのMOD適用・解除・管理を行うサービス
/// </summary>
public class TyranoModService
{
public const string ModScriptFileName = "tyrano_launcher_mod.js";
public const string IndexBackupSuffix = ".original_launcher_backup";
/// <summary>
/// index.html に改造スクリプトが適用されているかどうか判定します。
/// </summary>
public static bool CheckIsModded(string indexPath)
{
if (string.IsNullOrEmpty(indexPath))
return false;
string extPath = AsarArchiveService.ToExtendedPath(indexPath);
if (!File.Exists(extPath))
return false;
try
{
string content = File.ReadAllText(extPath);
return content.Contains(ModScriptFileName);
}
catch
{
return false;
}
}
/// <summary>
/// ティラノスクリプトゲームに改造スクリプトを適用します。
/// </summary>
public (bool Success, string Message) ApplyMod(TkoolGameItem game, Dictionary<string, bool>? pluginSettings)
{
var rawIndexPath = game.PluginsJsPath; // ティラノの場合は index.html パス
if (string.IsNullOrEmpty(rawIndexPath))
{
return (false, "index.html が見つかりません。ASARを解凍してください。");
}
var indexPath = AsarArchiveService.ToExtendedPath(rawIndexPath);
if (!File.Exists(indexPath))
{
return (false, "index.html が見つかりません。ASARを解凍してください。");
}
try
{
var dir = Path.GetDirectoryName(indexPath)!;
var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var backupPath = Path.Combine(gameBackupDir, "index.html" + IndexBackupSuffix);
var legacyBackupPath = indexPath + IndexBackupSuffix;
// 1. バックアップの作成(存在しない場合、Backups フォルダに保存)
if (!File.Exists(backupPath))
{
if (File.Exists(legacyBackupPath))
{
File.Copy(legacyBackupPath, backupPath, true);
}
else
{
string originalContent = File.ReadAllText(indexPath, Encoding.UTF8);
// 既にタグが含まれていた場合は除去したものをバックアップとする
string cleanContent = RemoveScriptTag(originalContent);
File.WriteAllText(backupPath, cleanContent, new UTF8Encoding(false));
}
}
// 2. 有効化する機能の判定
bool unlockCg = game.IsPluginEnabled("TyranoUnlockAllCg", pluginSettings, fallbackVal: true);
bool fastMsg = game.IsPluginEnabled("TyranoFastMessage", pluginSettings, fallbackVal: true);
bool devTools = game.IsPluginEnabled("TyranoDevTools", pluginSettings, fallbackVal: true);
bool cheatMenu = game.IsPluginEnabled("TyranoCheatMenu", pluginSettings, fallbackVal: true);
// 3. tyrano_launcher_mod.js を生成して配置
string modJsContent = BuildModScript(unlockCg, fastMsg, devTools, cheatMenu);
string modJsPath = Path.Combine(dir, ModScriptFileName);
File.WriteAllText(modJsPath, modJsContent, new UTF8Encoding(false));
// 4. index.html にスクリプトタグを注入
string baseContent = File.ReadAllText(backupPath, Encoding.UTF8);
string injectedContent = InjectScriptTag(baseContent);
File.WriteAllText(indexPath, injectedContent, new UTF8Encoding(false));
game.IsModded = true;
return (true, "ティラノスクリプト用改造を正常に適用しました。(全CG解放/高速化/DevTools/チートメニュー)");
}
catch (Exception ex)
{
return (false, $"ティラノ改造適用中にエラーが発生しました: {ex.Message}");
}
}
/// <summary>
/// ティラノスクリプトゲームの改造を解除し、元のオリジナル状態に復元します。
/// </summary>
public (bool Success, string Message) RestoreOriginal(TkoolGameItem game)
{
var rawIndexPath = game.PluginsJsPath;
if (string.IsNullOrEmpty(rawIndexPath))
{
return (false, "index.html のパスが設定されていません。");
}
var indexPath = AsarArchiveService.ToExtendedPath(rawIndexPath);
try
{
var dir = Path.GetDirectoryName(indexPath)!;
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);
// 1. index.html の復元 (Backups フォルダを優先)
if (File.Exists(backupPath))
{
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))
{
string content = File.ReadAllText(indexPath, Encoding.UTF8);
string clean = RemoveScriptTag(content);
File.WriteAllText(indexPath, clean, new UTF8Encoding(false));
}
// ゲームフォルダ内の旧バックアップがあれば削除
if (File.Exists(legacyBackupPath))
{
try { File.Delete(legacyBackupPath); } catch { }
}
// 2. tyrano_launcher_mod.js の削除
if (File.Exists(modJsPath))
{
try { File.Delete(modJsPath); } catch { }
}
game.IsModded = false;
return (true, "ティラノスクリプトの改造を解除し、オリジナル状態に復元しました。");
}
catch (Exception ex)
{
return (false, $"復元中にエラーが発生しました: {ex.Message}");
}
}
private static string InjectScriptTag(string html)
{
string tag = $"<script type=\"text/javascript\" src=\"./{ModScriptFileName}\"></script>";
if (html.Contains(ModScriptFileName))
{
return html;
}
if (html.Contains("</body>", StringComparison.OrdinalIgnoreCase))
{
return Regex.Replace(html, @"(</body>)", tag + "\n$1", RegexOptions.IgnoreCase);
}
else if (html.Contains("</html>", StringComparison.OrdinalIgnoreCase))
{
return Regex.Replace(html, @"(</html>)", tag + "\n$1", RegexOptions.IgnoreCase);
}
return html + "\n" + tag;
}
private static string RemoveScriptTag(string html)
{
return Regex.Replace(html, @"<script[^>]*src=""\./" + Regex.Escape(ModScriptFileName) + @"""[^>]*></script>\r?\n?", "", RegexOptions.IgnoreCase);
}
private static string BuildModScript(bool unlockCg, bool fastMessage, bool devTools, bool cheatMenu)
{
var sb = new StringBuilder();
sb.AppendLine("/* =============================================================== */");
sb.AppendLine("/* GameLauncher - TyranoScript Mod Plugin */");
sb.AppendLine("/* =============================================================== */");
sb.AppendLine("(function() {");
sb.AppendLine(" 'use strict';");
sb.AppendLine(" console.log('[GameLauncher] TyranoScript Mod active.');");
// 1. DevTools
if (devTools)
{
sb.AppendLine(@"
// F12キーで開発者ツールを開く
window.addEventListener('keydown', function(e) {
if (e.key === 'F12') {
try {
if (typeof require !== 'undefined') {
var electron = require('electron');
var remote = electron.remote || (electron.remote ? electron.remote : null);
var win = remote ? remote.getCurrentWindow() : null;
if (win && win.webContents) {
if (win.webContents.isDevToolsOpened()) win.webContents.closeDevTools();
else win.webContents.openDevTools({ mode: 'detach' });
}
} else if (typeof nw !== 'undefined') {
nw.Window.get().showDevTools();
}
} catch (err) {
console.warn('[GameLauncher] DevTools open failed:', err);
}
}
});");
}
sb.AppendLine(@"
function onTyranoReady() {
if (!window.TYRANO || !window.TYRANO.kag) {
setTimeout(onTyranoReady, 100);
return;
}
var kag = window.TYRANO.kag;
console.log('[GameLauncher] TYRANO.kag detected.');");
// 2. FastMessage
if (fastMessage)
{
sb.AppendLine(@"
// メッセージ高速化・ウェイト短縮
try {
if (kag.config) {
kag.config.defaultAutoSpeed = 10;
kag.config.defaultSkipSpeed = 5;
}
if (kag.stat && kag.stat.ch_speed !== undefined) {
kag.stat.ch_speed = 0;
}
if (kag.ftag && kag.ftag.master_tag && kag.ftag.master_tag.wait) {
var origWait = kag.ftag.master_tag.wait.start;
kag.ftag.master_tag.wait.start = function(pm) {
if (pm && pm.time) pm.time = Math.min(pm.time, 50);
return origWait.apply(this, arguments);
};
}
} catch (e) {
console.warn('[GameLauncher] FastMessage hook error:', e);
}");
}
// 3. UnlockAllCg
if (unlockCg)
{
sb.AppendLine(@"
// 全CG・全回想フラグの全開放
try {
function unlockFlags() {
if (kag.variable && kag.variable.sf) {
var sf = kag.variable.sf;
for (var key in sf) {
if (sf.hasOwnProperty(key)) {
var val = sf[key];
if (typeof val === 'object' && val !== null) {
for (var sub in val) {
if (val.hasOwnProperty(sub)) {
if (typeof val[sub] === 'boolean') val[sub] = true;
else if (typeof val[sub] === 'number' && val[sub] === 0) val[sub] = 1;
}
}
}
}
}
console.log('[GameLauncher] System variables (sf) unlocked for CG/scenes.');
}
}
setTimeout(unlockFlags, 1000);
setTimeout(unlockFlags, 3000);
} catch (e) {
console.warn('[GameLauncher] UnlockAllCg error:', e);
}");
}
// 4. CheatMenu
if (cheatMenu)
{
sb.AppendLine(@"
// 画面上フローティングチートメニュー
try {
var btn = document.createElement('div');
btn.innerHTML = '⚙ チート';
btn.style.cssText = 'position:fixed;top:10px;right:10px;z-index:999999;background:rgba(20,20,30,0.85);color:#00B894;padding:6px 12px;border-radius:6px;font-size:12px;cursor:pointer;border:1px solid #00B894;font-family:sans-serif;user-select:none;font-weight:bold;box-shadow:0 2px 6px rgba(0,0,0,0.5);';
var modal = document.createElement('div');
modal.style.cssText = 'display:none;position:fixed;top:45px;right:10px;width:340px;max-height:480px;background:rgba(24,24,32,0.96);border:1px solid #555;border-radius:8px;z-index:999999;padding:12px;overflow-y:auto;color:#E0E0E6;font-size:12px;font-family:sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.7);';
btn.onclick = function() {
if (modal.style.display === 'none') {
renderVars();
modal.style.display = 'block';
} else {
modal.style.display = 'none';
}
};
function renderVars() {
modal.innerHTML = '<div style=""font-weight:bold;margin-bottom:8px;border-bottom:1px solid #444;padding-bottom:4px;display:flex;justify-content:space-between;""><span>🎮 ゲーム内変数 (f) エディタ</span><span id=""_tkl_close"" style=""cursor:pointer;color:#bbb;"">✕</span></div><div id=""_tkl_list""></div>';
document.getElementById('_tkl_close').onclick = function() { modal.style.display = 'none'; };
var list = document.getElementById('_tkl_list');
var f = (kag.stat && kag.stat.f) ? kag.stat.f : (kag.variable ? kag.variable.f : null);
if (!f || Object.keys(f).length === 0) {
list.innerHTML = '<div style=""color:#888;"">変数(f)が見つかりません。ゲームを開始してからお試しください。</div>';
return;
}
for (var k in f) {
if (!f.hasOwnProperty(k)) continue;
var val = f[k];
if (typeof val === 'number' || typeof val === 'string' || typeof val === 'boolean') {
(function(key, currentVal) {
var row = document.createElement('div');
row.style.cssText = 'display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;';
var nameSpan = document.createElement('span');
nameSpan.innerText = key;
nameSpan.style.cssText = 'max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#FAB1A0;';
var input = document.createElement('input');
input.value = currentVal;
input.style.cssText = 'width:120px;background:#16161E;color:#fff;border:1px solid #444;border-radius:4px;padding:2px 4px;font-size:11px;';
input.onchange = function() {
var n = Number(input.value);
f[key] = isNaN(n) ? input.value : n;
console.log('[GameLauncher] Updated f.' + key + ' =', f[key]);
};
row.appendChild(nameSpan);
row.appendChild(input);
list.appendChild(row);
})(k, val);
}
}
}
document.body.appendChild(btn);
document.body.appendChild(modal);
} catch (e) {
console.warn('[GameLauncher] CheatMenu error:', e);
}");
}
sb.AppendLine(" }");
sb.AppendLine(" setTimeout(onTyranoReady, 300);");
sb.AppendLine("})();");
return sb.ToString();
}
}
}
+86
View File
@@ -0,0 +1,86 @@
namespace GameLauncher.Engines.Unity
{
/// <summary>
/// ゲームエンジンの大分類
/// </summary>
public enum GameEngineKind
{
Tkool,
Tyrano,
Unity,
Wolf,
SrpgStudio
}
/// <summary>
/// エンジンの種類
/// </summary>
public enum TkoolEngineType
{
MV,
MZ,
Tyrano,
VX,
VXAce,
Wolf,
SrpgStudio,
Unknown
}
/// <summary>
/// Unityのビルドバックエンド形式
/// </summary>
public enum UnityBackendType
{
Unknown = 0,
Mono = 1,
IL2CPP = 2
}
/// <summary>
/// ゲーム一覧のソート順
/// </summary>
public enum GameSortOrder
{
LastLaunchedDesc = 0, // 最終実行 (新しい順)
LastLaunchedAsc = 1, // 最終実行 (古い順)
FolderLastModifiedDesc = 2, // フォルダ更新日時 (新しい順)
FolderLastModifiedAsc = 3, // フォルダ更新日時 (古い順)
TitleAsc = 4, // タイトル (昇順)
TitleDesc = 5, // タイトル (降順)
FolderNameAsc = 6 // フォルダ名 (昇順)
}
/// <summary>
/// セーブデータの格納ソース種別
/// </summary>
public enum SaveSourceType
{
RegistryPlayerPrefs = 0,
LocalLowFile = 1,
GameFolderFile = 2
}
/// <summary>
/// PlayerPrefs値のデータ型
/// </summary>
public enum PlayerPrefsType
{
Int = 0,
Float = 1,
String = 2,
Binary = 3
}
/// <summary>
/// セーブデータコーデック種別
/// </summary>
public enum SaveCodecType
{
RawText = 0,
Json = 1,
EasySave3 = 2,
YurisSave = 3,
Binary = 4
}
}
+134
View File
@@ -0,0 +1,134 @@
using System;
using System.IO;
using GameLauncher.Models;
namespace GameLauncher.Engines.Unity
{
/// <summary>
/// Unityゲームのデータモデル
/// </summary>
public class UnityGameItem : GameItemBase
{
private string _dataDirectoryPath = string.Empty;
private string _companyName = string.Empty;
private string _productName = string.Empty;
private UnityBackendType _backendType = UnityBackendType.Unknown;
private string _unityVersion = string.Empty;
private bool _hasSaveData;
public override GameEngineKind EngineKind => GameEngineKind.Unity;
/// <summary>[Game]_Data ディレクトリ絶対パス</summary>
public string DataDirectoryPath
{
get => _dataDirectoryPath;
set { if (_dataDirectoryPath != value) { _dataDirectoryPath = value; OnPropertyChanged(); } }
}
/// <summary>app.info 由来の会社名/開発者名</summary>
public string CompanyName
{
get => _companyName;
set
{
if (_companyName != value)
{
_companyName = value;
OnPropertyChanged();
OnPropertyChanged(nameof(RegistryPath));
OnPropertyChanged(nameof(LocalLowPath));
}
}
}
/// <summary>app.info 由来の製品名</summary>
public string ProductName
{
get => _productName;
set
{
if (_productName != value)
{
_productName = value;
OnPropertyChanged();
OnPropertyChanged(nameof(RegistryPath));
OnPropertyChanged(nameof(LocalLowPath));
}
}
}
public override bool IsIL2CPP => BackendType == UnityBackendType.IL2CPP;
public override bool IsMono => BackendType == UnityBackendType.Mono;
/// <summary>バックエンド形式 (IL2CPP / Mono)</summary>
public UnityBackendType BackendType
{
get => _backendType;
set
{
if (_backendType != value)
{
_backendType = value;
OnPropertyChanged();
OnPropertyChanged(nameof(BackendBadgeText));
OnPropertyChanged(nameof(IsIL2CPP));
OnPropertyChanged(nameof(IsMono));
}
}
}
/// <summary>Unityバージョン文字列</summary>
public override string UnityVersion
{
get => _unityVersion;
set { if (_unityVersion != value) { _unityVersion = value; OnPropertyChanged(); } }
}
/// <summary>セーブデータ(レジストリまたはファイル)が検出されたかどうか</summary>
public override bool HasSaveData
{
get => _hasSaveData;
set { if (_hasSaveData != value) { _hasSaveData = value; OnPropertyChanged(); } }
}
/// <summary>
/// レジストリ (PlayerPrefs) のキーパス
/// HKCU\Software\[CompanyName]\[ProductName]
/// </summary>
public override string RegistryPath
{
get
{
if (string.IsNullOrEmpty(CompanyName) || string.IsNullOrEmpty(ProductName))
return string.Empty;
return $@"Software\{CompanyName}\{ProductName}";
}
}
/// <summary>
/// LocalLow のセーブデータ保存ディレクトリ
/// %USERPROFILE%\AppData\LocalLow\[CompanyName]\[ProductName]
/// </summary>
public override string LocalLowPath
{
get
{
if (string.IsNullOrEmpty(CompanyName) || string.IsNullOrEmpty(ProductName))
return string.Empty;
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var appData = Path.GetDirectoryName(localAppData);
if (string.IsNullOrEmpty(appData)) return string.Empty;
return Path.Combine(appData, "LocalLow", CompanyName, ProductName);
}
}
public override string BackendBadgeText => BackendType switch
{
UnityBackendType.IL2CPP => "IL2CPP",
UnityBackendType.Mono => "Mono",
_ => "Unity"
};
}
}
+177
View File
@@ -0,0 +1,177 @@
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using GameLauncher.Models;
namespace GameLauncher.Engines.Unity
{
/// <summary>
/// PlayerPrefs(レジストリ)の1エントリを表すモデル
/// </summary>
public class PlayerPrefsEntry : INotifyPropertyChanged
{
private string _rawKey = string.Empty;
private string _cleanKey = string.Empty;
private PlayerPrefsType _type = PlayerPrefsType.Int;
private object? _value;
private string _editValue = string.Empty;
private bool _isModified;
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>レジストリの生キー名(例: ClearedLevel_h1378399435)</summary>
public string RawKey
{
get => _rawKey;
set { if (_rawKey != value) { _rawKey = value; OnPropertyChanged(); } }
}
/// <summary>Unityのハッシュを除去した整形式キー名(例: ClearedLevel)</summary>
public string CleanKey
{
get => _cleanKey;
set { if (_cleanKey != value) { _cleanKey = value; OnPropertyChanged(); } }
}
/// <summary>値のデータ型</summary>
public PlayerPrefsType Type
{
get => _type;
set { if (_type != value) { _type = value; OnPropertyChanged(); OnPropertyChanged(nameof(TypeDisplay)); } }
}
/// <summary>実際の値(int, float, string, byte[])</summary>
public object? Value
{
get => _value;
set
{
if (!Equals(_value, value))
{
_value = value;
OnPropertyChanged();
UpdateEditValue();
}
}
}
/// <summary>UI表示・編集用の文字列値</summary>
public string EditValue
{
get => _editValue;
set
{
if (_editValue != value)
{
_editValue = value;
_isModified = true;
OnPropertyChanged();
OnPropertyChanged(nameof(IsModified));
}
}
}
/// <summary>値が変更されたかどうか</summary>
public bool IsModified
{
get => _isModified;
set { if (_isModified != value) { _isModified = value; OnPropertyChanged(); } }
}
public string TypeDisplay => Type switch
{
PlayerPrefsType.Int => "Int (数値)",
PlayerPrefsType.Float => "Float (小数)",
PlayerPrefsType.String => "String (文字列)",
PlayerPrefsType.Binary => "Binary (バイナリ)",
_ => "Unknown"
};
private void UpdateEditValue()
{
if (_value == null)
{
_editValue = string.Empty;
}
else if (_value is byte[] bytes)
{
try
{
var text = System.Text.Encoding.UTF8.GetString(bytes).TrimEnd('\0');
if (text.All(c => !char.IsControl(c) || c == '\r' || c == '\n' || c == '\t'))
{
_editValue = text;
_type = PlayerPrefsType.String;
return;
}
}
catch { }
if (bytes.Length == 4)
{
float f = BitConverter.ToSingle(bytes, 0);
if (!float.IsNaN(f) && !float.IsInfinity(f))
{
_editValue = f.ToString("G");
_type = PlayerPrefsType.Float;
return;
}
}
_editValue = BitConverter.ToString(bytes).Replace("-", " ");
}
else
{
_editValue = _value.ToString() ?? string.Empty;
}
_isModified = false;
OnPropertyChanged(nameof(EditValue));
OnPropertyChanged(nameof(IsModified));
}
}
/// <summary>
/// ディスク上のセーブファイル(LocalLow または ゲームフォルダ内)を表すモデル
/// </summary>
public class SaveFileEntry
{
public string FileName { get; set; } = string.Empty;
public string FilePath { get; set; } = string.Empty;
public long FileSize { get; set; }
public DateTime LastModified { get; set; }
public string LocationType { get; set; } = string.Empty; // "LocalLow" または "ゲームフォルダ"
public bool IsTextOrJson { get; set; }
public string FileSizeDisplay
{
get
{
if (FileSize < 1024) return $"{FileSize} B";
if (FileSize < 1024 * 1024) return $"{FileSize / 1024.0:F1} KB";
return $"{FileSize / (1024.0 * 1024.0):F2} MB";
}
}
public string LastModifiedDisplay => LastModified.ToString("yyyy/MM/dd HH:mm:ss");
}
/// <summary>
/// セーブデータのバックアップ履歴モデル
/// </summary>
public class SaveBackupEntry
{
public string Name { get; set; } = string.Empty;
public string BackupPath { get; set; } = string.Empty;
public DateTime Timestamp { get; set; }
public string BackupType { get; set; } = string.Empty; // "Registry (.reg)" または "ファイル"
public string Note { get; set; } = string.Empty;
public string TimestampDisplay => Timestamp.ToString("yyyy/MM/dd HH:mm:ss");
}
}
+683
View File
@@ -0,0 +1,683 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using GameLauncher.Helpers;
using GameLauncher.Models;
namespace GameLauncher.Engines.Unity
{
/// <summary>
/// UnityのPlayerPrefs(レジストリ)およびセーブファイル(LocalLow / ゲームフォルダ)の編集・バックアップを行うサービス
/// </summary>
public class UnitySaveManagerService
{
// ====================================================================
// 1. PlayerPrefs (レジストリ) 管理機能
// ====================================================================
/// <summary>
/// レジストリ(HKCU\Software\[CompanyName]\[ProductName])からPlayerPrefsエントリ一覧を取得します。
/// </summary>
public List<PlayerPrefsEntry> GetPlayerPrefs(string registryPath)
{
var list = new List<PlayerPrefsEntry>();
if (string.IsNullOrEmpty(registryPath)) return list;
try
{
using var key = Registry.CurrentUser.OpenSubKey(registryPath, writable: false);
if (key == null) return list;
var valueNames = key.GetValueNames();
foreach (var name in valueNames)
{
try
{
var kind = key.GetValueKind(name);
var rawValue = key.GetValue(name);
// キー名から "_h[数字]" のハッシュサフィックスを抽出・除去
string cleanKey = name;
var match = Regex.Match(name, @"^(.*)_h\d+$");
if (match.Success)
{
cleanKey = match.Groups[1].Value;
}
PlayerPrefsType type = PlayerPrefsType.Int;
if (kind == RegistryValueKind.DWord)
{
type = PlayerPrefsType.Int;
}
else if (kind == RegistryValueKind.String)
{
type = PlayerPrefsType.String;
}
else if (kind == RegistryValueKind.Binary)
{
type = PlayerPrefsType.Binary;
}
var entry = new PlayerPrefsEntry
{
RawKey = name,
CleanKey = cleanKey,
Type = type,
Value = rawValue
};
list.Add(entry);
}
catch { }
}
}
catch { }
// キー名昇順でソート
return list.OrderBy(e => e.CleanKey, StringComparer.OrdinalIgnoreCase).ToList();
}
/// <summary>
/// PlayerPrefsのエントリ値をレジストリに更新保存します。
/// </summary>
public bool SavePlayerPref(string registryPath, PlayerPrefsEntry entry)
{
if (string.IsNullOrEmpty(registryPath) || string.IsNullOrEmpty(entry.RawKey))
return false;
try
{
using var key = Registry.CurrentUser.CreateSubKey(registryPath, writable: true);
if (key == null) return false;
switch (entry.Type)
{
case PlayerPrefsType.Int:
if (int.TryParse(entry.EditValue, out int intVal))
{
key.SetValue(entry.RawKey, intVal, RegistryValueKind.DWord);
entry.Value = intVal;
entry.IsModified = false;
return true;
}
break;
case PlayerPrefsType.Float:
if (float.TryParse(entry.EditValue, out float floatVal))
{
// UnityのPlayerPrefsではfloatは4バイトバイナリとして格納される
byte[] floatBytes = BitConverter.GetBytes(floatVal);
key.SetValue(entry.RawKey, floatBytes, RegistryValueKind.Binary);
entry.Value = floatBytes;
entry.IsModified = false;
return true;
}
break;
case PlayerPrefsType.String:
// 文字列として直接格納するか、UTF-8バイト列(末尾0)として格納
// 既存のレジストリ型に合わせる
var existingKind = RegistryValueKind.Unknown;
try { existingKind = key.GetValueKind(entry.RawKey); } catch { }
if (existingKind == RegistryValueKind.Binary)
{
var bytes = Encoding.UTF8.GetBytes(entry.EditValue + "\0");
key.SetValue(entry.RawKey, bytes, RegistryValueKind.Binary);
entry.Value = bytes;
}
else
{
key.SetValue(entry.RawKey, entry.EditValue, RegistryValueKind.String);
entry.Value = entry.EditValue;
}
entry.IsModified = false;
return true;
case PlayerPrefsType.Binary:
// Hex文字列のパース(例: "AA BB CC" または "AABBCC")
var hexClean = entry.EditValue.Replace(" ", "").Replace("-", "");
if (hexClean.Length % 2 == 0)
{
byte[] rawBytes = Convert.FromHexString(hexClean);
key.SetValue(entry.RawKey, rawBytes, RegistryValueKind.Binary);
entry.Value = rawBytes;
entry.IsModified = false;
return true;
}
break;
}
}
catch { }
return false;
}
/// <summary>
/// PlayerPrefsに新規キーを追加します。
/// </summary>
public bool AddPlayerPref(string registryPath, string keyName, PlayerPrefsType type, string value, out string outRawKey)
{
outRawKey = string.Empty;
if (string.IsNullOrEmpty(registryPath) || string.IsNullOrWhiteSpace(keyName))
return false;
try
{
// Unityハッシュの付加
uint hash = CalculateUnityHash(keyName);
string rawKey = $"{keyName}_h{hash}";
outRawKey = rawKey;
using var key = Registry.CurrentUser.CreateSubKey(registryPath, writable: true);
if (key == null) return false;
switch (type)
{
case PlayerPrefsType.Int:
int.TryParse(value, out int intVal);
key.SetValue(rawKey, intVal, RegistryValueKind.DWord);
return true;
case PlayerPrefsType.Float:
float.TryParse(value, out float floatVal);
byte[] floatBytes = BitConverter.GetBytes(floatVal);
key.SetValue(rawKey, floatBytes, RegistryValueKind.Binary);
return true;
case PlayerPrefsType.String:
var bytes = Encoding.UTF8.GetBytes(value + "\0");
key.SetValue(rawKey, bytes, RegistryValueKind.Binary);
return true;
case PlayerPrefsType.Binary:
var hexClean = value.Replace(" ", "").Replace("-", "");
if (hexClean.Length % 2 == 0)
{
byte[] rawBytes = Convert.FromHexString(hexClean);
key.SetValue(rawKey, rawBytes, RegistryValueKind.Binary);
return true;
}
break;
}
}
catch { }
return false;
}
/// <summary>
/// PlayerPrefsのエントリをレジストリから削除します。
/// </summary>
public bool DeletePlayerPref(string registryPath, string rawKey)
{
if (string.IsNullOrEmpty(registryPath) || string.IsNullOrEmpty(rawKey))
return false;
try
{
using var key = Registry.CurrentUser.OpenSubKey(registryPath, writable: true);
if (key != null)
{
key.DeleteValue(rawKey, throwOnMissingValue: false);
return true;
}
}
catch { }
return false;
}
/// <summary>
/// UnityのPlayerPrefsキー用ハッシュ値(MurmurHash2 32bit)を算出します。
/// </summary>
public static uint CalculateUnityHash(string key)
{
byte[] data = Encoding.UTF8.GetBytes(key);
const uint m = 0x5bd1e995;
const int r = 24;
uint h = (uint)data.Length;
int length = data.Length;
int currentIndex = 0;
while (length >= 4)
{
uint k = BitConverter.ToUInt32(data, currentIndex);
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
currentIndex += 4;
length -= 4;
}
switch (length)
{
case 3:
h ^= (uint)(data[currentIndex + 2] << 16);
h ^= (uint)(data[currentIndex + 1] << 8);
h ^= data[currentIndex];
h *= m;
break;
case 2:
h ^= (uint)(data[currentIndex + 1] << 8);
h ^= data[currentIndex];
h *= m;
break;
case 1:
h ^= data[currentIndex];
h *= m;
break;
}
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
/// <summary>
/// PlayerPrefsレジストリキー全体を .reg ファイルおよび JSON ファイルとしてバックアップします。
/// </summary>
public string? BackupRegistry(string registryPath, string backupDir)
{
if (string.IsNullOrEmpty(registryPath)) return null;
try
{
if (!Directory.Exists(backupDir))
{
Directory.CreateDirectory(backupDir);
}
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var regBackupFile = Path.Combine(backupDir, $"PlayerPrefs_{timestamp}.reg");
// reg.exe を用いて .reg ファイルを正確に出力
var fullRegKey = $@"HKEY_CURRENT_USER\{registryPath}";
var psi = new ProcessStartInfo
{
FileName = "reg.exe",
Arguments = $"export \"{fullRegKey}\" \"{regBackupFile}\" /y",
CreateNoWindow = true,
UseShellExecute = false
};
using var proc = Process.Start(psi);
proc?.WaitForExit(3000);
// JSONバックアップも併せて出力
var entries = GetPlayerPrefs(registryPath);
var jsonBackupFile = Path.Combine(backupDir, $"PlayerPrefs_{timestamp}.json");
var serializableList = entries.Select(e => new
{
e.RawKey,
e.CleanKey,
Type = e.Type.ToString(),
e.EditValue
});
var json = JsonSerializer.Serialize(serializableList, new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
File.WriteAllText(jsonBackupFile, json);
return File.Exists(regBackupFile) ? regBackupFile : jsonBackupFile;
}
catch
{
return null;
}
}
/// <summary>
/// .reg ファイルからレジストリを復元します。
/// </summary>
public bool RestoreRegistry(string regFilePath)
{
if (!File.Exists(regFilePath)) return false;
try
{
var psi = new ProcessStartInfo
{
FileName = "reg.exe",
Arguments = $"import \"{regFilePath}\"",
CreateNoWindow = true,
UseShellExecute = false
};
using var proc = Process.Start(psi);
proc?.WaitForExit(3000);
return proc?.ExitCode == 0;
}
catch
{
return false;
}
}
/// <summary>
/// Windows標準のレジストリエディタ(regedit)を起動して該当キーを表示します。
/// </summary>
public void OpenRegistryEditor(string registryPath)
{
try
{
// regedit の「前回開いたキー」を更新
var fullKey = $@"Computer\HKEY_CURRENT_USER\{registryPath}";
using (var lastKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Regedit"))
{
lastKey?.SetValue("LastKey", fullKey);
}
Process.Start(new ProcessStartInfo("regedit.exe") { UseShellExecute = true });
}
catch { }
}
// ====================================================================
// 2. ディスク上のセーブファイル(LocalLow / ゲームフォルダ)管理機能
// ====================================================================
/// <summary>
/// ゲームに関連するディスク上のセーブファイルをすべて探索して取得します。
/// </summary>
public List<SaveFileEntry> GetSaveFiles(UnityGameItem game)
{
var list = new List<SaveFileEntry>();
// 1. LocalLow フォルダ
if (!string.IsNullOrEmpty(game.LocalLowPath) && Directory.Exists(game.LocalLowPath))
{
try
{
var files = Directory.EnumerateFiles(game.LocalLowPath, "*", SearchOption.AllDirectories);
foreach (var f in files)
{
var fileName = Path.GetFileName(f);
// ログファイルは除外(Player.log, Player-prev.log)
if (fileName.StartsWith("Player", StringComparison.OrdinalIgnoreCase) && fileName.EndsWith(".log", StringComparison.OrdinalIgnoreCase))
continue;
var fi = new FileInfo(f);
list.Add(new SaveFileEntry
{
FileName = fileName,
FilePath = f,
FileSize = fi.Length,
LastModified = fi.LastWriteTime,
LocationType = "LocalLow",
IsTextOrJson = CheckIsTextOrJson(f)
});
}
}
catch { }
}
// 2. ゲーム本体フォルダ及びサブフォルダ
if (Directory.Exists(game.RootDirectory))
{
try
{
// ルート直下
CollectCandidateFiles(game.RootDirectory, "ゲームフォルダ", list);
// Save / SaveData / saves / savedata サブフォルダ
var subNames = new[] { "Save", "SaveData", "saves", "savedata", "Save_Data" };
foreach (var sub in subNames)
{
var subPath = Path.Combine(game.RootDirectory, sub);
if (Directory.Exists(subPath))
{
CollectCandidateFiles(subPath, "ゲームフォルダ/" + sub, list, isStrict: false);
}
}
// Dataフォルダ直下のセーブファイル候補
if (!string.IsNullOrEmpty(game.DataDirectoryPath) && Directory.Exists(game.DataDirectoryPath))
{
CollectCandidateFiles(game.DataDirectoryPath, "Dataフォルダ", list);
}
}
catch { }
}
// 更新日時降順でソート
return list.OrderByDescending(f => f.LastModified).ToList();
}
private void CollectCandidateFiles(string dir, string locationLabel, List<SaveFileEntry> list, bool isStrict = true)
{
try
{
var files = Directory.EnumerateFiles(dir);
foreach (var f in files)
{
var fileName = Path.GetFileName(f);
// 既に同パスが登録されていればスキップ
if (list.Any(x => x.FilePath.Equals(f, StringComparison.OrdinalIgnoreCase)))
continue;
// システムファイルや実行ファイル等は除外
var ext = Path.GetExtension(f).ToLowerInvariant();
if (ext is ".exe" or ".dll" or ".config" or ".manifest" or ".txt" or ".log" or ".info" or ".resS" or ".assets")
{
// readmeやapp.info等はセーブファイルではない
if (!fileName.Contains("save", StringComparison.OrdinalIgnoreCase))
continue;
}
if (isStrict)
{
// セーブファイル候補のフィルタ
bool isCandidate = fileName.Contains("save", StringComparison.OrdinalIgnoreCase) ||
ext is ".sav" or ".save" or ".savegame" or ".dat";
if (!isCandidate) continue;
}
var fi = new FileInfo(f);
list.Add(new SaveFileEntry
{
FileName = fileName,
FilePath = f,
FileSize = fi.Length,
LastModified = fi.LastWriteTime,
LocationType = locationLabel,
IsTextOrJson = CheckIsTextOrJson(f)
});
}
}
catch { }
}
/// <summary>
/// ファイルがテキストまたはJSON形式か判定します。
/// </summary>
public bool CheckIsTextOrJson(string filePath)
{
try
{
var ext = Path.GetExtension(filePath).ToLowerInvariant();
if (ext is ".json" or ".xml" or ".txt" or ".ini" or ".yaml" or ".yml")
return true;
// ファイルの先頭512バイトを検査
using var fs = File.OpenRead(filePath);
var buffer = new byte[Math.Min(512, fs.Length)];
int read = fs.Read(buffer, 0, buffer.Length);
if (read == 0) return true;
// ヌル文字がほとんど無ければテキスト判定
int nullCount = buffer.Take(read).Count(b => b == 0);
return nullCount == 0;
}
catch
{
return false;
}
}
/// <summary>
/// セーブファイルをテキストとして読み出します。
/// </summary>
public string ReadSaveFileText(string filePath)
{
if (!File.Exists(filePath)) return string.Empty;
return File.ReadAllText(filePath, Encoding.UTF8);
}
/// <summary>
/// セーブファイルにテキストを書き込みます(書き込み前に自動で .bak バックアップを作成)。
/// </summary>
public bool WriteSaveFileText(string filePath, string newContent)
{
try
{
if (File.Exists(filePath))
{
// 自動バックアップ作成
var bakPath = filePath + ".bak";
File.Copy(filePath, bakPath, overwrite: true);
}
File.WriteAllText(filePath, newContent, Encoding.UTF8);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 単一のセーブファイルをバックアップフォルダへコピー保存します。
/// </summary>
public string? BackupSaveFile(string filePath, string backupDir)
{
if (!File.Exists(filePath)) return null;
try
{
if (!Directory.Exists(backupDir))
{
Directory.CreateDirectory(backupDir);
}
var fileName = Path.GetFileName(filePath);
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var destName = $"{Path.GetFileNameWithoutExtension(fileName)}_{timestamp}{Path.GetExtension(fileName)}";
var destPath = Path.Combine(backupDir, destName);
File.Copy(filePath, destPath, overwrite: true);
return destPath;
}
catch
{
return null;
}
}
/// <summary>
/// バックアップファイルからセーブファイルを復元します。
/// </summary>
public bool RestoreSaveFile(string backupFilePath, string targetFilePath)
{
if (!File.Exists(backupFilePath)) return false;
try
{
// 現在のファイルを退避
if (File.Exists(targetFilePath))
{
var tempBak = targetFilePath + ".pre_restore_bak";
File.Copy(targetFilePath, tempBak, overwrite: true);
}
File.Copy(backupFilePath, targetFilePath, overwrite: true);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// ゲーム専用のバックアップ一覧を取得します。
/// </summary>
public List<SaveBackupEntry> GetBackupList(UnityGameItem game)
{
var list = new List<SaveBackupEntry>();
var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
if (!Directory.Exists(backupDir)) return list;
try
{
var files = Directory.EnumerateFiles(backupDir);
foreach (var f in files)
{
var fi = new FileInfo(f);
var ext = fi.Extension.ToLowerInvariant();
string type = ext switch
{
".reg" => "レジストリ (.reg)",
".json" => "JSONバックアップ",
_ => "ファイルバックアップ"
};
list.Add(new SaveBackupEntry
{
Name = fi.Name,
BackupPath = f,
Timestamp = fi.LastWriteTime,
BackupType = type,
Note = $"{fi.Length / 1024.0:F1} KB"
});
}
}
catch { }
return list.OrderByDescending(b => b.Timestamp).ToList();
}
/// <summary>
/// エクスプローラーで指定フォルダを開きます。
/// </summary>
public static void OpenFolderInExplorer(string folderPath)
{
try
{
if (Directory.Exists(folderPath))
{
Process.Start(new ProcessStartInfo
{
FileName = folderPath,
UseShellExecute = true
});
}
else if (File.Exists(folderPath))
{
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = $"/select,\"{folderPath}\"",
UseShellExecute = true
});
}
}
catch { }
}
}
}
+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 = 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 = 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 = 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) = 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).ToList();
}
/// <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 = 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);
}
}
}
// セーブデータ内の全文字列スキャン
ScanStrings(result, decrypted, enc);
// セーブデータ内の通常変数スキャン
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 = 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 = 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;
}
}
}
}
}
}
}