feat(tkool): リソース修復サービスおよび文字化け・URLエンコード救済プラグインを追加

- ツクールMV/MZの日本語ファイル名・URLエンコード・丸数字表記揺れを並列修復する TkoolResourceRepairService を追加
- ゲーム起動時に読み込み不整合を動的に解決する必須救済プラグイン ResourceLoaderFix.js を追加
- TkoolModService にて ResourceLoaderFix を最優先で適用するよう対応
This commit is contained in:
armonica committed 2026-10-14 09:57:54 +09:00
1 parent 908dc443eb
commit 4398f80aa4
3 files changed
+894 -2

No files matched your search

+13 -2
View File
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@@ -222,10 +222,21 @@ namespace GameLauncher.Engines.Tkool
} }
// 有効化対象のプラグインを取得 // 有効化対象のプラグインを取得
// ※ResourceLoaderFix はリソース読み込み不具合の必須救済プラグインのため、常に有効化・先頭配置
var fixPlugin = _availablePlugins.FirstOrDefault(p => string.Equals(p.Id, "ResourceLoaderFix", StringComparison.OrdinalIgnoreCase));
var pluginsToEnable = _availablePlugins var pluginsToEnable = _availablePlugins
.Where(p => game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: true)) .Where(p => string.Equals(p.Id, "ResourceLoaderFix", StringComparison.OrdinalIgnoreCase)
? true
: game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: true))
.ToList(); .ToList();
// ResourceLoaderFix を最優先(先頭)に配置して、他プラグイン実行前のリソース要求も確実に救済
if (fixPlugin != null && pluginsToEnable.Contains(fixPlugin))
{
pluginsToEnable.Remove(fixPlugin);
pluginsToEnable.Insert(0, fixPlugin);
}
// 3. ゲーム側の plugins ディレクトリから不要な旧プラグインや無効プラグインを安全に掃除 // 3. ゲーム側の plugins ディレクトリから不要な旧プラグインや無効プラグインを安全に掃除
var allManaged = GetAllManagedPluginNames(_availablePlugins); var allManaged = GetAllManagedPluginNames(_availablePlugins);
var enabledIds = new HashSet<string>(pluginsToEnable.Select(p => p.Id), StringComparer.OrdinalIgnoreCase); var enabledIds = new HashSet<string>(pluginsToEnable.Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
+618
View File
@@ -0,0 +1,618 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using GameLauncher.Helpers;
namespace GameLauncher.Engines.Tkool
{
/// <summary>
/// ツクールMV/MZ等のゲームリソース(画像・音声・スクリプト等)における
/// URLエンコード名、文字化け、機種依存文字(丸数字等)の不整合を、
/// 「実際のゲームコード・データで使われているファイル名」と照合して並列かつ超高速に自動修復するサービス。
///
/// 設計方針:
/// - コード主導のピンポイント照合:
/// 1. data/*.json や plugins.js 等のゲームコード・定義データから要求リソース名を並列抽出。
/// 2. コード側が要求しているのにディスク上に存在しないファイル名(例: エロステ_ページ②.png)を特定。
/// 3. ディスク上の類似ファイル(エロステ_ページ2.png や URLデコード名)から要求通りのファイルを作成。
/// - マルチスレッド並列処理:
/// ・Parallel.ForEach による CPU コア全開の超高速走査・チェック・リンク生成。
/// - 独立ログファイル出力:
/// ・Logs フォルダ内に詳細ログファイル(ResourceRepair_*.log)を出力し、
/// ランチャー画面上のテキストボックス肥大化によるUIフリーズを完全防止。
/// </summary>
public class TkoolResourceRepairService
{
[DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);
/// <summary>修復完了キャッシュマーカーファイル名</summary>
public const string RepairMarkerFileName = ".gl_resource_repaired";
private static bool _encodingProviderRegistered;
// 丸数字マッピング (①: U+2460 〜 ⑳: U+2473)
private static readonly string[] CircleNumbers =
[
"①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩",
"⑪", "⑫", "⑬", "⑭", "⑮", "⑯", "⑰", "⑱", "⑲", "⑳"
];
// 全角数字マッピング (0: U+FF10 〜 9: U+FF19)
private static readonly string[] FullWidthNumbers =
[
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
];
public TkoolResourceRepairService()
{
EnsureEncodingProvider();
}
private static void EnsureEncodingProvider()
{
if (!_encodingProviderRegistered)
{
try
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
_encodingProviderRegistered = true;
}
catch { }
}
}
/// <summary>
/// 修復処理のリアルタイム進捗情報
/// </summary>
public record RepairProgress(int Current, int Total, int RepairedCount, string CurrentStatus);
/// <summary>
/// 修復処理の結果情報
/// </summary>
public record RepairResult(bool Success, int RepairedCount, int CleanedCount, long ElapsedMilliseconds, string Message, string LogFilePath);
/// <summary>
/// ログファイルの保存先ディレクトリを取得します。
/// </summary>
public static string GetLogsDirectory()
{
var exeDir = AppPathHelper.GetExeDirectory();
var logsDir = Path.Combine(exeDir, "Logs");
if (!Directory.Exists(logsDir))
{
Directory.CreateDirectory(logsDir);
}
return logsDir;
}
/// <summary>
/// 指定したツクールゲームのリソースファイルを非同期・並列で修復します(UIをブロックしません)。
/// </summary>
public Task<RepairResult> RepairGameResourcesAsync(
TkoolGameItem game,
bool forceRescan = false,
IProgress<RepairProgress>? progress = null,
Action<string>? uiLogCallback = null)
{
return Task.Run(() => this.RepairGameResources(game, forceRescan, progress, uiLogCallback));
}
/// <summary>
/// 指定したツクールゲームのリソースファイルを並列走査・コード照合修復します。
/// </summary>
public RepairResult RepairGameResources(
TkoolGameItem game,
bool forceRescan = false,
IProgress<RepairProgress>? progress = null,
Action<string>? uiLogCallback = null)
{
if (game == null)
{
return new RepairResult(false, 0, 0, 0, "対象ゲームが指定されていません。", string.Empty);
}
var sw = Stopwatch.StartNew();
// ログファイルの初期化
var logsDir = GetLogsDirectory();
var safeGameName = Regex.Replace(game.FolderName ?? game.Title ?? "Game", @"[\\/:*?""<>|]", "_");
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var logFilePath = Path.Combine(logsDir, $"ResourceRepair_{safeGameName}_{timestamp}.log");
var logLines = new ConcurrentBag<string>();
void FileLog(string message)
{
logLines.Add($"[{DateTime.Now:HH:mm:ss.fff}] {message}");
}
FileLog($"=== ゲームリソース高速並列修復開始 ===");
FileLog($"ゲーム名: {game.Title}");
FileLog($"ルートフォルダ: {game.RootDirectory}");
FileLog($"並列CPUコア数: {Environment.ProcessorCount}");
uiLogCallback?.Invoke($"[リソース修復] {game.Title}: ゲームコードとの並列照合を開始します...");
progress?.Report(new RepairProgress(0, 100, 0, "ゲームコード・データを収集中..."));
var targetDirs = this.CollectResourceDirectories(game);
if (targetDirs.Count == 0)
{
sw.Stop();
var msg = "修復対象のリソースディレクトリが見つかりませんでした。";
FileLog(msg);
this.WriteLogFile(logFilePath, logLines);
uiLogCallback?.Invoke($"[リソース修復] {msg}");
return new RepairResult(true, 0, 0, sw.ElapsedMilliseconds, msg, logFilePath);
}
// -------------------------------------------------------------
// ステップ 1: ゲームデータ (data/*.json, js/*.js) から要求リソース名を並列抽出
// -------------------------------------------------------------
FileLog("ステップ 1: data フォルダ内の JSON およびスクリプトから、コード上で実際に使用されているリソース名を並列抽出中...");
var requestedNames = this.ExtractRequestedResourceNamesFromCode(game, FileLog);
FileLog($"ステップ 1 完了: コード上で使われているリソース識別子を {requestedNames.Count} 件抽出しました。");
progress?.Report(new RepairProgress(20, 100, 0, $"コードリソース抽出完了 ({requestedNames.Count}件)"));
// -------------------------------------------------------------
// ステップ 2: 素材フォルダ (img, audio 等) の実ファイルを並列収集
// -------------------------------------------------------------
FileLog("ステップ 2: 素材フォルダ (img, audio 等) の全ファイルを並列収集・分類中...");
var resourceFiles = new ConcurrentBag<string>();
var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
Parallel.ForEach(targetDirs, parallelOptions, dir =>
{
if (!Directory.Exists(dir)) return;
try
{
foreach (var f in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories))
{
var name = Path.GetFileName(f);
if (!string.Equals(name, RepairMarkerFileName, StringComparison.OrdinalIgnoreCase))
{
resourceFiles.Add(f);
}
}
}
catch (Exception ex)
{
FileLog($"[警告] 一覧取得例外: {dir} ({ex.Message})");
}
});
var allFilesList = resourceFiles.ToList();
FileLog($"ステップ 2 完了: 素材ファイルを合計 {allFilesList.Count} 件検出しました。");
progress?.Report(new RepairProgress(40, 100, 0, $"素材ファイル収集完了 ({allFilesList.Count}件)"));
int repairedCount = 0;
int cleanedCount = 0;
// -------------------------------------------------------------
// ステップ 3: 過去の破損ファイル (%と丸数字の混在) の並列クリーンアップ
// -------------------------------------------------------------
Parallel.ForEach(allFilesList, parallelOptions, filePath =>
{
var fileName = Path.GetFileName(filePath);
if (fileName.Contains('%') && this.ContainsCircleNumber(fileName))
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
System.Threading.Interlocked.Increment(ref cleanedCount);
FileLog($"[不正ファイル削除] {fileName}");
}
}
catch { }
}
});
// -------------------------------------------------------------
// ステップ 4: パーセントエンコードされたファイル名の安全完全デコード (並列)
// -------------------------------------------------------------
FileLog("ステップ 4: URLエンコードされたファイル名の完全デコードと日本語リンク作成中 (並列)...");
var newlyDecodedFiles = new ConcurrentBag<string>();
Parallel.ForEach(allFilesList, parallelOptions, filePath =>
{
var fileName = Path.GetFileName(filePath);
if (fileName.Contains('%'))
{
try
{
var unescaped = this.FullyUnescapeString(fileName);
if (!string.Equals(unescaped, fileName, StringComparison.Ordinal) && !unescaped.Contains('%'))
{
var dirPath = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(dirPath))
{
var unescapedPath = Path.Combine(dirPath, unescaped);
if (!File.Exists(unescapedPath))
{
if (this.CreateLinkOrCopy(filePath, unescapedPath))
{
System.Threading.Interlocked.Increment(ref repairedCount);
newlyDecodedFiles.Add(unescapedPath);
FileLog($"[URLデコード作成] {fileName} -> {unescaped}");
}
}
}
}
}
catch { }
}
});
// ステップ4で新しく作成されたファイルも素材リストに合流
if (!newlyDecodedFiles.IsEmpty)
{
allFilesList.AddRange(newlyDecodedFiles);
}
progress?.Report(new RepairProgress(70, 100, repairedCount, "コード上のファイル名と実素材の照合中..."));
// -------------------------------------------------------------
// ステップ 5: コード上で要求されているファイル名と実素材の照合・表記揺れ解決 (並列)
// -------------------------------------------------------------
FileLog("ステップ 5: コード上で要求されているファイル名(丸数字など)と実素材の表記揺れ照合中 (並列)...");
// ディレクトリごとに実ファイル名辞書を作成(高速ルックアップ用)
var dirFilesMap = allFilesList
.GroupBy(f => Path.GetDirectoryName(f) ?? string.Empty)
.ToDictionary(g => g.Key, g => g.Select(p => Path.GetFileName(p)).ToHashSet(StringComparer.OrdinalIgnoreCase));
// ディレクトリごとに実ファイルの正規化キー辞書を作成(重複キーによるArgumentException例外を安全に回避)
var dirNormalizedMap = allFilesList
.GroupBy(f => Path.GetDirectoryName(f) ?? string.Empty)
.ToDictionary(g => g.Key, g =>
{
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var p in g)
{
var key = this.NormalizeFuzzyKey(Path.GetFileNameWithoutExtension(p));
if (!dict.ContainsKey(key))
{
dict[key] = p;
}
}
return dict;
});
// コードで要求されている各リソース名について照合
Parallel.ForEach(requestedNames, parallelOptions, reqName =>
{
var reqExt = Path.GetExtension(reqName);
var reqNameNoExt = string.IsNullOrEmpty(reqExt) ? reqName : Path.GetFileNameWithoutExtension(reqName);
var normalizedReq = this.NormalizeFuzzyKey(reqNameNoExt);
foreach (var (dirPath, fileSet) in dirFilesMap)
{
// 拡張子がある場合とない場合(.png を補完)を検討
var extensionsToCheck = string.IsNullOrEmpty(reqExt)
? new[] { ".png", ".ogg", ".m4a" }
: new[] { reqExt };
foreach (var ext in extensionsToCheck)
{
var expectedFileName = reqNameNoExt + ext;
// すでにその名前が存在していれば修復不要
if (fileSet.Contains(expectedFileName)) continue;
// ディレクトリ内に正規化キーが一致する実ファイルがあるか探す
if (dirNormalizedMap.TryGetValue(dirPath, out var normDict) &&
normDict.TryGetValue(normalizedReq, out var existingFilePath))
{
var existingExt = Path.GetExtension(existingFilePath);
if (string.Equals(existingExt, ext, StringComparison.OrdinalIgnoreCase))
{
var targetPath = Path.Combine(dirPath, expectedFileName);
if (!File.Exists(targetPath))
{
if (this.CreateLinkOrCopy(existingFilePath, targetPath))
{
System.Threading.Interlocked.Increment(ref repairedCount);
FileLog($"[コード要求リソース修復] コード要求名: {expectedFileName} <- 実ファイル: {Path.GetFileName(existingFilePath)}");
lock (fileSet) { fileSet.Add(expectedFileName); }
}
}
}
}
}
}
});
sw.Stop();
// ログファイルへの一括書き込み
FileLog($"=== 修復完了: 作成 {repairedCount} 件、クリーンアップ {cleanedCount} 件 (所要時間: {sw.ElapsedMilliseconds}ms) ===");
this.WriteLogFile(logFilePath, logLines);
var summaryMsg = $"リソース修復完了: コード要求照合により {repairedCount} 件作成、{cleanedCount} 件クリーンアップ (所要時間: {sw.ElapsedMilliseconds}ms)";
uiLogCallback?.Invoke($"[リソース修復] {summaryMsg}");
uiLogCallback?.Invoke($"[リソース修復] 詳細ログを出力しました: {logFilePath}");
progress?.Report(new RepairProgress(100, 100, repairedCount, "完了"));
return new RepairResult(true, repairedCount, cleanedCount, sw.ElapsedMilliseconds, summaryMsg, logFilePath);
}
/// <summary>
/// ゲームの data/*.json および js/*.js からコード上で要求されているリソース名を並列抽出します。
/// </summary>
private HashSet<string> ExtractRequestedResourceNamesFromCode(TkoolGameItem game, Action<string> log)
{
var requested = new ConcurrentBag<string>();
var dataDirs = new List<string>();
// data フォルダおよび js フォルダの探索
var roots = new List<string>();
if (game.IsEvbExtracted && !string.IsNullOrEmpty(game.EvbExtractedDirPath) && Directory.Exists(game.EvbExtractedDirPath))
{
roots.Add(game.EvbExtractedDirPath);
}
if (!string.IsNullOrEmpty(game.RootDirectory) && Directory.Exists(game.RootDirectory))
{
roots.Add(game.RootDirectory);
}
foreach (var r in roots)
{
var candidates = new[] { r, Path.Combine(r, "www") };
foreach (var c in candidates)
{
var dataPath = Path.Combine(c, "data");
if (Directory.Exists(dataPath) && !dataDirs.Contains(dataPath)) dataDirs.Add(dataPath);
var jsPath = Path.Combine(c, "js");
if (Directory.Exists(jsPath) && !dataDirs.Contains(jsPath)) dataDirs.Add(jsPath);
}
}
var textFiles = new List<string>();
foreach (var d in dataDirs)
{
try
{
textFiles.AddRange(Directory.GetFiles(d, "*.json", SearchOption.AllDirectories));
textFiles.AddRange(Directory.GetFiles(d, "*.js", SearchOption.AllDirectories));
}
catch { }
}
log($"コード検査対象ファイル数: {textFiles.Count} 件 (並列抽出)");
var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
Parallel.ForEach(textFiles, parallelOptions, file =>
{
try
{
var text = File.ReadAllText(file, Encoding.UTF8);
// JSON/JS文字列 "..." または '...' を抽出
var matches = Regex.Matches(text, @"""([^""\r\n]{1,80})""|'([^'\r\n]{1,80})'");
foreach (Match m in matches)
{
var val = (m.Groups[1].Success ? m.Groups[1].Value : m.Groups[2].Value).Trim();
// 素材名として意味のある文字列(日本語、丸数字、記号、拡張子付き等)を収集
if (this.IsPotentialResourceName(val))
{
requested.Add(val);
}
}
}
catch { }
});
return new HashSet<string>(requested, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// 文字列が画像・音声等のリソース名候補として適切か判定します。
/// </summary>
private bool IsPotentialResourceName(string text)
{
if (string.IsNullOrWhiteSpace(text) || text.Length > 80) return false;
// システム予約語やJSON構文は除外
if (text == "true" || text == "false" || text == "null" || text == "undefined") return false;
if (text.StartsWith("{") || text.StartsWith("[")) return false;
// 拡張子を持つ、または日本語/丸数字を含む、または _ や - を含む識別子
if (text.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
text.EndsWith(".ogg", StringComparison.OrdinalIgnoreCase) ||
text.EndsWith(".m4a", StringComparison.OrdinalIgnoreCase))
{
return true;
}
// 日本語・全角文字または丸数字を含む文字列(例: "エロステ_ページ②")
if (this.ContainsNonAscii(text) || this.ContainsCircleNumber(text))
{
// 空白のみや極端な記号列は除外
return !text.Contains("<") && !text.Contains(">");
}
return false;
}
/// <summary>
/// 丸数字(①〜⑳)⇔ 通常数字(1〜20)および 全角数字 を正規化したファジーマッチ用キーを生成します。
/// </summary>
private string NormalizeFuzzyKey(string text)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
var res = text.Normalize(NormalizationForm.FormC).ToLowerInvariant();
// 丸数字 -> 通常数字
for (int i = 0; i < CircleNumbers.Length; i++)
{
res = res.Replace(CircleNumbers[i], (i + 1).ToString());
}
// 全角数字 -> 半角数字
for (int i = 0; i < FullWidthNumbers.Length; i++)
{
res = res.Replace(FullWidthNumbers[i], i.ToString());
}
// 波ダッシュ・チルダ
res = res.Replace('\u301C', '\uFF5E');
// 全角カッコ -> 半角カッコ
res = res.Replace('(', '(').Replace(')', ')');
return res;
}
/// <summary>
/// 蓄積されたログ行をログファイルへ一括書き込みします。
/// </summary>
private void WriteLogFile(string path, IEnumerable<string> lines)
{
try
{
File.WriteAllLines(path, lines, new UTF8Encoding(true));
}
catch { }
}
/// <summary>
/// パーセントエンコードされた文字列を100%完全にデコードします。
/// </summary>
private string FullyUnescapeString(string input)
{
if (string.IsNullOrEmpty(input) || !input.Contains('%')) return input;
try
{
var unescaped = Uri.UnescapeDataString(input);
if (!unescaped.Contains('%')) return unescaped;
}
catch { }
try
{
return Regex.Replace(input, @"((?:%[0-9A-Fa-f]{2})+)", match =>
{
try
{
var hexPart = match.Value;
var bytes = new List<byte>();
for (int i = 0; i < hexPart.Length; i += 3)
{
if (hexPart[i] == '%' && i + 2 < hexPart.Length)
{
bytes.Add(Convert.ToByte(hexPart.Substring(i + 1, 2), 16));
}
}
return Encoding.UTF8.GetString(bytes.ToArray());
}
catch
{
return match.Value;
}
});
}
catch
{
return input;
}
}
/// <summary>
/// 丸数字が含まれているか判定します。
/// </summary>
private bool ContainsCircleNumber(string text)
{
if (string.IsNullOrEmpty(text)) return false;
foreach (var circle in CircleNumbers)
{
if (text.Contains(circle)) return true;
}
return false;
}
/// <summary>
/// 非ASCII文字(全角文字・日本語等)が含まれているか判定します。
/// </summary>
private bool ContainsNonAscii(string text)
{
if (string.IsNullOrEmpty(text)) return false;
foreach (char c in text)
{
if (c > 127) return true;
}
return false;
}
/// <summary>
/// ハードリンクを最優先で作成し、失敗した場合はファイルコピーを行います。
/// </summary>
private bool CreateLinkOrCopy(string sourceFile, string targetFile)
{
try
{
if (File.Exists(targetFile)) return true;
if (CreateHardLink(targetFile, sourceFile, IntPtr.Zero))
{
return true;
}
File.Copy(sourceFile, targetFile, overwrite: false);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 修復対象となるリソースフォルダ一覧(img, audio, js, data等)を収集します。
/// </summary>
private List<string> CollectResourceDirectories(TkoolGameItem game)
{
var result = new List<string>();
var roots = new List<string>();
if (game.IsEvbExtracted && !string.IsNullOrEmpty(game.EvbExtractedDirPath) && Directory.Exists(game.EvbExtractedDirPath))
{
roots.Add(game.EvbExtractedDirPath);
}
if (!string.IsNullOrEmpty(game.RootDirectory) && Directory.Exists(game.RootDirectory))
{
roots.Add(game.RootDirectory);
}
foreach (var root in roots)
{
var candidates = new[] { root, Path.Combine(root, "www"), Path.Combine(root, "package.nw") };
foreach (var baseDir in candidates)
{
if (!Directory.Exists(baseDir)) continue;
var subDirs = new[] { "img", "audio", "js", "data" };
foreach (var sub in subDirs)
{
var target = Path.Combine(baseDir, sub);
if (Directory.Exists(target) && !result.Contains(target))
{
result.Add(target);
}
}
}
}
return result;
}
}
}
+263
View File
@@ -0,0 +1,263 @@
/*:
* @target MZ MV
* @plugindesc 日本語・URLエンコード・文字化け・機種依存文字(丸数字等)の素材読み込み失敗を自動修復・救済します。
* @author GameLauncher
*
* @help
* 日本語ファイル名がURLエンコード(%E3%...)されたり、ファイル名と要求パスが
* 一致せず「Loading Error Failed to load」で停止してしまう現象を自動的に修復・救済します。
* 丸数字(①②...)と通常数字(1, 2...)の表記揺れやNW.jsのファイルシステム探索に対応しています。
*/
(() => {
'use strict';
const hasNode = typeof require === 'function' && typeof process === 'object';
const fs = hasNode ? require('fs') : null;
const path = hasNode ? require('path') : null;
// 1x1 透明 PNG (Data URL) - 万が一ファイルが見つからない場合のフォールバック用
const BLANK_PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
// 丸数字・ローマ数字・全角数字のマッピングテーブル
const CIRCLE_NUMBERS = ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩', '⑪', '⑫', '⑬', '⑭', '⑮', '⑯', '⑰', '⑱', '⑲', '⑳'];
/**
* 文字列内の丸数字や全角数字、波ダッシュ等を正規化して比較用キーを生成します。
* @param {string} str - 対象文字列
* @returns {string} 正規化文字列
*/
function normalizeFuzzy(str) {
if (!str) return '';
let res = str.normalize('NFC').toLowerCase();
// 丸数字 -> 通常数字
for (let i = 0; i < CIRCLE_NUMBERS.length; i++) {
res = res.replaceAll(CIRCLE_NUMBERS[i], String(i + 1));
}
// 全角数字 -> 半角数字
res = res.replace(/[0-9]/g, s => String.fromCharCode(s.charCodeAt(0) - 0xFEE0));
// 波ダッシュ・チルダ
res = res.replaceAll('\u301C', '\uFF5E');
// 全角カッコ -> 半角カッコ
res = res.replaceAll('(', '(').replaceAll(')', ')');
return res;
}
/**
* URLからファイルシステム上の実ファイルを探索します。
* @param {string} url - 読み込み対象のURL/相対パス
* @returns {string|null} 実ファイルの絶対パスまたは相対パス(見つからない場合はnull)
*/
function findActualFile(url) {
if (!fs || !path || !url) return null;
// クエリパラメータやハッシュを除去
const cleanUrl = url.split('?')[0].split('#')[0];
let decodedUrl = cleanUrl;
try {
decodedUrl = decodeURIComponent(cleanUrl);
} catch (e) { }
// 中途半端に % が残っている場合の再デコード
if (decodedUrl.includes('%')) {
try {
decodedUrl = decodedUrl.replace(/(%[0-9A-Fa-f]{2})+/g, match => {
try { return decodeURIComponent(match); } catch (e) { return match; }
});
} catch (e) { }
}
let encodedUrl = cleanUrl;
try {
const parts = cleanUrl.split('/');
encodedUrl = parts.map(p => encodeURIComponent(decodeURIComponent(p))).join('/');
} catch (e) { }
// 1. そのままのパスで存在するか
if (fs.existsSync(cleanUrl)) return cleanUrl;
// 2. URLデコードしたパスで存在するか
if (fs.existsSync(decodedUrl)) return decodedUrl;
// 3. URLエンコードしたパスで存在するか
if (fs.existsSync(encodedUrl)) return encodedUrl;
// 4. ディレクトリ内の実ファイルを走査して柔軟に検索(丸数字・表記揺れ対応)
try {
const dir = path.dirname(decodedUrl);
const targetBase = path.basename(decodedUrl);
const targetExt = path.extname(decodedUrl);
const targetNameWithoutExt = path.basename(decodedUrl, targetExt);
if (fs.existsSync(dir)) {
const files = fs.readdirSync(dir);
const fuzzyTarget = normalizeFuzzy(targetBase);
const fuzzyTargetWithoutExt = normalizeFuzzy(targetNameWithoutExt);
for (const file of files) {
const fileExt = path.extname(file);
const fileNameWithoutExt = path.basename(file, fileExt);
// A. 通常比較
if (file.toLowerCase() === targetBase.toLowerCase()) {
return path.join(dir, file);
}
// B. 表記揺れ(丸数字①⇔1、全角数字等)のファジーマッチ
const fuzzyFile = normalizeFuzzy(file);
const fuzzyFileWithoutExt = normalizeFuzzy(fileNameWithoutExt);
if (fuzzyFile === fuzzyTarget) {
return path.join(dir, file);
}
if (fuzzyFileWithoutExt === fuzzyTargetWithoutExt && fileExt.toLowerCase() === targetExt.toLowerCase()) {
return path.join(dir, file);
}
// C. URLエンコード/デコードされたファイル名との比較
try {
const decodedFile = decodeURIComponent(file);
if (normalizeFuzzy(decodedFile) === fuzzyTarget) {
return path.join(dir, file);
}
} catch (e) { }
}
}
} catch (e) { }
return null;
}
/**
* 実ファイルをBase64 DataURLとして読み込みます。
* @param {string} filePath - 実ファイルのパス
* @param {string} mimeType - MIMEタイプ
* @returns {string|null} DataURL
*/
function readFileAsDataUrl(filePath, mimeType = 'image/png') {
if (!fs || !filePath) return null;
try {
const buf = fs.readFileSync(filePath);
return `data:${mimeType};base64,${buf.toString('base64')}`;
} catch (e) {
return null;
}
}
// =========================================================================
// 1. Bitmap ロードの救済 (ツクールMV / MZ)
// =========================================================================
if (typeof Bitmap !== 'undefined') {
const _Bitmap_load = Bitmap.load;
Bitmap.load = function(url) {
if (fs && url) {
const actual = findActualFile(url);
if (actual && actual !== url) {
try {
const actualUrl = actual.replace(/\\/g, '/');
return _Bitmap_load.call(this, actualUrl);
} catch (e) { }
}
}
return _Bitmap_load.call(this, url);
};
const _Bitmap_prototype_onError = Bitmap.prototype._onError;
Bitmap.prototype._onError = function() {
if (!this._recoveryAttempted && this._url) {
this._recoveryAttempted = true;
const actualFile = findActualFile(this._url);
if (actualFile) {
const dataUrl = readFileAsDataUrl(actualFile, 'image/png');
if (dataUrl && this._image) {
console.log(`[GameLauncher] 画像の実ファイルを特定して自動救済: ${this._url} -> ${actualFile}`);
this._isLoading = true;
this._hasError = false;
this._image.src = dataUrl;
return;
}
}
// URLデコード版を直接 image.src に設定してリトライ
try {
const decoded = decodeURIComponent(this._url);
if (decoded !== this._url && this._image) {
this._isLoading = true;
this._hasError = false;
this._url = decoded;
this._image.src = decoded;
return;
}
} catch (e) { }
// 最終手段: ゲーム停止・クラッシュを回避するため透明PNGで代替
if (this._image) {
console.warn(`[GameLauncher] 未存在画像の透過代替を適用(エラー停止回避): ${this._url}`);
this._isLoading = false;
this._hasError = false;
this._image.src = BLANK_PNG;
if (typeof this._onLoad === 'function') {
try { this._onLoad(); } catch (e) { }
}
return;
}
}
_Bitmap_prototype_onError.call(this);
};
}
// =========================================================================
// 2. WebAudio / AudioManager ロードの救済 (ツクールMV / MZ)
// =========================================================================
if (typeof WebAudio !== 'undefined') {
const _WebAudio_prototype_load = WebAudio.prototype._load;
WebAudio.prototype._load = function(url) {
let targetUrl = url;
if (fs && url) {
const actual = findActualFile(url);
if (actual) {
targetUrl = actual.replace(/\\/g, '/');
}
}
return _WebAudio_prototype_load.call(this, targetUrl);
};
}
// =========================================================================
// 3. Graphics.printLoadingError のエラー停止緩和
// =========================================================================
if (typeof Graphics !== 'undefined' && Graphics.printLoadingError) {
const _Graphics_printLoadingError = Graphics.printLoadingError;
Graphics.printLoadingError = function(url) {
console.warn(`[GameLauncher] Loading Error が検出されました: ${url}`);
_Graphics_printLoadingError.call(this, url);
};
}
// =========================================================================
// 4. PluginManager スクリプト読み込みの救済
// =========================================================================
if (typeof PluginManager !== 'undefined' && PluginManager.loadScript) {
const _PluginManager_loadScript = PluginManager.loadScript;
PluginManager.loadScript = function(name) {
if (fs && name) {
const target = 'js/plugins/' + name;
const actual = findActualFile(target);
if (actual) {
const baseName = path.basename(actual);
return _PluginManager_loadScript.call(this, baseName);
}
}
return _PluginManager_loadScript.call(this, name);
};
}
console.log('[GameLauncher] ResourceLoaderFix プラグインが正常にロードされました。');
})();