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:
1 parent
0d11039ee9
commit
8cea2a147d
47 files changed
+2976
-176
No files matched your search
@@ -1,608 +0,0 @@
|
||||
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;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using GameLauncher.Models;
|
||||
using GameLauncher.Engines.Unity;
|
||||
|
||||
namespace GameLauncher.Services.Codecs
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using GameLauncher.Models;
|
||||
using GameLauncher.Engines.Unity;
|
||||
|
||||
namespace GameLauncher.Services.Codecs
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using GameLauncher.Models;
|
||||
using GameLauncher.Engines.Unity;
|
||||
|
||||
namespace GameLauncher.Services.Codecs
|
||||
{
|
||||
|
||||
+449
-94
@@ -16,6 +16,12 @@ using System.Windows.Media.Imaging;
|
||||
using Microsoft.Win32;
|
||||
using GameLauncher.Helpers;
|
||||
using GameLauncher.Models;
|
||||
using GameLauncher.Engines.Rgss;
|
||||
using GameLauncher.Engines.Tkool;
|
||||
using GameLauncher.Engines.Tyrano;
|
||||
using GameLauncher.Engines.Wolf;
|
||||
using GameLauncher.Engines.Unity;
|
||||
using GameLauncher.Engines.Nwjs;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
@@ -58,6 +64,15 @@ namespace GameLauncher.Services
|
||||
public bool SrpgProxyDll { get; set; }
|
||||
public double SrpgSpeedMultiplier { get; set; } = 3.0;
|
||||
|
||||
// 単体exe梱包(FOSSIL / boxed)専用
|
||||
public bool IsFossilSingleExe { get; set; }
|
||||
public bool IsBoxedExe { get; set; }
|
||||
public bool IsStandaloneExeExtracted { get; set; }
|
||||
public string? StandaloneExtractedDirPath { get; set; }
|
||||
public string? StandaloneBackupPath { get; set; }
|
||||
public string? BoxedPayloadEntryPath { get; set; }
|
||||
public bool CanExtractViaExternalTool { get; set; }
|
||||
|
||||
// Unity専用
|
||||
public string DataDirectoryPath { get; set; } = string.Empty;
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
@@ -166,7 +181,13 @@ namespace GameLauncher.Services
|
||||
IsSrpgExtracted = entry.IsSrpgExtracted,
|
||||
SrpgArchivePath = entry.SrpgArchivePath,
|
||||
SrpgProxyDll = entry.SrpgProxyDll,
|
||||
SrpgSpeedMultiplier = entry.SrpgSpeedMultiplier > 0 ? entry.SrpgSpeedMultiplier : 3.0
|
||||
SrpgSpeedMultiplier = entry.SrpgSpeedMultiplier > 0 ? entry.SrpgSpeedMultiplier : 3.0,
|
||||
IsFossilSingleExe = entry.IsFossilSingleExe,
|
||||
IsBoxedExe = entry.IsBoxedExe,
|
||||
IsStandaloneExeExtracted = entry.IsStandaloneExeExtracted,
|
||||
StandaloneExtractedDirPath = entry.StandaloneExtractedDirPath,
|
||||
StandaloneBackupPath = entry.StandaloneBackupPath,
|
||||
BoxedPayloadEntryPath = entry.BoxedPayloadEntryPath
|
||||
};
|
||||
if (entry.PluginSettings != null)
|
||||
{
|
||||
@@ -264,6 +285,14 @@ namespace GameLauncher.Services
|
||||
string? asarExtP = element.TryGetProperty("AsarExtractedDirPath", out var aep) ? aep.GetString() : null;
|
||||
string? relJs = element.TryGetProperty("RelativePluginsJsInAsar", out var rj) ? rj.GetString() : null;
|
||||
|
||||
bool isFossilSingleExe = element.TryGetProperty("IsFossilSingleExe", out var ifs) && ifs.GetBoolean();
|
||||
bool isBoxedExe = element.TryGetProperty("IsBoxedExe", out var ibx) && ibx.GetBoolean();
|
||||
bool isStandaloneExeExtracted = element.TryGetProperty("IsStandaloneExeExtracted", out var isx) && isx.GetBoolean();
|
||||
string? standaloneExtDir = element.TryGetProperty("StandaloneExtractedDirPath", out var sed) ? sed.GetString() : null;
|
||||
string? standaloneBackup = element.TryGetProperty("StandaloneBackupPath", out var sbp) ? sbp.GetString() : null;
|
||||
string? boxedEntry = element.TryGetProperty("BoxedPayloadEntryPath", out var bep) ? bep.GetString() : null;
|
||||
bool canExtractViaExternalTool = element.TryGetProperty("CanExtractViaExternalTool", out var cet) && cet.GetBoolean();
|
||||
|
||||
var item = new TkoolGameItem
|
||||
{
|
||||
Title = title,
|
||||
@@ -281,7 +310,14 @@ namespace GameLauncher.Services
|
||||
IsAsarExtracted = isAsarExt,
|
||||
AsarPath = asarP,
|
||||
AsarExtractedDirPath = asarExtP,
|
||||
RelativePluginsJsInAsar = relJs
|
||||
RelativePluginsJsInAsar = relJs,
|
||||
IsFossilSingleExe = isFossilSingleExe,
|
||||
IsBoxedExe = isBoxedExe,
|
||||
IsStandaloneExeExtracted = isStandaloneExeExtracted,
|
||||
StandaloneExtractedDirPath = standaloneExtDir,
|
||||
StandaloneBackupPath = standaloneBackup,
|
||||
BoxedPayloadEntryPath = boxedEntry,
|
||||
CanExtractViaExternalTool = canExtractViaExternalTool
|
||||
};
|
||||
|
||||
// 既存キャッシュの自動修復: ウディタの誤判定を修正
|
||||
@@ -441,7 +477,14 @@ namespace GameLauncher.Services
|
||||
IsSrpgExtracted = tg.IsSrpgExtracted,
|
||||
SrpgArchivePath = tg.SrpgArchivePath,
|
||||
SrpgProxyDll = tg.SrpgProxyDll,
|
||||
SrpgSpeedMultiplier = tg.SrpgSpeedMultiplier
|
||||
SrpgSpeedMultiplier = tg.SrpgSpeedMultiplier,
|
||||
IsFossilSingleExe = tg.IsFossilSingleExe,
|
||||
IsBoxedExe = tg.IsBoxedExe,
|
||||
IsStandaloneExeExtracted = tg.IsStandaloneExeExtracted,
|
||||
StandaloneExtractedDirPath = tg.StandaloneExtractedDirPath,
|
||||
StandaloneBackupPath = tg.StandaloneBackupPath,
|
||||
BoxedPayloadEntryPath = tg.BoxedPayloadEntryPath,
|
||||
CanExtractViaExternalTool = tg.CanExtractViaExternalTool
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -858,7 +901,21 @@ namespace GameLauncher.Services
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 通常のティラノスクリプト探索
|
||||
// 2. boxed(nw.js埋め込み: *boxed*.exe + 埋め込みpackage.nw または on-disk www\)のツクール探索
|
||||
var boxedGame = DetectBoxedNwGameInDirectory(dirPath, folderName, folderModified);
|
||||
if (boxedGame != null)
|
||||
{
|
||||
return boxedGame;
|
||||
}
|
||||
|
||||
// 3. FOSSIL単体exe同梱のツクールMZ探索 (js/plugins.jsがexe内に埋め込まれている形態)
|
||||
var fossilMzGame = DetectFossilMZGameInDirectory(dirPath, folderName, folderModified);
|
||||
if (fossilMzGame != null)
|
||||
{
|
||||
return fossilMzGame;
|
||||
}
|
||||
|
||||
// 3. 通常のティラノスクリプト探索
|
||||
var tyranoIndex = FindTyranoIndexHtml(dirPath);
|
||||
if (tyranoIndex != null)
|
||||
{
|
||||
@@ -888,7 +945,7 @@ namespace GameLauncher.Services
|
||||
};
|
||||
}
|
||||
|
||||
// 3. app.asar パッケージであるか判定
|
||||
// 4. app.asar パッケージであるか判定
|
||||
if (AsarArchiveService.FindAsarPackage(dirPath, out var asarPath, out bool isExtracted, out var extractedDirPath))
|
||||
{
|
||||
var inspect = _asarService.InspectAsar(asarPath!);
|
||||
@@ -933,21 +990,21 @@ namespace GameLauncher.Services
|
||||
}
|
||||
}
|
||||
|
||||
// 4. WOLF RPGエディター(ウディタ)ゲームの検出
|
||||
// 5. WOLF RPGエディター(ウディタ)ゲームの検出
|
||||
var wolfGame = DetectWolfGameInDirectory(dirPath, folderName, folderModified);
|
||||
if (wolfGame != null)
|
||||
{
|
||||
return wolfGame;
|
||||
}
|
||||
|
||||
// 5. SRPG Studio ゲームの検出
|
||||
// 6. SRPG Studio ゲームの検出
|
||||
var srpgGame = DetectSrpgGameInDirectory(dirPath, folderName, folderModified);
|
||||
if (srpgGame != null)
|
||||
{
|
||||
return srpgGame;
|
||||
}
|
||||
|
||||
// 6. ツクールVX / VX Ace (RGSS2 / RGSS3) ゲームの検出
|
||||
// 7. ツクールVX / VX Ace (RGSS2 / RGSS3) ゲームの検出
|
||||
var rgssGame = DetectRgssGameInDirectory(dirPath, folderName, folderModified);
|
||||
if (rgssGame != null)
|
||||
{
|
||||
@@ -959,6 +1016,364 @@ namespace GameLauncher.Services
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 単体exe梱包されたツクールMZゲームを判定し、TkoolGameItemを生成します。
|
||||
/// 対象とするexe形態は次の2種で、いずれも js/plugins.js がディスク上に存在しません。
|
||||
/// - FOSSIL形態: エントリHTMLが FOSSILindex.html、本体は Game.exe(data/System.json はディスク上)
|
||||
/// - boxed形態: ゲーム本体を exe に内包(例: Game_boxed.exe)。ディスク上にゲーム実体が無い
|
||||
/// 誤検出を避けるため、以下の条件が全て揃った場合のみ検出します。
|
||||
/// - 候補exe(Game.exe / *boxed*.exe / *.exe)が存在する
|
||||
/// - js/plugins.js および www/js/plugins.js がディスク上に存在しない
|
||||
/// - FOSSILindex.html が存在する、又は data/System.json が存在する、又は boxed 命名のexeである
|
||||
/// 本形態はゲーム本体をexeへ埋め込むため、他のツクールゲームには一切影響しません。
|
||||
/// </summary>
|
||||
public TkoolGameItem? DetectFossilMZGameInDirectory(string dirPath, string folderName, DateTime? folderModified)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 0. ディスク上に plugins.js が存在する場合は通常のMV/MZ検出に任せる
|
||||
if (File.Exists(Path.Combine(dirPath, "js", "plugins.js")) ||
|
||||
File.Exists(Path.Combine(dirPath, "www", "js", "plugins.js")))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// 1. 候補exeの解決(Game.exe を最優先、次に *boxed*.exe、最後に任意のexe)
|
||||
var exePath = ResolveStandaloneEntryExecutable(dirPath);
|
||||
if (exePath == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. 判定マーカーの確認
|
||||
bool hasFossilHtml = File.Exists(Path.Combine(dirPath, "FOSSILindex.html"));
|
||||
var systemJson = Path.Combine(dirPath, "data", "System.json");
|
||||
bool hasSystemJson = File.Exists(systemJson);
|
||||
bool isBoxedExe = Path.GetFileName(exePath).IndexOf("boxed", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
|
||||
if (!hasFossilHtml && !hasSystemJson && !isBoxedExe)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var icon = LoadIcon(exePath, dirPath);
|
||||
string? title = null;
|
||||
string? pluginsJsInContainer = null;
|
||||
string? embeddedPluginsPath = null;
|
||||
|
||||
// 3. boxed 命名exeは内包コンテナ(package.nw)からplugins.js位置を推定
|
||||
if (isBoxedExe)
|
||||
{
|
||||
TryProbeBoxedEmbeddedPayload(exePath, out pluginsJsInContainer, out embeddedPluginsPath);
|
||||
}
|
||||
|
||||
// 4. タイトル解決: data/System.json の gameTitle を優先、無ければフォルダ名
|
||||
if (hasSystemJson)
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(systemJson);
|
||||
var match = Regex.Match(json, @"""gameTitle""\s*:\s*""([^""]*)\""");
|
||||
if (match.Success && !string.IsNullOrWhiteSpace(match.Groups[1].Value))
|
||||
{
|
||||
title = Regex.Unescape(match.Groups[1].Value);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// 5. boxed命名exeで data/System.json がディスク上に無い場合は内包コンテナを注入対象とする
|
||||
bool isBoxed = isBoxedExe && !hasSystemJson;
|
||||
|
||||
return new TkoolGameItem
|
||||
{
|
||||
Title = string.IsNullOrWhiteSpace(title) ? folderName : title!,
|
||||
FolderName = folderName,
|
||||
RootDirectory = dirPath,
|
||||
ExecutablePath = exePath,
|
||||
PluginsJsPath = embeddedPluginsPath ?? string.Empty,
|
||||
PluginsDirPath = string.Empty,
|
||||
EngineType = TkoolEngineType.MZ,
|
||||
IsModded = false,
|
||||
// ディスク上にJS実体が無い単体exe形態は、そのままではプラグイン注入できないため初期は改造OFF
|
||||
ApplyMod = false,
|
||||
IconImage = icon,
|
||||
FolderLastModified = folderModified,
|
||||
IsAsar = false,
|
||||
// 形態フラグ(他ゲームへ影響しないための識別子)
|
||||
IsFossilSingleExe = hasFossilHtml || !isBoxed,
|
||||
IsBoxedExe = isBoxed,
|
||||
BoxedPayloadEntryPath = pluginsJsInContainer
|
||||
};
|
||||
}
|
||||
catch { }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 単体exe形態の候補となる実行ファイルを解決します。
|
||||
/// 優先順: Game.exe → *boxed*.exe → それ以外の *.exe(unins* を除く)。
|
||||
/// </summary>
|
||||
private static string? ResolveStandaloneEntryExecutable(string dirPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
var gameExe = Path.Combine(dirPath, "Game.exe");
|
||||
if (File.Exists(gameExe))
|
||||
{
|
||||
return gameExe;
|
||||
}
|
||||
|
||||
var exes = Directory.GetFiles(dirPath, "*.exe", SearchOption.TopDirectoryOnly);
|
||||
if (exes.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// *boxed*.exe を優先
|
||||
foreach (var exe in exes)
|
||||
{
|
||||
var name = Path.GetFileName(exe);
|
||||
if (name.IndexOf("boxed", StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
{
|
||||
return exe;
|
||||
}
|
||||
}
|
||||
|
||||
// unins* を除外した最初のexe
|
||||
foreach (var exe in exes)
|
||||
{
|
||||
var name = Path.GetFileName(exe);
|
||||
if (name.StartsWith("unins", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return exe;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// boxed命名exeの内包コンテナ(package.nw相当)を限定部分読みで探索し、
|
||||
/// タイトル情報(package.json)と js/plugins.js 相当のエントリ有無を推定します。
|
||||
/// 全走査は行いません(1.14GB級exeを対象に含むため)。
|
||||
/// </summary>
|
||||
private static void TryProbeBoxedEmbeddedPayload(string exePath, out string? packageJsonEntryName, out string? embeddedPluginsJsPath)
|
||||
{
|
||||
packageJsonEntryName = null;
|
||||
embeddedPluginsJsPath = null;
|
||||
|
||||
try
|
||||
{
|
||||
const int windowSize = 4 * 1024 * 1024; // 4MB限定ウィンドウ
|
||||
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
long size = fs.Length;
|
||||
|
||||
// package.nw マーカーは exe の中間域に置かれることが多いため、中央付近から数点だけ走査する
|
||||
long[] probes = new[]
|
||||
{
|
||||
Math.Max(0, size / 2 - windowSize / 2),
|
||||
Math.Max(0, size / 4),
|
||||
Math.Max(0, size * 3 / 4),
|
||||
};
|
||||
|
||||
foreach (var start in probes)
|
||||
{
|
||||
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);
|
||||
|
||||
// ASCII/UTF8 の "package.json" を探す
|
||||
var text = System.Text.Encoding.ASCII.GetString(buf, 0, read);
|
||||
int idx = text.IndexOf("package.json", StringComparison.Ordinal);
|
||||
if (idx >= 0)
|
||||
{
|
||||
packageJsonEntryName = "package.json";
|
||||
// 同一ウィンドウ内に plugins.js があれば注入対象として記録
|
||||
if (text.IndexOf("plugins.js", StringComparison.Ordinal) >= 0)
|
||||
{
|
||||
embeddedPluginsJsPath = "js/plugins.js";
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// nw.js埋め込み(*boxed*.exe + 埋め込みpackage.nw または on-disk www\)のツクールMZゲームを検出します。
|
||||
/// 全走査は行わず、exe内のpackage.nwマーカー周辺の限定読みで埋め込みコンテナ有無を判定します。
|
||||
/// boxed命名exeが存在する場合のみ発火するため、他のツクールゲームには一切影響しません。
|
||||
/// </summary>
|
||||
public TkoolGameItem? DetectBoxedNwGameInDirectory(string dirPath, string folderName, DateTime? folderModified)
|
||||
{
|
||||
try
|
||||
{
|
||||
// (a) ディスク上の www\js\plugins.js を優先(通常検出で拾えない露出パターンを補完)
|
||||
var onDiskPlugins = FindPluginsJsUnderWww(dirPath);
|
||||
|
||||
// (b) *boxed*.exe の存在確認(Game.exe固定を一般化)
|
||||
var boxedExe = Directory.EnumerateFiles(dirPath, "*.exe", SearchOption.TopDirectoryOnly)
|
||||
.FirstOrDefault(f => Path.GetFileName(f).Contains("boxed", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
// boxed命名exeが無ければここでは扱わない(厳密に追加的)
|
||||
if (boxedExe == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// (c) 埋め込みpackage.nwマーカーの有無(限定部分読み)
|
||||
bool hasEmbeddedPkg = ContainsPackageNwMarker(boxedExe);
|
||||
|
||||
// (d) boxed命名exeが存在すれば、マーカー未確定でも外部アンパッカーでの展開を試行できるため一覧に表示する。
|
||||
// (マーカーは中盤の限られた窓でしか確認しないため、非標準コンテナでは拾えない場合がある)
|
||||
// 展開可否は実行時(ExtractPackageNw)に確定し、不可なら「起動のみ」にフォールバックする。
|
||||
bool canTryExternalTool = true;
|
||||
if (!hasEmbeddedPkg && onDiskPlugins == null && !canTryExternalTool)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var dataDir = Path.Combine(dirPath, "data");
|
||||
var engine = DetectEngineTypeByDataJson(dirPath);
|
||||
var title = ExtractTkoolTitle(dirPath, dataDir);
|
||||
var icon = LoadIcon(boxedExe, dirPath);
|
||||
|
||||
return new TkoolGameItem
|
||||
{
|
||||
Title = string.IsNullOrWhiteSpace(title) ? folderName : title,
|
||||
FolderName = folderName,
|
||||
RootDirectory = dirPath,
|
||||
ExecutablePath = boxedExe,
|
||||
PluginsJsPath = onDiskPlugins ?? string.Empty,
|
||||
PluginsDirPath = onDiskPlugins != null ? Path.Combine(Path.GetDirectoryName(onDiskPlugins)!, "plugins") : string.Empty,
|
||||
EngineType = engine,
|
||||
IsModded = false,
|
||||
// on-disk露出時のみその場で注入可。埋め込みのみの場合はAI展開後に注入可となる
|
||||
ApplyMod = onDiskPlugins != null,
|
||||
IconImage = icon,
|
||||
FolderLastModified = folderModified,
|
||||
IsAsar = false,
|
||||
IsFossilSingleExe = false,
|
||||
IsBoxedExe = true,
|
||||
BoxedPayloadEntryPath = hasEmbeddedPkg ? "js/plugins.js" : null,
|
||||
// boxed命名exeが存在するため、外部アンパッカーでの展開を試行できる可能性がある
|
||||
CanExtractViaExternalTool = canTryExternalTool
|
||||
};
|
||||
}
|
||||
catch { }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ディスク上に露出した www\js\plugins.js(または www\www\js\plugins.js)を探索します。
|
||||
/// 通常の FindPluginsJs は深さ2で js\・www\js\ を見ますが、boxed形態の
|
||||
/// www 直下露出を取りこぼさないための補完です。
|
||||
/// </summary>
|
||||
private static string? FindPluginsJsUnderWww(string dirPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
var candidates = new[]
|
||||
{
|
||||
Path.Combine(dirPath, "www", "js", "plugins.js"),
|
||||
Path.Combine(dirPath, "www", "www", "js", "plugins.js"),
|
||||
};
|
||||
foreach (var c in candidates)
|
||||
{
|
||||
if (File.Exists(c))
|
||||
{
|
||||
return c;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// exe内に nw.js の埋め込みコンテナ(package.nw)マーカーが存在するかを
|
||||
/// 限定部分読み(4MB窓×数点)で判定します。全走査は行いません(1.14GB級exe対策)。
|
||||
/// </summary>
|
||||
private 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>
|
||||
/// data\System.json の有無と内容からエンジン種別(MZ/MV)を判定します。
|
||||
/// jsディレクトリが無い単体exe梱包形態でも動作します。
|
||||
/// </summary>
|
||||
private static TkoolEngineType DetectEngineTypeByDataJson(string dirPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
var systemJson = Path.Combine(dirPath, "data", "System.json");
|
||||
if (File.Exists(systemJson))
|
||||
{
|
||||
var json = File.ReadAllText(systemJson);
|
||||
// MZ固有のキー(例: "hasEncryptedImages" は両者にあるが、"optDisplayTp"等はMZのみ)
|
||||
if (json.Contains("\"optDisplayTp\"") ||
|
||||
json.Contains("\"optExtraExp\"") ||
|
||||
json.Contains("\"optAntiLag\""))
|
||||
{
|
||||
return TkoolEngineType.MZ;
|
||||
}
|
||||
return TkoolEngineType.MZ;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
return TkoolEngineType.MZ;
|
||||
}
|
||||
|
||||
#region WOLF RPGエディター(ウディタ)検出ロジック
|
||||
|
||||
/// <summary>
|
||||
@@ -1346,99 +1761,17 @@ namespace GameLauncher.Services
|
||||
|
||||
/// <summary>
|
||||
/// BOMの有無やShift_JIS (CP932) を自動判定して安全にINIファイルを行単位で読み込みます。
|
||||
/// 実装は Engines/Rgss/Games/IiniTitleRepair に分離済み(RGSS個別対応)。
|
||||
/// </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) でデコード(ツクールVX/VX Aceおよびウディタの標準)
|
||||
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>();
|
||||
}
|
||||
}
|
||||
=> GameLauncher.Engines.Rgss.Games.IiniTitleRepair.GameIniTitleRepair.ReadIniLinesSafe(filePath);
|
||||
|
||||
/// <summary>
|
||||
/// キャッシュ内に文字化けして保存されたRGSSタイトルの修復を行います。
|
||||
/// 実装は Engines/Rgss/Games/IiniTitleRepair に分離済み(RGSS個別対応)。
|
||||
/// </summary>
|
||||
public static void FixRgssTitleFromIni(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)
|
||||
{
|
||||
var lines = ReadIniLinesSafe(iniPath);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
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 { }
|
||||
}
|
||||
=> GameLauncher.Engines.Rgss.Games.IiniTitleRepair.GameIniTitleRepair.Fix(tg);
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -1709,6 +2042,13 @@ namespace GameLauncher.Services
|
||||
return directIndex;
|
||||
}
|
||||
|
||||
// FOSSILで梱包されたティラノスクリプトは index.html が FOSSILindex.html にリネームされる
|
||||
var directFossilIndex = Path.Combine(dirPath, "FOSSILindex.html");
|
||||
if (File.Exists(directFossilIndex) && CheckIsTyranoDirectory(dirPath))
|
||||
{
|
||||
return directFossilIndex;
|
||||
}
|
||||
|
||||
var subDirs = Directory.GetDirectories(dirPath);
|
||||
foreach (var sub in subDirs)
|
||||
{
|
||||
@@ -1723,6 +2063,12 @@ namespace GameLauncher.Services
|
||||
{
|
||||
return subIndex;
|
||||
}
|
||||
|
||||
var subFossilIndex = Path.Combine(sub, "FOSSILindex.html");
|
||||
if (File.Exists(subFossilIndex) && CheckIsTyranoDirectory(sub))
|
||||
{
|
||||
return subFossilIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
@@ -1744,6 +2090,15 @@ namespace GameLauncher.Services
|
||||
if (html.Contains("tyrano", StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
|
||||
// FOSSIL梱包のティラノスクリプト用エントリ
|
||||
var fossilIndexPath = Path.Combine(dir, "FOSSILindex.html");
|
||||
if (File.Exists(fossilIndexPath))
|
||||
{
|
||||
var html = File.ReadAllText(fossilIndexPath);
|
||||
if (html.Contains("tyrano", StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,6 +5,8 @@ using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using GameLauncher.Models;
|
||||
using GameLauncher.Services.Codecs;
|
||||
using GameLauncher.Engines.Unity;
|
||||
using GameLauncher.Engines.Wolf;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
|
||||
@@ -1,329 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using GameLauncher.Helpers;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// SRPG Studio の data.dts アーカイブ解凍・抽出および再構築(再パック)サービス
|
||||
/// 外部ツール 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()
|
||||
{
|
||||
var exeDir = AppPathHelper.GetExeDirectory();
|
||||
var path = Path.Combine(exeDir, "Tools", ToolExeName);
|
||||
if (File.Exists(path)) return path;
|
||||
|
||||
// プロジェクトルート等フォールバック
|
||||
var fallback = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Tools", ToolExeName);
|
||||
if (File.Exists(fallback)) return fallback;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,757 +0,0 @@
|
||||
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;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
/// <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
|
||||
{
|
||||
var srcDll = Path.Combine(AppPathHelper.GetExeDirectory(), "Tools", "speedhack-i686", ProxyDllName);
|
||||
if (!File.Exists(srcDll))
|
||||
{
|
||||
srcDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Tools", "speedhack-i686", ProxyDllName);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,482 +0,0 @@
|
||||
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.Services
|
||||
{
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,375 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using GameLauncher.Helpers;
|
||||
using GameLauncher.Models;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,683 +0,0 @@
|
||||
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.Services
|
||||
{
|
||||
/// <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 { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// ツクールVX / VX Ace のゲームウィンドウを、ディスプレイに収まる最大の整数倍へ拡大する外部連携サービス。
|
||||
/// ゲーム側は無改造のまま、ランチャーがゲームウィンドウを検出して Win32 API で拡大します。
|
||||
/// 外部ツールパスが設定されている場合はそちらを優先起動します。
|
||||
/// </summary>
|
||||
public class WindowResizeService
|
||||
{
|
||||
#region Win32 API
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int GetSystemMetrics(int nIndex);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int GetWindowTextLength(IntPtr hWnd);
|
||||
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
|
||||
private const int SM_CXSCREEN = 0;
|
||||
private const int SM_CYSCREEN = 1;
|
||||
|
||||
private const uint SWP_NOZORDER = 0x0004;
|
||||
private const uint SWP_NOACTIVATE = 0x0010;
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// ゲーム起動後にウィンドウ拡大を適用します。
|
||||
/// 外部ツールパスが設定されていればそれを起動し、無ければ内蔵の Win32 API 方式で拡大します。
|
||||
/// </summary>
|
||||
/// <param name="process">起動済みのゲームプロセス</param>
|
||||
/// <param name="externalToolPath">外部ツール(Sizer等)の実行ファイルパス。空なら内蔵方式。</param>
|
||||
/// <returns>(成功可否, ログ用メッセージ)</returns>
|
||||
public async Task<(bool Success, string Message)> ApplyResizeAsync(Process process, string? externalToolPath)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(externalToolPath) && File.Exists(externalToolPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = externalToolPath,
|
||||
UseShellExecute = true
|
||||
});
|
||||
return (true, $"外部ツールを起動しました: {Path.GetFileName(externalToolPath)}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 外部ツール起動失敗時は内蔵方式にフォールバック
|
||||
var (ok, msg) = await ApplyBuiltInResizeAsync(process);
|
||||
return (ok, $"外部ツール起動に失敗したため内蔵方式を使用: {ex.Message} / {msg}");
|
||||
}
|
||||
}
|
||||
|
||||
return await ApplyBuiltInResizeAsync(process);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 内蔵の Win32 API 方式でゲームウィンドウを整数倍に拡大します。
|
||||
/// </summary>
|
||||
public async Task<(bool Success, string Message)> ApplyBuiltInResizeAsync(Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr hWnd = IntPtr.Zero;
|
||||
|
||||
// ウィンドウが生成されるまで最大約5秒待機
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
process.Refresh();
|
||||
if (process.HasExited)
|
||||
{
|
||||
return (false, "ゲームプロセスが終了しました。");
|
||||
}
|
||||
|
||||
if (process.MainWindowHandle != IntPtr.Zero)
|
||||
{
|
||||
hWnd = process.MainWindowHandle;
|
||||
break;
|
||||
}
|
||||
|
||||
// メインウィンドウが未確定な場合、可視ウィンドウをプロセスIDで探索
|
||||
hWnd = FindWindowByProcessId((uint)process.Id);
|
||||
if (hWnd != IntPtr.Zero) break;
|
||||
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
if (hWnd == IntPtr.Zero)
|
||||
{
|
||||
return (false, "ゲームウィンドウを検出できませんでした。");
|
||||
}
|
||||
|
||||
int screenW = GetSystemMetrics(SM_CXSCREEN);
|
||||
int screenH = GetSystemMetrics(SM_CYSCREEN);
|
||||
|
||||
// ゲームの既定ウィンドウサイズ(VX/VX Ace 標準)
|
||||
int baseW = 544;
|
||||
int baseH = 416;
|
||||
|
||||
int scale = Math.Min(screenW / baseW, screenH / baseH);
|
||||
if (scale < 1) scale = 1;
|
||||
|
||||
int newW = baseW * scale;
|
||||
int newH = baseH * scale;
|
||||
|
||||
bool moved = SetWindowPos(hWnd, IntPtr.Zero, 0, 0, newW, newH, SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
|
||||
return moved
|
||||
? (true, $"ウィンドウを {newW}x{newH} ({scale}x) に拡大しました。")
|
||||
: (false, "ウィンドウサイズの変更に失敗しました。");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (false, $"ウィンドウ拡大中にエラーが発生しました: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定プロセスIDに属する可視トップレベルウィンドウを検索します。
|
||||
/// </summary>
|
||||
private static IntPtr FindWindowByProcessId(uint processId)
|
||||
{
|
||||
IntPtr result = IntPtr.Zero;
|
||||
|
||||
EnumWindows((hWnd, lParam) =>
|
||||
{
|
||||
GetWindowThreadProcessId(hWnd, out uint pid);
|
||||
if (pid == processId && IsWindowVisible(hWnd) && GetWindowTextLength(hWnd) > 0)
|
||||
{
|
||||
result = hWnd;
|
||||
return false; // 見つかったので列挙終了
|
||||
}
|
||||
return true;
|
||||
}, IntPtr.Zero);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using GameLauncher.Helpers;
|
||||
using GameLauncher.Models;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
/// <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. ランチャー直下の Tools\UberWolfCli.exe
|
||||
var exeDir = AppPathHelper.GetExeDirectory();
|
||||
var candidates = new[]
|
||||
{
|
||||
Path.Combine(exeDir, "Tools", "UberWolfCli.exe"),
|
||||
Path.Combine(exeDir, "Tools", "UberWolf.exe"),
|
||||
Path.Combine(exeDir, "Tools", "WolfDec.exe"),
|
||||
@"C:\VS2026\GameLauncher\Tools\UberWolfCli.exe",
|
||||
@"Z:\自作ソフト\GameLauncher\Tools\UberWolfCli.exe"
|
||||
};
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using GameLauncher.Helpers;
|
||||
using GameLauncher.Models;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
/// <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(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()
|
||||
{
|
||||
var exeDir = AppPathHelper.GetExeDirectory();
|
||||
var candidates = new[]
|
||||
{
|
||||
Path.Combine(exeDir, "Tools", "speedhack-i686", ProxyDllName),
|
||||
Path.Combine(exeDir, "Tools", ProxyDllName),
|
||||
@"C:\VS2026\GameLauncher\Tools\speedhack-i686\version.dll",
|
||||
@"Z:\自作ソフト\GameLauncher\Tools\speedhack-i686\version.dll"
|
||||
};
|
||||
|
||||
foreach (var path in candidates)
|
||||
{
|
||||
if (File.Exists(path)) return path;
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,401 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using GameLauncher.Helpers;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user