Files
GameLauncher/plugins/ResourceLoaderFix.js
T
armonica 4398f80aa4 feat(tkool): リソース修復サービスおよび文字化け・URLエンコード救済プラグインを追加
- ツクールMV/MZの日本語ファイル名・URLエンコード・丸数字表記揺れを並列修復する TkoolResourceRepairService を追加
- ゲーム起動時に読み込み不整合を動的に解決する必須救済プラグイン ResourceLoaderFix.js を追加
- TkoolModService にて ResourceLoaderFix を最優先で適用するよう対応
2026-10-14 09:57:54 +09:00

264 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*:
* @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 プラグインが正常にロードされました。');
})();