Files
GameLauncher/Engines/Rgss/RgssModService.cs
T

1172 lines
46 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GameLauncher.Helpers;
using GameLauncher.Models;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Unity;
namespace GameLauncher.Engines.Rgss
{
/// <summary>
/// ツクールVX / VX Ace の Scripts.rvdata2 / Scripts.rvdata 内の1つのスクリプト項目
/// </summary>
public class RgssScriptEntry
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Code { get; set; } = string.Empty;
}
/// <summary>
/// Ruby Marshal 4.8 形式で保存された ツクールVX/VX Ace スクリプトデータの
/// 解析・抽出・注入・再エンコードを行うヘルパークラス
/// </summary>
public static class RubyMarshalHelper
{
/// <summary>
/// Scripts.rvdata2 または Scripts.rvdata を読み込み、スクリプト一覧を取得します。
/// </summary>
public static List<RgssScriptEntry> LoadScripts(string filePath)
{
var list = new List<RgssScriptEntry>();
if (!File.Exists(filePath)) return list;
byte[] data = File.ReadAllBytes(filePath);
using var ms = new MemoryStream(data);
using var reader = new BinaryReader(ms);
if (ms.Length < 3) return list;
byte vMaj = reader.ReadByte();
byte vMin = reader.ReadByte();
if (vMaj != 4 || vMin != 8)
{
throw new InvalidDataException($"未対応の Ruby Marshal バージョンです: {vMaj}.{vMin}");
}
byte tag = reader.ReadByte();
if (tag != '[')
{
throw new InvalidDataException("ルート要素が Array ('[') ではありません。");
}
int count = ReadFixnum(reader);
for (int i = 0; i < count; i++)
{
byte subTag = reader.ReadByte();
if (subTag != '[') break;
int subCount = ReadFixnum(reader);
// 要素0: Fixnum Id
int id = ReadObjectAsInt(reader);
// 要素1: String Name
string name = ReadObjectAsString(reader);
// 要素2: String CompressedCode (zlib)
byte[] compBytes = ReadObjectAsBytes(reader);
string code = string.Empty;
if (compBytes.Length > 0)
{
try
{
code = DecompressZlib(compBytes);
}
catch
{
// 解凍失敗時は空文字
}
}
list.Add(new RgssScriptEntry
{
Id = id,
Name = name,
Code = code
});
}
return list;
}
/// <summary>
/// スクリプト一覧を Ruby Marshal 4.8 形式でシリアライズし、ファイルへ保存します。
/// </summary>
public static void SaveScripts(string filePath, List<RgssScriptEntry> scripts)
{
using var ms = new MemoryStream();
using var writer = new BinaryWriter(ms);
// 1. Marshal ヘッダ (4.8)
writer.Write((byte)4);
writer.Write((byte)8);
// 2. ルート Array タグ '[' と要素数
writer.Write((byte)'[');
WriteFixnum(writer, scripts.Count);
// 3. 各スクリプト項目
foreach (var script in scripts)
{
// 各項目は [id, name, compressed_code] の 3要素配列
writer.Write((byte)'[');
WriteFixnum(writer, 3);
// 要素0: Fixnum Id
WriteObjectAsInt(writer, script.Id);
// 要素1: String Name
WriteObjectAsString(writer, script.Name);
// 要素2: String CompressedCode (zlib圧縮)
byte[] uncompressed = Encoding.UTF8.GetBytes(script.Code ?? string.Empty);
byte[] compressed = CompressZlib(uncompressed);
WriteObjectAsBytes(writer, compressed);
}
var dir = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllBytes(filePath, ms.ToArray());
}
#region Marshal 内部リーダー / ライター
private static int ReadFixnum(BinaryReader reader)
{
sbyte b = reader.ReadSByte();
if (b == 0) return 0;
if (b > 0)
{
if (b > 4) return b - 5;
int len = b;
int res = 0;
for (int i = 0; i < len; i++) res |= (reader.ReadByte() << (8 * i));
return res;
}
else
{
if (b < -4) return b + 5;
int len = -b;
int res = -1;
for (int i = 0; i < len; i++)
{
res &= ~(0xFF << (8 * i));
res |= (reader.ReadByte() << (8 * i));
}
return res;
}
}
private static void WriteFixnum(BinaryWriter writer, int value)
{
if (value == 0)
{
writer.Write((sbyte)0);
}
else if (value > 0 && value < 123)
{
writer.Write((sbyte)(value + 5));
}
else if (value < 0 && value > -124)
{
writer.Write((sbyte)(value - 5));
}
else if (value > 0)
{
if (value <= 0xFF)
{
writer.Write((sbyte)1);
writer.Write((byte)value);
}
else if (value <= 0xFFFF)
{
writer.Write((sbyte)2);
writer.Write((ushort)value);
}
else if (value <= 0xFFFFFF)
{
writer.Write((sbyte)3);
writer.Write((byte)(value & 0xFF));
writer.Write((byte)((value >> 8) & 0xFF));
writer.Write((byte)((value >> 16) & 0xFF));
}
else
{
writer.Write((sbyte)4);
writer.Write(value);
}
}
else
{
// 負の大きな数
writer.Write((sbyte)-4);
writer.Write(value);
}
}
private static int ReadObjectAsInt(BinaryReader reader)
{
byte tag = reader.ReadByte();
if (tag == 'i') return ReadFixnum(reader);
reader.BaseStream.Position--;
return ReadFixnum(reader);
}
private static void WriteObjectAsInt(BinaryWriter writer, int value)
{
writer.Write((byte)'i');
WriteFixnum(writer, value);
}
private static string ReadObjectAsString(BinaryReader reader)
{
byte tag = reader.ReadByte();
if (tag == 'I')
{
reader.ReadByte(); // '"'
int len = ReadFixnum(reader);
byte[] strBytes = reader.ReadBytes(len);
int ivarCount = ReadFixnum(reader);
for (int k = 0; k < ivarCount; k++)
{
byte symTag = reader.ReadByte();
if (symTag == ':')
{
int symLen = ReadFixnum(reader);
reader.ReadBytes(symLen);
}
else if (symTag == ';')
{
ReadFixnum(reader);
}
byte valTag = reader.ReadByte();
if (valTag == 'T' || valTag == 'F') { }
else if (valTag == '"') { int l = ReadFixnum(reader); reader.ReadBytes(l); }
else if (valTag == 'i') { ReadFixnum(reader); }
}
return Encoding.UTF8.GetString(strBytes);
}
else if (tag == '"')
{
int len = ReadFixnum(reader);
byte[] strBytes = reader.ReadBytes(len);
return Encoding.UTF8.GetString(strBytes);
}
return string.Empty;
}
private static void WriteObjectAsString(BinaryWriter writer, string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text ?? string.Empty);
// インスタンス変数付きUTF-8文字列 (I"...\x06: \x06ET)
writer.Write((byte)'I');
writer.Write((byte)'"');
WriteFixnum(writer, bytes.Length);
writer.Write(bytes);
// 1つのインスタンス変数 (:E => true UTF-8)
WriteFixnum(writer, 1);
writer.Write((byte)':');
byte[] symE = Encoding.UTF8.GetBytes("E");
WriteFixnum(writer, symE.Length);
writer.Write(symE);
writer.Write((byte)'T'); // true
}
private static byte[] ReadObjectAsBytes(BinaryReader reader)
{
byte tag = reader.ReadByte();
if (tag == '"')
{
int len = ReadFixnum(reader);
return reader.ReadBytes(len);
}
else if (tag == 'I')
{
reader.ReadByte(); // '"'
int len = ReadFixnum(reader);
byte[] bytes = reader.ReadBytes(len);
int ivarCount = ReadFixnum(reader);
for (int k = 0; k < ivarCount; k++)
{
byte symTag = reader.ReadByte();
if (symTag == ':') { int l = ReadFixnum(reader); reader.ReadBytes(l); }
else if (symTag == ';') { ReadFixnum(reader); }
byte valTag = reader.ReadByte();
if (valTag == 'T' || valTag == 'F') { }
else if (valTag == '"') { int l = ReadFixnum(reader); reader.ReadBytes(l); }
else if (valTag == 'i') { ReadFixnum(reader); }
}
return bytes;
}
return [];
}
private static void WriteObjectAsBytes(BinaryWriter writer, byte[] data)
{
writer.Write((byte)'"');
WriteFixnum(writer, data.Length);
writer.Write(data);
}
#endregion
#region Zlib 圧縮 / 解凍 / Adler32
private static string DecompressZlib(byte[] data)
{
if (data == null || data.Length < 6) return string.Empty;
// 先頭2バイト(zlibヘッダ)と末尾4バイト(Adler32)を除いて raw deflate 解凍
using var ms = new MemoryStream(data, 2, data.Length - 6);
using var deflate = new DeflateStream(ms, CompressionMode.Decompress);
using var reader = new StreamReader(deflate, Encoding.UTF8);
return reader.ReadToEnd();
}
private static byte[] CompressZlib(byte[] uncompressed)
{
using var ms = new MemoryStream();
// 1. Zlib ヘッダ (0x78, 0x9C: Default Compression)
ms.WriteByte(0x78);
ms.WriteByte(0x9C);
// 2. Raw Deflate
using (var deflate = new DeflateStream(ms, CompressionLevel.Optimal, leaveOpen: true))
{
deflate.Write(uncompressed, 0, uncompressed.Length);
}
// 3. Adler-32 チェックサム (ビッグエンディアン)
uint adler = ComputeAdler32(uncompressed);
ms.WriteByte((byte)((adler >> 24) & 0xFF));
ms.WriteByte((byte)((adler >> 16) & 0xFF));
ms.WriteByte((byte)((adler >> 8) & 0xFF));
ms.WriteByte((byte)(adler & 0xFF));
return ms.ToArray();
}
private static uint ComputeAdler32(byte[] data)
{
const uint MOD_ADLER = 65521;
uint a = 1, b = 0;
for (int i = 0; i < data.Length; i++)
{
a = (a + data[i]) % MOD_ADLER;
b = (b + a) % MOD_ADLER;
}
return (b << 16) | a;
}
#endregion
}
/// <summary>
/// ツクールVX / VX Ace (RGSS2 / RGSS3) ゲームのMOD適用・解除・アーカイブ抽出を統括するサービス
/// </summary>
public class RgssModService
{
/// <summary>MODスクリプトのセクション名</summary>
public const string ModSectionName = "GameLauncher_Mod";
/// <summary>バックアップファイルのサフィックス</summary>
public const string BackupSuffix = ".original_launcher_backup";
/// <summary>
/// 指定されたスクリプトファイルに GameLauncher の改造スクリプトが含まれているか判定します。
/// </summary>
public static bool CheckIsModded(string scriptsFilePath)
{
if (string.IsNullOrEmpty(scriptsFilePath) || !File.Exists(scriptsFilePath))
{
return false;
}
try
{
var scripts = RubyMarshalHelper.LoadScripts(scriptsFilePath);
return scripts.Any(s => s.Name.Equals(ModSectionName, StringComparison.OrdinalIgnoreCase));
}
catch
{
return false;
}
}
/// <summary>
/// ツクールVX/VX Aceゲームに対して、チェック状態に応じた改造の適用または復元を行います。
/// </summary>
public async Task<(bool Success, string Message)> ApplyOrRestoreModAsync(
TkoolGameItem game,
Dictionary<string, bool>? pluginSettings = null,
string? rgssExtractorPath = null)
{
if (game.ApplyMod)
{
return await ApplyModAsync(game, pluginSettings, rgssExtractorPath);
}
else
{
return RestoreOriginal(game);
}
}
/// <summary>
/// 改造スクリプトを適用します。
/// スクリプトファイルが未抽出の場合は自動でアーカイブから抽出します。
/// </summary>
public async Task<(bool Success, string Message)> ApplyModAsync(
TkoolGameItem game,
Dictionary<string, bool>? pluginSettings = null,
string? rgssExtractorPath = null)
{
try
{
var scriptsPath = game.PluginsJsPath;
// 1. スクリプトファイルが存在しない場合(RGSS暗号化アーカイブ内の場合)、自動抽出
if (string.IsNullOrEmpty(scriptsPath) || !File.Exists(scriptsPath))
{
var (extractSuccess, extractMsg) = await ExtractScriptsAsync(game, rgssExtractorPath);
if (!extractSuccess)
{
return (false, $"スクリプトの抽出に失敗したため改造を適用できませんでした: {extractMsg}");
}
scriptsPath = game.PluginsJsPath;
}
if (string.IsNullOrEmpty(scriptsPath) || !File.Exists(scriptsPath))
{
return (false, "スクリプトファイル (Scripts.rvdata2 または Scripts.rvdata) が見つかりません。");
}
// 2. バックアップの作成 (Backups フォルダへ保存)
var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var scriptFileName = Path.GetFileName(scriptsPath);
var backupPath = Path.Combine(gameBackupDir, scriptFileName + BackupSuffix);
var legacyBackupPath = scriptsPath + BackupSuffix;
if (!File.Exists(backupPath))
{
if (File.Exists(legacyBackupPath))
{
File.Copy(legacyBackupPath, backupPath, true);
}
else
{
// 現在のスクリプトを読み込み、MODセクションを除去したクリーンな状態でバックアップ
var currentScripts = RubyMarshalHelper.LoadScripts(scriptsPath);
currentScripts.RemoveAll(s => s.Name.Equals(ModSectionName, StringComparison.OrdinalIgnoreCase));
RubyMarshalHelper.SaveScripts(backupPath, currentScripts);
}
}
// 3. バックアップ(クリーン状態)を元に編集
var baseScripts = RubyMarshalHelper.LoadScripts(backupPath);
baseScripts.RemoveAll(s => s.Name.Equals(ModSectionName, StringComparison.OrdinalIgnoreCase));
// 4. 有効化するMOD項目の Ruby スクリプトコードを生成
string modRubyCode = BuildModScript(game, pluginSettings);
var modEntry = new RgssScriptEntry
{
Id = 99999999,
Name = ModSectionName,
Code = modRubyCode
};
// Main セクションの直前(Mainが無ければ末尾)に挿入
int mainIndex = baseScripts.FindIndex(s => s.Name.Equals("Main", StringComparison.OrdinalIgnoreCase) || s.Name.Contains("メイン"));
if (mainIndex >= 0)
{
baseScripts.Insert(mainIndex, modEntry);
}
else
{
baseScripts.Add(modEntry);
}
// 5. 書き込み保存
RubyMarshalHelper.SaveScripts(scriptsPath, baseScripts);
game.IsModded = true;
return (true, "ツクールVX/VX Ace用スクリプト改造を正常に適用しました。");
}
catch (Exception ex)
{
return (false, $"ツクールVX改造適用中にエラーが発生しました: {ex.Message}");
}
}
/// <summary>
/// 改造を解除し、ゲームを改造前のオリジナル状態に復元します。
/// </summary>
public (bool Success, string Message) RestoreOriginal(TkoolGameItem game)
{
try
{
var scriptsPath = game.PluginsJsPath;
var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var scriptFileName = !string.IsNullOrEmpty(scriptsPath)
? Path.GetFileName(scriptsPath)
: (game.EngineType == TkoolEngineType.VXAce ? "Scripts.rvdata2" : "Scripts.rvdata");
var backupPath = Path.Combine(gameBackupDir, scriptFileName + BackupSuffix);
var legacyBackupPath = !string.IsNullOrEmpty(scriptsPath) ? scriptsPath + BackupSuffix : null;
// 1. バックアップが存在する場合はバックアップから復元
if (File.Exists(backupPath))
{
if (!string.IsNullOrEmpty(scriptsPath))
{
File.Copy(backupPath, scriptsPath, true);
}
}
else if (legacyBackupPath != null && File.Exists(legacyBackupPath))
{
File.Copy(legacyBackupPath, scriptsPath!, true);
try { File.Copy(legacyBackupPath, backupPath, true); } catch { }
}
else if (!string.IsNullOrEmpty(scriptsPath) && File.Exists(scriptsPath))
{
// バックアップが無い場合、現在のファイルからMODセクションを除去
var currentScripts = RubyMarshalHelper.LoadScripts(scriptsPath);
currentScripts.RemoveAll(s => s.Name.Equals(ModSectionName, StringComparison.OrdinalIgnoreCase));
RubyMarshalHelper.SaveScripts(scriptsPath, currentScripts);
}
// ゲームフォルダ内の旧バックアップファイルを削除
if (legacyBackupPath != null && File.Exists(legacyBackupPath))
{
try { File.Delete(legacyBackupPath); } catch { }
}
// 2. もし元々アーカイブのみのゲーム(初回にスクリプトのみを新規抽出して実ファイル配置しただけ)の場合、
//   配置したスクリプトを安全に削除すれば、ゲームは再び完全な暗号化アーカイブ起動状態に戻る
if (game.HasRgssArchive && !string.IsNullOrEmpty(scriptsPath) && File.Exists(scriptsPath))
{
var isNewlyExtractedFlag = Path.Combine(gameBackupDir, ".extracted_by_launcher");
if (File.Exists(isNewlyExtractedFlag))
{
try
{
File.Delete(scriptsPath);
File.Delete(isNewlyExtractedFlag);
game.IsRgssExtracted = false;
game.PluginsJsPath = string.Empty;
var dataDir = Path.GetDirectoryName(scriptsPath);
if (!string.IsNullOrEmpty(dataDir) && Directory.Exists(dataDir) && Directory.GetFileSystemEntries(dataDir).Length == 0)
{
try { Directory.Delete(dataDir); } catch { }
}
}
catch { }
}
}
game.IsModded = false;
return (true, "ツクールVXゲームを改造前のオリジナル状態に正常に復元しました。");
}
catch (Exception ex)
{
return (false, $"復元中にエラーが発生しました: {ex.Message}");
}
}
/// <summary>
/// アーカイブから Scripts.rvdata2 または Scripts.rvdata を抽出します。
/// 内蔵アンパッカーを使用し、高速かつ確実に抽出します。
/// </summary>
public async Task<(bool Success, string Message)> ExtractScriptsAsync(TkoolGameItem game, string? rgssExtractorPath)
{
return await Task.Run(() =>
{
try
{
var archivePath = game.RgssArchivePath;
if (string.IsNullOrEmpty(archivePath) || !File.Exists(archivePath))
{
// ルートフォルダからアーカイブを探索
var candidates = Directory.GetFiles(game.RootDirectory, "*.rgss*a", SearchOption.TopDirectoryOnly);
if (candidates.Length > 0)
{
archivePath = candidates[0];
game.RgssArchivePath = archivePath;
}
}
if (string.IsNullOrEmpty(archivePath) || !File.Exists(archivePath))
{
return (false, "RGSSアーカイブ (*.rgss3a / *.rgss2a) が見つかりません。");
}
var targetScriptName = game.EngineType == TkoolEngineType.VXAce ? "Scripts.rvdata2" : "Scripts.rvdata";
var dataDir = Path.Combine(game.RootDirectory, "Data");
if (!Directory.Exists(dataDir))
{
Directory.CreateDirectory(dataDir);
}
var destScriptPath = Path.Combine(dataDir, targetScriptName);
// 1. RGSS Extractor.exe が設定されている場合は、確実な外部ツール抽出(インメモリリフレクション)を最優先で実行
bool extracted = false;
if (!string.IsNullOrEmpty(rgssExtractorPath) && File.Exists(rgssExtractorPath))
{
extracted = ExtractUsingRgssExtractorExe(rgssExtractorPath, archivePath, targetScriptName, destScriptPath);
}
// 2. 外部ツールがない、または抽出に失敗した場合は C# 内蔵高速アンパッカーを実行
if (!extracted)
{
extracted = ExtractSingleFileFromRgssArchive(archivePath, targetScriptName, destScriptPath);
}
if (!extracted || !File.Exists(destScriptPath))
{
return (false, $"アーカイブ内から {targetScriptName} を抽出できませんでした。");
}
game.PluginsJsPath = destScriptPath;
game.PluginsDirPath = dataDir;
game.IsRgssExtracted = true;
// 当ランチャーによって新規抽出されたことを示すマーカーを Backups フォルダに記録(復元時の完全クリーンアップ用)
var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var marker = Path.Combine(gameBackupDir, ".extracted_by_launcher");
try { File.WriteAllText(marker, DateTime.Now.ToString("o")); } catch { }
// クリーンな抽出スクリプトを直ちに Backups フォルダにバックアップ
var backupPath = Path.Combine(gameBackupDir, targetScriptName + BackupSuffix);
if (!File.Exists(backupPath))
{
try { File.Copy(destScriptPath, backupPath, true); } catch { }
}
return (true, $"{targetScriptName} の抽出が完了しました。(ゲームの Data フォルダに配置完了)");
}
catch (Exception ex)
{
return (false, $"スクリプト抽出中にエラーが発生しました: {ex.Message}");
}
});
}
#region RGSS アンパッカー (内蔵実装)
/// <summary>
/// RGSS3A / RGSS2A / RGSSAD アーカイブから指定ファイル(Scripts.rvdata2 等)をピンポイントで抽出します。
/// </summary>
private static bool ExtractSingleFileFromRgssArchive(string archivePath, string targetFileName, string destinationPath)
{
try
{
using var fs = new FileStream(archivePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var br = new BinaryReader(fs);
if (fs.Length < 16) return false;
byte[] header = br.ReadBytes(8);
string magic = Encoding.ASCII.GetString(header, 0, 6);
if (!magic.Equals("RGSSAD", StringComparison.OrdinalIgnoreCase))
{
return false;
}
byte ver = header[7]; // 3: RGSS3A (VX Ace), 1: RGSSAD (XP/VX)
if (ver == 3)
{
// RGSS3A (ツクールVX Ace)
uint magicKey = br.ReadUInt32();
magicKey = magicKey * 9 + 3;
while (fs.Position < fs.Length)
{
uint offset = br.ReadUInt32() ^ magicKey;
uint size = br.ReadUInt32() ^ magicKey;
uint dataKey = br.ReadUInt32() ^ magicKey;
uint nameLen = br.ReadUInt32() ^ magicKey;
if (offset == 0) break;
byte[] nameBytes = br.ReadBytes((int)nameLen);
for (int i = 0; i < nameBytes.Length; i++)
{
nameBytes[i] ^= (byte)((magicKey >> (8 * (i % 4))) & 0xFF);
}
string entryName = Encoding.UTF8.GetString(nameBytes);
if (entryName.EndsWith(targetFileName, StringComparison.OrdinalIgnoreCase) ||
Path.GetFileName(entryName).Equals(targetFileName, StringComparison.OrdinalIgnoreCase))
{
// 該当ファイル発見!データを読み取り復号
long currentPos = fs.Position;
fs.Seek(offset, SeekOrigin.Begin);
byte[] fileData = br.ReadBytes((int)size);
uint key = dataKey;
for (int i = 0; i < fileData.Length; i++)
{
fileData[i] ^= (byte)(key & 0xFF);
if (i % 4 == 3)
{
key = key * 7 + 3;
}
}
var destDir = Path.GetDirectoryName(destinationPath);
if (!string.IsNullOrEmpty(destDir) && !Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
File.WriteAllBytes(destinationPath, fileData);
return true;
}
}
}
else
{
// RGSSAD (ツクールXP / VX)
uint key = 0xDEADCAFE;
while (fs.Position < fs.Length)
{
if (fs.Position + 4 > fs.Length) break;
int nameLen = (int)(br.ReadUInt32() ^ key);
key = key * 7 + 3;
if (nameLen <= 0 || nameLen > 1024 || fs.Position + nameLen > fs.Length) break;
byte[] nameBytes = br.ReadBytes(nameLen);
for (int i = 0; i < nameLen; i++)
{
nameBytes[i] ^= (byte)(key & 0xFF);
key = key * 7 + 3;
}
string entryName = Encoding.UTF8.GetString(nameBytes);
uint size = br.ReadUInt32() ^ key;
key = key * 7 + 3;
long dataOffset = fs.Position;
if (entryName.EndsWith(targetFileName, StringComparison.OrdinalIgnoreCase) ||
Path.GetFileName(entryName).Equals(targetFileName, StringComparison.OrdinalIgnoreCase))
{
byte[] fileData = br.ReadBytes((int)size);
uint dKey = key;
for (int i = 0; i < fileData.Length; i++)
{
fileData[i] ^= (byte)(dKey & 0xFF);
dKey = dKey * 7 + 3;
}
var destDir = Path.GetDirectoryName(destinationPath);
if (!string.IsNullOrEmpty(destDir) && !Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
File.WriteAllBytes(destinationPath, fileData);
return true;
}
else
{
// スキップ
fs.Seek(size, SeekOrigin.Current);
}
}
}
}
catch
{
// 解析失敗時はフォールバック
}
return false;
}
/// <summary>
/// <summary>
/// 外部ツール RGSS Extractor.exe を利用して抽出し、生成物を配置します。
/// .NET アセンブリであるため、まずはインメモリで直接 Main_Parser を呼び出して高速・無音で抽出し、
/// フォールバックとしてプロセス起動による抽出を行います。
/// </summary>
private static bool ExtractUsingRgssExtractorExe(string exePath, string archivePath, string targetFileName, string destinationPath)
{
try
{
if (File.Exists(exePath))
{
// 1. .NET リフレクションによる直接インメモリ高速抽出
try
{
var asm = System.Reflection.Assembly.LoadFrom(exePath);
var parserType = asm.GetType("RGSS_Extractor.Main_Parser");
if (parserType != null)
{
var parser = Activator.CreateInstance(parserType);
var parseFileMethod = parserType.GetMethod("parse_file", new[] { typeof(string) });
var getFileDataMethod = parserType.GetMethod("get_filedata");
var closeFileMethod = parserType.GetMethod("close_file");
if (parseFileMethod != null && getFileDataMethod != null && parser != null)
{
var entries = parseFileMethod.Invoke(parser, new object[] { archivePath }) as System.Collections.IEnumerable;
if (entries != null)
{
foreach (var entry in entries)
{
var nameProp = entry.GetType().GetProperty("name") ?? (System.Reflection.MemberInfo?)entry.GetType().GetField("name");
string? entryName = null;
if (nameProp is System.Reflection.PropertyInfo pi) entryName = pi.GetValue(entry) as string;
else if (nameProp is System.Reflection.FieldInfo fi) entryName = fi.GetValue(entry) as string;
if (!string.IsNullOrEmpty(entryName) &&
(entryName.EndsWith(targetFileName, StringComparison.OrdinalIgnoreCase) ||
Path.GetFileName(entryName).Equals(targetFileName, StringComparison.OrdinalIgnoreCase)))
{
var fileBytes = getFileDataMethod.Invoke(parser, new object[] { entry }) as byte[];
if (fileBytes != null && fileBytes.Length > 0)
{
closeFileMethod?.Invoke(parser, null);
var destDir = Path.GetDirectoryName(destinationPath);
if (!string.IsNullOrEmpty(destDir) && !Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
File.WriteAllBytes(destinationPath, fileBytes);
return true;
}
}
}
}
closeFileMethod?.Invoke(parser, null);
}
}
}
catch { }
// 2. フォールバック: プロセス起動による抽出
var toolDir = Path.GetDirectoryName(exePath) ?? AppDomain.CurrentDomain.BaseDirectory;
var psi = new ProcessStartInfo
{
FileName = exePath,
Arguments = $"\"{archivePath}\"",
WorkingDirectory = toolDir,
UseShellExecute = false,
CreateNoWindow = true
};
using var proc = Process.Start(psi);
if (proc != null)
{
proc.WaitForExit(30000); // 最大30秒待機
}
// RGSS Extractor はツール自身のフォルダ配下に Data\Scripts.rvdata2 等を出力
var possibleOutput = Path.Combine(toolDir, "Data", targetFileName);
if (File.Exists(possibleOutput))
{
var destDir = Path.GetDirectoryName(destinationPath);
if (!string.IsNullOrEmpty(destDir) && !Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
File.Copy(possibleOutput, destinationPath, true);
try { File.Delete(possibleOutput); } catch { }
return true;
}
}
}
catch { }
return false;
}
#endregion
#region Ruby MOD スクリプト生成
/// <summary>
/// 有効化された各MOD設定に応じた Ruby スクリプトコードを生成します。
/// </summary>
public static string BuildModScript(TkoolGameItem game, Dictionary<string, bool>? pluginSettings)
{
var sb = new StringBuilder();
sb.AppendLine("#==============================================================================");
sb.AppendLine("# ■ GameLauncher 自動生成 MOD スクリプト (ツクールVX / VX Ace用)");
sb.AppendLine($"# 生成日時: {DateTime.Now:yyyy/MM/dd HH:mm:ss}");
sb.AppendLine("#==============================================================================");
sb.AppendLine();
bool isAce = game.EngineType == TkoolEngineType.VXAce;
// 1. 移動速度アップ&常時ダッシュ
if (game.IsPluginEnabled("RgssDashSpeedUp", pluginSettings, true))
{
sb.AppendLine(@"# --- 移動速度高速化&常時オートダッシュ ---
class Game_Player < Game_Character
alias org_gl_move_speed move_speed
def move_speed
return 5
end
alias org_gl_dash? dash?
def dash?
return false if @move_route_forcing
return false if $game_map && $game_map.disable_dash?
return false if (respond_to?(:vehicle) && vehicle)
return true
end
end
");
}
// 2. アイテム入手時 99個固定化
if (game.IsPluginEnabled("RgssItemGainMax", pluginSettings, true))
{
sb.AppendLine(@"# --- アイテム入手時 99個固定化 ---
class Game_Party < Game_Unit
alias org_gl_gain_item gain_item
def gain_item(item, amount, include_equip = false)
if item && amount > 0
amount = 99
end
org_gl_gain_item(item, amount, include_equip)
end
end
");
}
// 3. アイテム消費なし
if (game.IsPluginEnabled("RgssItemNoConsume", pluginSettings, true))
{
sb.AppendLine(@"# --- アイテム消費なし ---
class Game_Party < Game_Unit
alias org_gl_consume_item consume_item
def consume_item(item)
# 消費処理をスキップ(何もしない)
end
end
");
}
// 4. 獲得ゴールド最大化
if (game.IsPluginEnabled("RgssGoldGainMax", pluginSettings, true))
{
sb.AppendLine(@"# --- 獲得ゴールド最大化 ---
class Game_Troop < Game_Unit
alias org_gl_gold_total gold_total
def gold_total
return 999999
end
end
");
}
// 5. 獲得経験値最大化
if (game.IsPluginEnabled("RgssExpGainMax", pluginSettings, true))
{
sb.AppendLine(@"# --- 獲得経験値最大化 ---
class Game_Troop < Game_Unit
alias org_gl_exp_total exp_total
def exp_total
return 999999
end
end
");
}
// 6. 戦闘ターン開始時 全回復 (HP)
if (game.IsPluginEnabled("RgssBattleTurnRecoverHp", pluginSettings, true))
{
sb.AppendLine(@"# --- 戦闘中ターン全回復 (HP) ---
class Game_Actor < Game_Battler
alias org_gl_on_turn_end_hp on_turn_end
def on_turn_end
org_gl_on_turn_end_hp
begin
self.hp = self.mhp if respond_to?(:mhp) && respond_to?(:hp=)
rescue
end
end
end
");
}
// 7. 戦闘ターン開始時 全回復 (MP)
if (game.IsPluginEnabled("RgssBattleTurnRecoverMp", pluginSettings, true))
{
sb.AppendLine(@"# --- 戦闘中ターン全回復 (MP) ---
class Game_Actor < Game_Battler
alias org_gl_on_turn_end_mp on_turn_end
def on_turn_end
org_gl_on_turn_end_mp
begin
self.mp = self.mmp if respond_to?(:mmp) && respond_to?(:mp=)
rescue
end
end
end
");
}
// 8. 戦闘ターン開始時 全回復 (TP) - VX Ace専用
if (isAce && game.IsPluginEnabled("RgssBattleTurnRecoverTp", pluginSettings, true))
{
sb.AppendLine(@"# --- 戦闘中ターン全回復 (TP) ---
class Game_Actor < Game_Battler
alias org_gl_on_turn_end_tp on_turn_end
def on_turn_end
org_gl_on_turn_end_tp
begin
self.tp = self.max_tp if respond_to?(:max_tp) && respond_to?(:tp=)
rescue
end
end
end
");
}
// 9. メッセージ瞬間表示・超高速化
if (game.IsPluginEnabled("RgssMessageInstant", pluginSettings, true))
{
sb.AppendLine(@"# --- メッセージ瞬間表示・ウェイト短縮 ---
class Window_Message < Window_Base
# 1文字送りのウェイトをスキップ
def wait_for_one_character
end
# 通常ウェイトの短縮
alias org_gl_wait wait
def wait(duration)
# ウェイト時間を大幅短縮
org_gl_wait([duration / 3, 1].max)
end
end
");
}
// 10. コマンド位置記憶 (ツクールMV風)
if (game.IsPluginEnabled("RgssCommandMemory", pluginSettings, true))
{
sb.AppendLine(@"# --- コマンド位置記憶スクリプト ---
class Game_System
def menu_command_index
@menu_command_index ||= 0
end
attr_writer :menu_command_index
end
class Game_Actor < Game_Battler
def last_command_index
@last_command_index ||= 0
end
attr_writer :last_command_index
end
class Window_MenuCommand < Window_Command
alias org_gl_select_last select_last
def select_last
if $game_system && $game_system.menu_command_index < item_max
select($game_system.menu_command_index)
else
org_gl_select_last rescue nil
end
end
end
class Scene_Menu < Scene_MenuBase
alias org_gl_terminate_cmd_mem terminate
def terminate
org_gl_terminate_cmd_mem
if $game_system && @command_window
$game_system.menu_command_index = @command_window.index
end
end
end
class Window_ActorCommand < Window_Command
alias org_gl_idx_set index=
def index=(idx)
org_gl_idx_set(idx)
if @actor && @actor_command_updating
@actor.last_command_index = self.index
end
end
alias org_gl_setup_cmd_mem setup
def setup(actor)
@actor_command_updating = false
org_gl_setup_cmd_mem(actor)
if @actor
idx = @actor.last_command_index
idx = 0 if idx >= item_max
select(idx)
end
@actor_command_updating = true
end
end
");
}
// 11. ウィンドウをディスプレイに合わせて整数倍拡大 (スクリプト注入)
if (game.IsPluginEnabled("RgssWindowResizeFull", pluginSettings, false))
{
sb.AppendLine(BuildWindowResizeScript(isAce));
}
return sb.ToString();
}
/// <summary>
/// ディスプレイに収まる最大の整数倍でゲーム解像度を拡大する Ruby スクリプトを生成します。
/// VX Ace は Graphics.resize_screen、VX (RGSS2) は Win32API フォールバックでウィンドウを拡大します。
/// </summary>
private static string BuildWindowResizeScript(bool isAce)
{
var sb = new StringBuilder();
sb.AppendLine("# --- ウィンドウをディスプレイに合わせて整数倍拡大 (整数倍スケーリング) ---");
sb.AppendLine("begin");
sb.AppendLine(" gl_get_system_metrics = Win32API.new('user32', 'GetSystemMetrics', 'i', 'i')");
sb.AppendLine(" gl_display_w = gl_get_system_metrics.call(0)");
sb.AppendLine(" gl_display_h = gl_get_system_metrics.call(1)");
sb.AppendLine(" gl_base_w = (defined?(Graphics.width) ? Graphics.width : 544)");
sb.AppendLine(" gl_base_h = (defined?(Graphics.height) ? Graphics.height : 416)");
sb.AppendLine(" gl_scale_w = gl_display_w / gl_base_w");
sb.AppendLine(" gl_scale_h = gl_display_h / gl_base_h");
sb.AppendLine(" gl_scale = [gl_scale_w, gl_scale_h].min");
sb.AppendLine(" gl_scale = 1 if gl_scale < 1");
sb.AppendLine(" gl_new_w = gl_base_w * gl_scale");
sb.AppendLine(" gl_new_h = gl_base_h * gl_scale");
sb.AppendLine(" if defined?(Graphics.resize_screen)");
sb.AppendLine(" Graphics.resize_screen(gl_new_w, gl_new_h)");
sb.AppendLine(" else");
sb.AppendLine(" $gl_old_scale = gl_scale");
sb.AppendLine(" end");
sb.AppendLine("rescue");
sb.AppendLine(" # 取得・拡大に失敗してもゲームは通常起動させる");
sb.AppendLine("end");
sb.AppendLine();
return sb.ToString();
}
#endregion
}
}