using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.Json; using GameLauncher.Helpers; namespace GameLauncher.Engines.Wolf { /// /// ウディタ(WOLF RPGエディター)セーブデータ内の1つの変数項目 /// 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; } } /// /// ウディタセーブデータ内の可変データベース項目 /// 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; } } /// /// ウディタセーブデータ内の文字列項目 /// public class WolfStringItem { public int Offset { get; set; } public int Length { get; set; } public string Value { get; set; } = string.Empty; } /// /// パース済みウディタセーブデータ /// 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 Variables { get; set; } = []; public List DatabaseItems { get; set; } = []; public List Strings { get; set; } = []; } /// /// WOLF RPGエディターのセーブデータ(SaveXX.sav)の復号・暗号化・解析・編集サービス /// 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 { } } /// /// 指定されたゲームディレクトリからセーブデータファイル一覧を取得します。 /// public List GetSaveFiles(string gameDirectory) { var result = new List(); if (string.IsNullOrEmpty(gameDirectory) || !Directory.Exists(gameDirectory)) return result; var searchDirs = new List { 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)]; } /// /// 暗号化されたウディタセーブデータを復号します。 /// 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; } /// /// 復号状態のウディタセーブデータを暗号化します(チェックサム自動更新付き)。 /// 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; } /// /// セーブファイルを読み込み、復号してパースします。 /// public WolfSaveData LoadSave(string filePath) { if (!File.Exists(filePath)) throw new FileNotFoundException($"セーブデータファイルが見つかりません: {filePath}"); byte[] rawBytes = File.ReadAllBytes(filePath); byte[] decrypted = this.Decrypt(rawBytes); var result = new WolfSaveData { FilePath = filePath, FileName = Path.GetFileName(filePath), RawDecryptedBytes = decrypted }; if (decrypted.Length < 0x20) return result; // 文字エンコーディング判定 (オフセット6が 0x55 なら UTF-8, それ以外は Shift-JIS) result.IsUtf8 = (decrypted[6] == 0x55); Encoding enc = result.IsUtf8 ? Encoding.UTF8 : Encoding.GetEncoding(932); // ゲームタイトルの取得 (オフセット 0x15 からの文字列) if (decrypted[0x14] == 0x19 && decrypted.Length > 0x17) { ushort titleLen = BitConverter.ToUInt16(decrypted, 0x15); if (titleLen > 1 && 0x17 + titleLen <= decrypted.Length) { result.GameTitle = enc.GetString(decrypted, 0x17, titleLen - 1).Trim('\0'); int nextOffset = 0x17 + titleLen; if (nextOffset + 2 <= decrypted.Length) { result.FileVersion = BitConverter.ToUInt16(decrypted, nextOffset); } } } // セーブデータ内の全文字列スキャン this.ScanStrings(result, decrypted, enc); // セーブデータ内の通常変数スキャン this.ScanVariables(result, decrypted); return result; } /// /// 文字列の検出スキャン /// 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 { } } } } } /// /// 変数テーブルのスキャン(32bit整数群) /// 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 }); } } } /// /// セーブファイルをバックアップしてから上書き保存します。 /// バックアップは必ず Z:\自作ソフト\GameLauncher\Backups に保存されます。 /// public string SaveToFile(WolfSaveData model, string folderName, string rootDirectory) { if (model == null || model.RawDecryptedBytes == null || model.RawDecryptedBytes.Length == 0) throw new InvalidOperationException("保存対象のデータが空です。"); // 1. バックアップ作成 (Backups フォルダへ) string? backupPath = this.BackupSaveFile(model.FilePath, folderName, rootDirectory); // 2. 変数・項目の変更を RawDecryptedBytes に書き戻し foreach (var item in model.Variables) { if (item.Offset >= START_OFFSET && item.Offset + 4 <= model.RawDecryptedBytes.Length) { byte[] valBytes = BitConverter.GetBytes(item.Value); Buffer.BlockCopy(valBytes, 0, model.RawDecryptedBytes, item.Offset, 4); } } // 3. 暗号化 & チェックサム再計算 byte[] encrypted = this.Encrypt(model.RawDecryptedBytes); // 4. アトミック書き込み string tempFile = model.FilePath + ".tmp_" + Guid.NewGuid().ToString("N"); File.WriteAllBytes(tempFile, encrypted); File.Move(tempFile, model.FilePath, overwrite: true); return backupPath ?? string.Empty; } /// /// セーブデータのバックアップを作成します。 /// 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; } } /// /// セーブデータを JSON 形式でエクスポートします。 /// 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); } /// /// JSON 形式の編集内容をセーブデータモデルへインポート・反映します。 /// 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; } } } } } } }