发布咸鱼喵喵截图辅助工具公开版

This commit is contained in:
2026-10-03 01:16:35 +08:00
commit 178e1d8714
26 changed files with 5694 additions and 0 deletions
+26
View File
@@ -0,0 +1,26 @@
# 咸鱼喵喵截图辅助工具:简单使用方法
一个在浏览器里操作的本地辅助工具,支持剧情全文搜索、传送、播放对白、角色摆拍,以及角色数值和背包调整,方便回看剧情和截图。
需要 Windows、已安装的《咸鱼喵喵》、[Node.js 22 或更新版本](https://nodejs.org/),以及 [NW.js SDK 0.64.1(Windows x64)](https://dl.nwjs.io/v0.64.1/nwjs-sdk-v0.64.1-win-x64.zip)。发布包不含游戏本体、存档、完整剧本和上述运行环境;无需 npm install。
1. 将包内的 `aitemp截图工具` 文件夹放进游戏安装目录,与游戏的 `package.json` 同级。可从 Steam 的“管理 → 浏览本地文件”找到游戏目录。
2. 解压 NW.js SDK,把 `nwjs-sdk-v0.64.1-win-x64` 文件夹放进 `aitemp截图工具`。确认路径如下,别多套一层文件夹:
```text
游戏目录/
package.json
aitemp截图工具/
tool/启动.bat
nwjs-sdk-v0.64.1-win-x64/nw.exe
out/triggers.csv
unpacked/data/...
```
3. 先在原游戏中正常保存一次并退出。双击 `tool/启动.bat`,首次选择 **1:只启动面板**,在“存档与沙盒”页创建游戏副本。副本需要额外磁盘空间,默认放在游戏所在盘的 `Nyaruru_shots` 文件夹。
4. 副本创建完成后,再次双击 `启动.bat`,工具会备份存档并启动副本游戏。在游戏里正常读档进入地图,确认面板顶部连接的是沙盒。
5. 在面板搜索台词或故事编号,按需要选择“前往”“运行过场”或“只播台词”;摆拍后可点“撤销场景还原”。全文台词在连接游戏后自动读取,断开连接后清空。
面板默认地址为 `http://127.0.0.1:8787`。用完双击 `tool/停止面板.bat`,游戏窗口另行关闭。升级前先退出旧面板和游戏。
建议始终在沙盒里使用:剧情操作可能改变进度,自动存档和手动保存照常生效。“全部还原”会解除临时效果和锁定,但不会回退已经改过的数值、背包或剧情进度;摆拍状态也不保证能通过读档完整恢复。详细说明见包内 `tool/使用须知.md`。
+106
View File
@@ -0,0 +1,106 @@
const fs = require('fs');
const path = require('path');
const net = require('net');
const { spawn } = require('child_process');
const readline = require('readline/promises');
const { readConfig, samePath } = require('./lib/safety');
const FILES = require('./lib/files');
const { CdpClient } = require('./lib/cdp');
const { OPS } = require('./lib/ops');
const TOOL = __dirname, AITEMP = path.dirname(TOOL), GAME = path.dirname(AITEMP);
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function listening(port) {
return new Promise(resolve => {
const s = net.connect({ host: '127.0.0.1', port });
const finish = yes => { s.destroy(); resolve(yes); };
s.once('connect', () => finish(true)); s.once('error', () => finish(false)); s.setTimeout(1000, () => finish(false));
});
}
async function panel(config, matchConfig = true) {
const r = await fetch(`http://127.0.0.1:${config.webPort}/api/health`, { signal: AbortSignal.timeout(1500) });
const data = await r.json();
if (!r.ok || data.version !== 2 || !data.toolDir || !samePath(data.toolDir, TOOL) || (matchConfig && JSON.stringify(data.config) !== JSON.stringify(config))) {
throw new Error('面板端口运行的是旧服务、其他版本或旧配置。请先关闭那个面板服务,再重新启动');
}
return data;
}
async function main() {
if (Number(process.versions.node.split('.')[0]) < 22) throw new Error('需要 Node.js 22 或更新版本');
const config = readConfig(path.join(TOOL, 'config.json'), { cdpPort: 9223, sandboxDir: path.join(path.parse(GAME).root, 'Nyaruru_shots'), webPort: 8787 }, GAME);
if (process.argv.includes('--stop')) {
const runtimeFile = path.join(TOOL, '.server-runtime.json');
const port = fs.existsSync(runtimeFile) ? JSON.parse(fs.readFileSync(runtimeFile, 'utf8')).port : config.webPort;
await panel({ ...config, webPort: port }, false);
await fetch(`http://127.0.0.1:${port}/api/shutdown`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
console.log('控制面板服务已停止,游戏窗口保留'); return;
}
const runtimeFile = path.join(TOOL, '.server-runtime.json');
if (fs.existsSync(runtimeFile)) {
const runtime = JSON.parse(fs.readFileSync(runtimeFile, 'utf8'));
if (runtime.port !== config.webPort && await listening(runtime.port)) {
await panel({ ...config, webPort: runtime.port }, false);
throw new Error('旧面板仍在原端口运行,请先双击“停止面板.bat”,再重新启动');
}
}
console.log('咸鱼喵喵 · 截图辅助工具\n调试端口 ' + config.cdpPort + ' / 面板端口 ' + config.webPort);
const panelRunning = await listening(config.webPort);
if (panelRunning) await panel(config);
const status = FILES.sandboxStatus(GAME, config.sandboxDir, AITEMP);
let target = status.ready ? config.sandboxDir : null;
if (!status.ready) {
console.log('沙盒尚不可用:' + status.reason + '\n[1] 只启动面板,创建沙盒\n[2] 启动原版游戏\n[3] 退出');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
let choice; try { choice = (await rl.question('请选择(默认 1):')).trim(); } finally { rl.close(); }
if (choice === '3') { console.log('已退出'); return; }
if (choice === '2') target = GAME;
else if (choice && choice !== '1') throw new Error('无效选择,已退出');
}
if (target) {
const occupied = await listening(config.cdpPort);
if (occupied) {
const client = new CdpClient(config.cdpPort);
try {
const info = await client.evalJson(OPS.selfPath());
if (!info.ok || !info.gameDir || !samePath(info.gameDir, target) || !info.saveDir || !samePath(info.saveDir, path.join(target, 'save'))) {
throw new Error('调试端口上的游戏与目标不符。期望:' + target + ';实际:' + (info.gameDir || '未知'));
}
} catch (e) { throw new Error('未启动面板:不能确认已有游戏实例。' + e.message); }
finally { client.close(); }
}
const backup = FILES.backupSaves(path.join(AITEMP, 'backups'), target, samePath(target, GAME) ? 'original' : 'sandbox');
console.log('存档已备份并校验:' + backup.name);
if (!occupied) {
const nw = path.join(AITEMP, 'nwjs-sdk-v0.64.1-win-x64', 'nw.exe');
if (!fs.existsSync(nw)) throw new Error('缺少 SDK 版 NW.js 0.64.1:' + nw + '\n下载:https://dl.nwjs.io/v0.64.1/nwjs-sdk-v0.64.1-win-x64.zip');
const child = spawn(nw, [target, '--remote-debugging-port=' + config.cdpPort], { cwd: path.dirname(nw), detached: true, stdio: 'ignore', windowsHide: true });
await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); child.unref();
const client = new CdpClient(config.cdpPort);
let ready = false;
try {
for (let i = 0; i < 20; i++) {
try {
const info = await client.evalJson(OPS.selfPath());
if (!info.ok || !info.gameDir || !samePath(info.gameDir, target) || !info.saveDir || !samePath(info.saveDir, path.join(target, 'save'))) throw new Error('实际游戏路径不符');
ready = true; break;
} catch { client.close(); await sleep(500); }
}
} finally { client.close(); }
if (!ready) throw new Error('游戏未能就绪或实例身份不符,未启动面板。请检查游戏窗口');
}
console.log('当前游戏:' + target);
}
if (!panelRunning) {
const log = fs.openSync(path.join(TOOL, 'server.log'), 'a');
const child = spawn(process.execPath, [path.join(TOOL, 'server.js')], { cwd: TOOL, detached: true, stdio: ['ignore', log, log], windowsHide: true });
await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); child.unref(); fs.closeSync(log);
let ready = false;
for (let i = 0; i < 20; i++) { try { await panel(config); ready = true; break; } catch { await sleep(300); } }
if (!ready) throw new Error('面板启动失败,请查看 tool/server.log');
}
const url = `http://127.0.0.1:${config.webPort}`;
const browser = spawn('rundll32.exe', ['url.dll,FileProtocolHandler', url], { detached: true, stdio: 'ignore', windowsHide: true });
browser.on('error', () => console.log('请手动打开:' + url)); browser.unref();
console.log('面板已就绪:' + url + (target ? '' : '\n本次没有启动游戏。创建沙盒后再次运行启动.bat'));
}
if (require.main === module) main().catch(e => { console.error('\n启动停止:' + e.message); process.exitCode = 1; });
module.exports = { main, listening, panel };
+97
View File
@@ -0,0 +1,97 @@
// 单连接 CDP 客户端,要求 Node.js 22+(内置 fetch / WebSocket)。
const RECONNECT_DELAY_MS = 3000;
class CdpClient {
constructor(port = 9223) {
this.port = port; this.ws = null; this.sessionId = null;
this._id = 0; this._pending = new Map(); this._connecting = null; this.generation = 0;
}
get base() { return `http://127.0.0.1:${this.port}`; }
async isAlive() {
try {
const r = await fetch(`${this.base}/json/version`, { signal: AbortSignal.timeout(1500) });
return r.ok && !!(await r.json()).webSocketDebuggerUrl;
} catch { return false; }
}
connect() {
if (this.ws?.readyState === 1 && this.sessionId) return Promise.resolve();
if (this._connecting) return this._connecting;
const generation = ++this.generation;
const attempt = this._connect(generation);
this._connecting = attempt;
attempt.finally(() => { if (this._connecting === attempt) this._connecting = null; }).catch(() => {});
return attempt;
}
async _connect(generation) {
let ws;
try {
const r = await fetch(`${this.base}/json/version`, { signal: AbortSignal.timeout(3000) });
if (!r.ok) throw new Error('调试端口没有返回 CDP 信息');
const v = await r.json();
if (this.generation !== generation) throw new Error('连接已取消');
ws = new WebSocket(v.webSocketDebuggerUrl);
this.ws = ws;
await new Promise((resolve, reject) => {
const timer = setTimeout(() => { reject(new Error('连接游戏超时')); try { ws.close(); } catch {} }, 4000);
const fail = () => { clearTimeout(timer); reject(new Error('无法建立游戏调试连接')); };
ws.onopen = () => { clearTimeout(timer); resolve(); };
ws.onerror = fail; ws.onclose = fail;
});
if (this.generation !== generation) throw new Error('连接已取消');
ws.onmessage = ev => {
let msg; try { msg = JSON.parse(ev.data); } catch { return; }
const p = this._pending.get(msg.id);
if (p && p.ws === ws) {
this._pending.delete(msg.id); clearTimeout(p.timer);
if (msg.error) p.reject(new Error(JSON.stringify(msg.error))); else p.resolve(msg.result);
}
if (msg.method === 'Target.detachedFromTarget' && msg.params?.sessionId === this.sessionId && this.ws === ws) this.close();
};
ws.onclose = () => this._drop(ws, new Error('游戏连接已断开'));
ws.onerror = () => { this._drop(ws, new Error('游戏调试连接出错')); try { ws.close(); } catch {} };
const { targetInfos } = await this._send('Target.getTargets', {}, false);
const pages = targetInfos.filter(t => t.type === 'page' && /\/index\.html?(?:[?#]|$)/i.test(t.url || ''));
if (pages.length !== 1) throw new Error('无法唯一识别游戏主页面,请关闭多余游戏窗口');
const { sessionId } = await this._send('Target.attachToTarget', { targetId: pages[0].targetId, flatten: true }, false);
if (this.ws !== ws || this.generation !== generation) throw new Error('连接已更换');
this.sessionId = sessionId;
} catch (e) {
if (ws) { this._drop(ws, e); try { ws.close(); } catch {} }
throw e;
}
}
_drop(ws, error) {
for (const [id, p] of this._pending) if (p.ws === ws) {
clearTimeout(p.timer); p.reject(error); this._pending.delete(id);
}
if (this.ws === ws) { this.ws = null; this.sessionId = null; }
}
_send(method, params = {}, session = true) {
const ws = this.ws;
if (!ws || ws.readyState !== 1) return Promise.reject(new Error('游戏连接已断开'));
const id = ++this._id, payload = { id, method, params };
if (session && this.sessionId) payload.sessionId = this.sessionId;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => { this._pending.delete(id); reject(new Error(`CDP 调用超时: ${method};不要立即重复操作,请先检查游戏状态`)); }, 20000);
this._pending.set(id, { resolve, reject, timer, ws });
try { ws.send(JSON.stringify(payload)); }
catch (e) { clearTimeout(timer); this._pending.delete(id); reject(e); }
});
}
async eval(expression) {
await this.connect();
const res = await this._send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
if (res.exceptionDetails) throw new Error(res.exceptionDetails.exception?.description || res.exceptionDetails.text);
return res.result?.value;
}
async evalJson(expression) {
const value = await this.eval(expression);
return typeof value === 'string' ? JSON.parse(value) : value;
}
async screenshot() { await this.connect(); return (await this._send('Page.captureScreenshot', { format: 'png' })).data; }
close() {
++this.generation; this._connecting = null;
const ws = this.ws;
if (ws) { this._drop(ws, new Error('游戏连接已关闭或切换')); try { ws.close(); } catch {} }
}
}
module.exports = { CdpClient, RECONNECT_DELAY_MS };
+216
View File
@@ -0,0 +1,216 @@
// 静态数据加载
//
// 数据来源全部是**之前分析阶段已产出的本地文件**(aitemp/out 和 aietmp/unpacked),
// 工具运行时只读它们,不碰游戏目录里的任何文件。
//
// unpacked/data/System.json → 360 个开关的中文名
// unpacked/data/MapInfos.json → 393 张地图
// out/triggers.csv → 897 条剧情触发点(其中 731 条有坐标)
//
// ⚠️ **台词不在这里。** 这是"C 方案"(见开发文档 12.5)的核心约定:
// 随包分发的只有**结构索引**(哪里有个触发点),
// 一个字创作内容都不带。台词在连上游戏后从 `$dataStory` 实时读,
// 只存在于内存,**绝不落盘**(读取逻辑在 lib/ops.js 的 readStoryIndex)。
//
// 历史:早期版本这里有个 loadStoryIndex(),启动时读 ../out/story.json
// (1.9 MB,全部 870 条剧情的完整台词)。那是作者的原创剧本,
// 随包外传等于分发游戏内容,发布版必须去掉。
const fs = require('fs');
const path = require('path');
/** 极简 CSV 解析(RFC4180:支持引号包裹、字段内逗号、双引号转义) */
function parseCsv(text) {
const rows = [];
let row = [], field = '', inQuotes = false;
// 去掉 BOM
if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1);
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (inQuotes) {
if (c === '"') {
if (text[i + 1] === '"') { field += '"'; i++; }
else inQuotes = false;
} else field += c;
} else if (c === '"') {
inQuotes = true;
} else if (c === ',') {
row.push(field); field = '';
} else if (c === '\n') {
row.push(field); rows.push(row); row = []; field = '';
} else if (c !== '\r') {
field += c;
}
}
if (field !== '' || row.length) { row.push(field); rows.push(row); }
return rows;
}
function readJson(file) {
return JSON.parse(fs.readFileSync(file, 'utf8'));
}
/**
* 载入每张地图的 BGM 名,用来做**粗略的区域提示**。
*
* 游戏的地图在 MapInfos.json 里只有 "MAP170" 这种编号,没有地点名
* (Map*.json 里的 displayName 和 meta 都是空的)。
* 但 BGM 文件名有区分度:cave(24张) / black_forest(26张) / lake(23张)…
* 所以拿它当"这片区域大概是什么"的线索,聊胜于无。
*/
const AREA_NAMES = {
cave: '洞窟', black_forest: '黑森林', lake: '湖畔',
town: '城镇', boss: 'Boss 战', title: '标题',
};
function loadMapAreas(dataDir) {
const areas = new Map();
let files;
try { files = fs.readdirSync(dataDir); } catch { return areas; }
for (const f of files) {
const m = /^Map(\d+)\.json$/.exec(f);
if (!m) continue;
try {
const d = readJson(path.join(dataDir, f));
const bgm = (d.bgm && d.bgm.name) || '';
if (bgm) areas.set(Number(m[1]), AREA_NAMES[bgm] || bgm);
} catch { /* 个别地图文件损坏不影响整体 */ }
}
return areas;
}
/**
* 载入全部静态数据。
* @param {string} baseDir aitemp 目录
*/
function loadAll(baseDir) {
const outDir = path.join(baseDir, 'out');
const dataDir = path.join(baseDir, 'unpacked', 'data');
// ---- 开关 ----
const sys = readJson(path.join(dataDir, 'System.json'));
const switches = [];
const switchNameToId = new Map();
for (let i = 1; i < sys.switches.length; i++) {
const name = sys.switches[i];
if (name === undefined || name === null) continue;
switches.push({ id: i, name: String(name) });
// 同名开关极少见,出现时保留首个
if (!switchNameToId.has(String(name))) switchNameToId.set(String(name), i);
}
// ---- 变量 ----
const variables = [];
for (let i = 1; i < sys.variables.length; i++) {
const name = sys.variables[i];
if (name === undefined || name === null) continue;
variables.push({ id: i, name: String(name) });
}
// ---- 地图 ----
const mapInfos = readJson(path.join(dataDir, 'MapInfos.json'));
const maps = mapInfos
.filter(m => m && m.id)
.map(m => ({ id: m.id, name: String(m.name || ''), parentId: m.parentId || 0 }));
// ---- 区域名 ----
// 台词**不在这里**:它由 server.js 在连上游戏后从 $dataStory 实时补进内存
const mapAreas = loadMapAreas(dataDir);
// ---- 剧情触发点 ----
const csvPath = path.join(outDir, 'triggers.csv');
const raw = parseCsv(fs.readFileSync(csvPath, 'utf8'));
const header = raw[0];
const col = (row, key) => row[header.indexOf(key)] ?? '';
const triggers = [];
for (let i = 1; i < raw.length; i++) {
const r = raw[i];
if (!r || r.length < 2) continue;
// 地图字段形如 "Map004.json MAP004",从中取出数字 ID
const mapField = col(r, '地图');
const mapMatch = /Map0*(\d+)\.json/i.exec(mapField);
const mapId = mapMatch ? Number(mapMatch[1]) : null;
// 坐标字段形如 "(0,0)"
const coordField = col(r, '坐标');
const coordMatch = /\(\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(coordField);
const x = coordMatch ? Number(coordMatch[1]) : null;
const y = coordMatch ? Number(coordMatch[2]) : null;
const condition = col(r, '条件').trim();
// 条件里引用的开关名(形如 开关[第一天夜晚莉莉亚回家](需ON))
const needSwitchNames = [];
for (const m of condition.matchAll(/开关\[([^\]]+)\]/g)) needSwitchNames.push(m[1]);
const needVarNames = [];
for (const m of condition.matchAll(/变量\[([^\]]+)\]/g)) needVarNames.push(m[1]);
const storyId = Number(col(r, '故事序号')) || 0;
triggers.push({
storyId,
source: col(r, '来源'),
mapId,
mapArea: mapId !== null ? (mapAreas.get(mapId) || '') : '',
eventId: col(r, '事件ID'),
eventName: col(r, '事件名'),
x, y,
page: col(r, '页'),
pageIndex: /^\d+\//.test(col(r, '页')) ? Number(col(r, '页').split('/')[0]) - 1 : null,
triggerType: col(r, '触发方式'),
condition,
needSwitchNames,
needVarNames,
// ⚠️ 这里**故意没有** line / speaker / lineCount —— 只有 storyId。
// UI 上那句台词预览由 server.js 在拼响应时从内存里的台词表补上
// (见 /api/triggers),没连游戏时就是空的,前端退回显示地图+坐标。
// 有地图和坐标的才能"一键前往"
actionable: mapId !== null && x !== null && y !== null,
});
}
// 仅合并完全相同的候选;不同事件、页和条件必须保留。
const seen = new Set();
const uniqueTriggers = [];
for (const t of triggers) {
const k = `${t.storyId}|${t.mapId}|${t.eventId}|${t.page}|${t.x}|${t.y}|${t.condition}`;
if (seen.has(k)) continue;
seen.add(k);
uniqueTriggers.push(t);
}
// ---- 常用开关:被触发点条件引用到的那些 ----
// 这是"截图工作真正会用到的开关"的精确集合,用来做开关面板的默认视图
const commonSwitchIds = [];
for (const name of new Set(uniqueTriggers.flatMap(t => t.needSwitchNames))) {
const id = switchNameToId.get(name);
if (id !== undefined) commonSwitchIds.push(id);
}
commonSwitchIds.sort((a, b) => a - b);
return {
switches,
variables,
maps,
triggers: uniqueTriggers,
commonSwitchIds,
switchNameToId,
stats: {
switches: switches.length,
variables: variables.length,
maps: maps.length,
triggersTotal: triggers.length,
triggersUnique: uniqueTriggers.length,
triggersActionable: uniqueTriggers.filter(t => t.actionable).length,
commonSwitches: commonSwitchIds.length,
mapAreas: mapAreas.size,
// 注意:storyLoaded / triggersWithLine **不在这里** ——
// 台词要连上游戏才知道,它们是运行时值,由 server.js 的 /api/status 现算。
},
};
}
module.exports = { loadAll, parseCsv };
+145
View File
@@ -0,0 +1,145 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { execFile } = require('child_process');
const { canonical, samePath, contains } = require('./safety');
const MANIFEST = 'backup-manifest.json';
const COMPLETE = '.nyaruru-sandbox-complete.json';
const INCOMPLETE = '.nyaruru-sandbox-incomplete';
const hash = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
const saveNames = dir => fs.existsSync(dir) ? fs.readdirSync(dir).filter(n => /\.rmmzsave$/i.test(n)).sort() : [];
function safeFile(dir, name) {
if (path.basename(name) !== name || !/\.rmmzsave$/i.test(name)) throw new Error('非法存档文件名');
const file = path.join(dir, name), st = fs.lstatSync(file);
if (!st.isFile() || st.isSymbolicLink()) throw new Error('存档必须是普通文件:' + name);
return file;
}
function backupSaves(root, sourceDir, label = 'auto') {
const saveDir = path.join(canonical(sourceDir), 'save');
if (!fs.existsSync(saveDir) || !samePath(saveDir, path.join(sourceDir, 'save')) || fs.lstatSync(saveDir).isSymbolicLink()) throw new Error('存档目录不存在或是目录链接');
const names = saveNames(saveDir);
if (!names.length) throw new Error('没有找到 .rmmzsave 存档,未创建空备份');
fs.mkdirSync(root, { recursive: true });
const dest = fs.mkdtempSync(path.join(root, `${label.replace(/[^a-z0-9_-]/gi, '')}_${new Date().toISOString().replace(/[:.]/g, '-')}_`));
// 未完成目录没有 manifest,不会被列为可恢复备份。
const files = names.map(name => ({ name, sha256: hash(safeFile(saveDir, name)) }));
for (const f of files) fs.copyFileSync(safeFile(saveDir, f.name), path.join(dest, f.name), fs.constants.COPYFILE_EXCL);
if (JSON.stringify(names) !== JSON.stringify(saveNames(saveDir)) || files.some(f => hash(safeFile(saveDir, f.name)) !== f.sha256 || hash(path.join(dest, f.name)) !== f.sha256)) {
throw new Error('备份期间存档发生变化或复制校验失败,请停止存档操作后重试。未完成目录:' + dest);
}
const manifest = { version: 1, sourceDir: canonical(sourceDir), createdAt: new Date().toISOString(), files };
fs.writeFileSync(path.join(dest, MANIFEST), JSON.stringify(manifest, null, 2), { flag: 'wx' });
return { dir: dest, name: path.basename(dest), files: files.length, from: saveDir };
}
function inspectBackup(root, name) {
if (typeof name !== 'string' || name === '.' || name === '..' || /[\\/:]/.test(name)) throw new Error('非法备份名');
const dir = path.join(root, name);
if (!fs.existsSync(dir) || fs.lstatSync(dir).isSymbolicLink() || !fs.statSync(dir).isDirectory()) throw new Error('备份不存在或是目录链接');
let manifest = null;
const meta = path.join(dir, MANIFEST);
if (fs.existsSync(meta)) {
manifest = JSON.parse(fs.readFileSync(meta, 'utf8'));
if (!Array.isArray(manifest.files) || !manifest.files.length) throw new Error('备份清单无效');
} else if (!/^\d{8}_\d{6}$|^[a-z][a-z0-9_-]*_\d{8}_\d{6}$/i.test(name)) {
throw new Error('备份没有完成标记');
}
const files = manifest ? manifest.files : saveNames(dir).map(name => ({ name }));
if (!files.length || new Set(files.map(f => f.name)).size !== files.length) throw new Error('备份为空或文件重复');
for (const f of files) {
const digest = hash(safeFile(dir, f.name));
if (f.sha256 && digest !== f.sha256) throw new Error('备份内容校验失败:' + f.name);
f.sha256 = digest;
}
return { dir, manifest, files };
}
function listBackups(root) {
if (!fs.existsSync(root)) return [];
return fs.readdirSync(root).flatMap(name => {
try {
const b = inspectBackup(root, name);
return [{ name, files: b.files.length, sourceDir: b.manifest?.sourceDir || null, legacy: !b.manifest, mtime: fs.statSync(b.dir).mtimeMs }];
} catch { return []; }
}).sort((a, b) => b.mtime - a.mtime);
}
function restoreBackup(root, name, targetDir) {
const b = inspectBackup(root, name);
const target = canonical(targetDir), saveDir = path.join(target, 'save');
if (fs.existsSync(saveDir) && fs.lstatSync(saveDir).isSymbolicLink()) throw new Error('不能还原到存档目录链接');
const safety = saveNames(saveDir).length ? backupSaves(root, target, 'prerestore') : null;
const stage = fs.mkdtempSync(path.join(target, '.save-restore-'));
// 保留云配置等非存档文件;存档集合严格来自选中的备份。
if (fs.existsSync(saveDir)) {
for (const entry of fs.readdirSync(saveDir, { withFileTypes: true })) {
if (entry.isSymbolicLink() || entry.isDirectory()) throw new Error('存档目录含链接或子目录,停止还原');
if (!/\.rmmzsave$/i.test(entry.name)) fs.copyFileSync(path.join(saveDir, entry.name), path.join(stage, entry.name));
}
}
for (const f of b.files) {
fs.copyFileSync(path.join(b.dir, f.name), path.join(stage, f.name));
if (hash(path.join(stage, f.name)) !== f.sha256) throw new Error('还原暂存校验失败');
}
const old = path.join(target, `.save-before-restore-${crypto.randomUUID()}`);
const hadSave = fs.existsSync(saveDir);
if (hadSave) fs.renameSync(saveDir, old);
try { fs.renameSync(stage, saveDir); }
catch (e) { if (hadSave) fs.renameSync(old, saveDir); throw e; }
return { restored: b.files.length, target: saveDir, safetyBackup: safety?.name || null, previousDirectory: hadSave ? old : null };
}
function excludedDirs(gameDir, toolDir) {
return fs.readdirSync(gameDir, { withFileTypes: true }).filter(e => e.isDirectory() && (
/^aitemp/i.test(e.name) || samePath(path.join(gameDir, e.name), toolDir) || fs.existsSync(path.join(gameDir, e.name, 'tool', 'server.js'))
)).map(e => path.join(gameDir, e.name));
}
function gameFiles(gameDir, excluded) {
const result = [];
function walk(dir, prefix = '') {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const file = path.join(dir, e.name), rel = path.join(prefix, e.name);
if (!prefix && (['save', 'error', 'debug.log'].includes(e.name.toLowerCase()) || /^aitemp/i.test(e.name) || e.name.startsWith('.save-') || excluded.some(d => samePath(d, file)))) continue;
if (e.isSymbolicLink()) throw new Error('游戏目录含链接,无法验证完整副本:' + rel);
if (e.isDirectory()) walk(file, rel);
else if (e.isFile()) result.push({ name: rel, size: fs.statSync(file).size });
}
}
walk(gameDir); return result;
}
function sandboxStatus(gameDir, sandboxDir, toolDir, checkingCopy = false) {
try {
if (contains(gameDir, sandboxDir) || contains(sandboxDir, gameDir)) return { ready: false, reason: '沙盒路径与原版重叠' };
if (!fs.existsSync(sandboxDir)) return { ready: false, reason: '尚未创建' };
if (!checkingCopy && fs.existsSync(path.join(sandboxDir, INCOMPLETE))) return { ready: false, reason: '上次复制尚未完成,请另选空目录重新创建' };
const required = gameFiles(gameDir, excludedDirs(gameDir, toolDir));
if (!required.some(f => f.name === 'package.json') || !required.some(f => f.name === 'index.html')) throw new Error('原版游戏目录不完整');
const bad = required.find(f => {
const dest = path.join(sandboxDir, f.name);
return !fs.existsSync(dest) || !fs.statSync(dest).isFile() || fs.statSync(dest).size !== f.size || !contains(sandboxDir, canonical(dest));
});
if (bad) return { ready: false, reason: '副本缺失或大小不符:' + bad.name };
return { ready: true, legacy: !fs.existsSync(path.join(sandboxDir, COMPLETE)), files: required.length };
} catch (e) { return { ready: false, reason: e.message }; }
}
function copySandbox(gameDir, sandboxDir, toolDir) {
if (contains(gameDir, sandboxDir) || contains(sandboxDir, gameDir)) throw new Error('沙盒路径与原版重叠');
if (fs.existsSync(sandboxDir) && fs.readdirSync(sandboxDir).length) throw new Error('目标目录非空,不能覆盖;请选择新的空目录');
const excluded = excludedDirs(gameDir, toolDir);
const originalSave = path.join(gameDir, 'save');
const saves = saveNames(originalSave).map(name => ({ name, sha256: hash(safeFile(originalSave, name)) }));
if (!saves.length) throw new Error('原版没有存档,请先正常开始游戏并保存');
fs.mkdirSync(sandboxDir, { recursive: true });
fs.writeFileSync(path.join(sandboxDir, INCOMPLETE), new Date().toISOString(), { flag: 'wx' });
return new Promise((resolve, reject) => {
execFile('robocopy', [gameDir, sandboxDir, '/E', '/XJ', '/NFL', '/NDL', '/NJH', '/NJS', '/NP', '/R:1', '/W:1', '/XF', 'aitemp*', 'debug.log', '/XD', ...excluded, 'error', '.save-*'],
{ windowsHide: true, maxBuffer: 32 * 1024 * 1024 }, (err, out, stderr) => {
try {
if (err && !(Number.isInteger(err.code) && err.code <= 7 && err.code >= 0)) throw new Error(stderr || err.message);
const status = sandboxStatus(gameDir, sandboxDir, toolDir, true);
if (!status.ready) throw new Error(status.reason);
if (JSON.stringify(saveNames(originalSave)) !== JSON.stringify(saves.map(f => f.name)) || saves.some(f => hash(safeFile(originalSave, f.name)) !== f.sha256 || hash(safeFile(path.join(sandboxDir, 'save'), f.name)) !== f.sha256)) throw new Error('复制期间存档发生变化或副本校验失败,请退出游戏后重建');
fs.writeFileSync(path.join(sandboxDir, COMPLETE), JSON.stringify({ createdAt: new Date().toISOString(), files: status.files }));
fs.unlinkSync(path.join(sandboxDir, INCOMPLETE));
resolve(status);
} catch (e) { reject(e); }
});
});
}
module.exports = { backupSaves, listBackups, restoreBackup, inspectBackup, sandboxStatus, copySandbox, excludedDirs };
+1335
View File
File diff suppressed because it is too large Load Diff
+120
View File
@@ -0,0 +1,120 @@
// 此函数在游戏上下文中运行。记录留在 window 的非枚举属性中,不进入存档。
function installPhotoTools() {
if (window.__nyaruruPhoto) { window.__nyaruruPhoto.touch?.(); return window.__nyaruruPhoto; }
const records = new Map();
let lastTouch = Date.now();
const refreshSprite = ev => {
const walk = node => {
if (!node) return;
if (node._character === ev && node.setCharacterBitmap) {
node._characterName = ev.bitmapName ? ev.bitmapName() : ev.characterName();
node._characterIndex = ev.characterIndex();
node._tileId = ev.tileId();
if (node._tileId) node.setTileBitmap(); else node.setCharacterBitmap();
// 换位图会重置为整张图;角色帧号即使没变,也必须重新裁切。
// 图片异步加载完成时还会重置一次,因此在加载回调中刷新游戏自己的帧逻辑。
const bitmap = node._contentSprite ? node._contentSprite.bitmap : node.bitmap;
const refreshFrame = () => {
const current = node._contentSprite ? node._contentSprite.bitmap : node.bitmap;
if (node._character !== ev || current !== bitmap) return;
node._framePos = -1;
if (node.updateFrame) node.updateFrame();
};
node._framePos = -1;
if (bitmap && bitmap.addLoadListener) bitmap.addLoadListener(refreshFrame);
else refreshFrame();
}
for (const child of node.children || []) walk(child);
};
try { walk(SceneManager._scene); } catch { /* 精灵尚未建立时由下一帧刷新 */ }
};
const settle = (ev, page) => {
const ai = ev.event?.().pages?.[page]?.list?.find(c => c.code === 357 && c.parameters?.[1] === 'ai')?.parameters?.[3];
// 只有原页明确要求贴地的角色参与;飞行角色、固定摆件及无近处地面保持原位。
if (String(ai?.smoothfloor) !== 'true' || String(ai?.skipSmoothfloor) === 'true' || String(ai?.fix) === 'true' || !ev.hitPreview || !ev.locate) return;
const th = $gameMap.tileHeight(), tw = $gameMap.tileWidth();
for (let dy = 0; dy <= th; dy++) {
const hits = (ev.hitPreview(0, dy) || []).filter(o => o?.terrain === true);
if (!hits.length) continue;
if (hits.some(o => o.type === 2)) return;
const drop = Math.max(0, dy - 1); // 停在地形外侧,不能把碰撞体塞进地板。
if (!drop) return;
const x = ev.tileXToCenterX ? (ev.px - ev.tileXToCenterX(0)) / tw : (ev._realX ?? ev._x);
const y = ev.tileYToCenterY ? (ev.py + drop - ev.tileYToCenterY(0)) / th : (ev._realY ?? ev._y) + drop / th;
ev.locate(x, y);
ev.clearImpact?.(); ev.clearGrounding?.();
ev._groundingX = ev._terrainGroundingX = ev.px;
ev._groundingY = ev._terrainGroundingY = ev.py;
return;
}
};
const unpin = ev => {
const record = records.get(ev);
if (!record) return;
// 还原被我们覆盖的自有字段和方法,包括原始 _erased、解释器及物理状态。
for (const key of Reflect.ownKeys(ev)) if (!Object.hasOwn(record, key)) delete ev[key];
Object.defineProperties(ev, record);
records.delete(ev);
refreshSprite(ev);
};
const api = {
touch: () => { lastTouch = Date.now(); },
count: () => records.size,
facePlayer(ev) {
if (!records.has(ev) || typeof $gamePlayer === 'undefined' || !ev.setDirection) return;
const dx = $gamePlayer.px - ev.px;
if (!Number.isFinite(dx) || Math.abs(dx) < 1) return;
const fixed = ev._directionFix;
try { ev._directionFix = false; ev.setDirection(dx < 0 ? 4 : 6); }
finally { ev._directionFix = fixed; }
},
unpinAll() {
const n = records.size;
for (const ev of [...records.keys()]) unpin(ev);
if ($gameMap?.requestRefresh) $gameMap.requestRefresh();
return n;
},
pin(ev, page) {
if (records.has(ev)) unpin(ev);
const record = Object.getOwnPropertyDescriptors(ev);
records.set(ev, record);
try {
// setupPageSettings 会写 statemMembers,隔离这层避免污染撤销快照。
if (ev._statemMembers) ev._statemMembers = { ...ev._statemMembers };
ev._erased = false;
ev._pageIndex = page;
ev.setupPageSettings();
settle(ev, page);
for (const name of ['start', 'update', 'updateParallel', 'checkEventTriggerAuto', 'checkEventTriggerTouch', 'physicsTriggerTouch', 'refresh']) {
Object.defineProperty(ev, name, { value() {}, configurable: true, writable: true });
}
// 只更新图片帧,不调用 Game_Event.update(其中包含 AI、移动和事件触发)。
Object.defineProperty(ev, 'update', { configurable: true, writable: true, value() {
if (typeof ImageFrame !== 'undefined' && this.updateFrameAnimation) {
this.updateFrameAnimation(ImageFrame.info(this.characterName()));
}
} });
Object.defineProperty(ev, 'findProperPageIndex', { value: () => page, configurable: true, writable: true });
ev._starting = false; ev._trigger = null; ev._interpreter = null; ev._moveType = 0;
ev.physics = false; ev.fix = true;
ev.vx = ev.vy = ev._vx = ev._vy = 0;
api.facePlayer(ev);
refreshSprite(ev);
} catch (e) { unpin(ev); throw e; }
},
};
Object.defineProperty(window, '__nyaruruPhoto', { value: api, configurable: true });
// 面板关闭或断线后两分钟撤销摆拍,恢复事件原有行为。
if (typeof setInterval === 'function') setInterval(() => {
if (records.size && Date.now() - lastTouch > 120000) api.unpinAll();
}, 10000);
// 不拦截游戏的手动或自动存档;摆拍跨读档的限制由面板提示。
// 正常切图或读档会结束摆拍,清除旧地图的记录。
for (const [object, name] of [[Game_Map.prototype, 'setup'], [DataManager, 'extractSaveContents']]) {
const original = object[name];
if (typeof original !== 'function') continue;
object[name] = function(...args) { api.unpinAll(); return original.apply(this, args); };
}
return api;
}
module.exports = { installPhotoTools };
+11
View File
@@ -0,0 +1,11 @@
// 与启动器、服务端一致:读取实际游戏及存档目录,不解析页面 URL。
const { CdpClient } = require('./cdp');
const { OPS } = require('./ops');
async function probe(port) {
if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error('端口无效');
const c = new CdpClient(port);
try { const r = await c.evalJson(OPS.selfPath()); if (!r.ok || !r.gameDir) throw new Error(r.error || '无法识别游戏'); return r; }
finally { c.close(); }
}
if (require.main === module) probe(Number(process.argv[2])).then(r => console.log(r.gameDir)).catch(e => { console.error(e.message); process.exitCode = 1; });
module.exports = { probe };
+9
View File
@@ -0,0 +1,9 @@
const { execFile } = require('child_process');
async function assertGamesStopped() {
if (process.platform !== 'win32') throw new Error('当前平台无法核实游戏进程,停止还原');
const script = '[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; @(Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { $_.Name -match "^(nw|Nyaruru).*\\.exe$" } | Select-Object ProcessId,Name) | ConvertTo-Json -Compress';
const text = await new Promise((resolve, reject) => execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, timeout: 6000, encoding: 'utf8' }, (e, out) => e ? reject(new Error('无法检查游戏进程,停止还原:' + e.message)) : resolve(out)));
const rows = text.trim() ? JSON.parse(text) : [];
if ((Array.isArray(rows) ? rows : [rows]).length) throw new Error('请先退出游戏及 NW.js 游戏窗口,再还原存档,避免运行中的游戏把旧状态写回');
}
module.exports = { assertGamesStopped };
+43
View File
@@ -0,0 +1,43 @@
// 启动器与服务端共用的路径、配置校验。
const fs = require('fs');
const path = require('path');
function canonical(input) {
if (typeof input !== 'string' || !path.isAbsolute(input)) throw new Error('必须填写绝对路径');
let p = path.resolve(input);
const tail = [];
while (!fs.existsSync(p)) {
const parent = path.dirname(p);
if (parent === p) throw new Error('目录所在磁盘不存在');
tail.unshift(path.basename(p)); p = parent;
}
return path.join(fs.realpathSync.native(p), ...tail);
}
function samePath(a, b) { return canonical(a).toLowerCase() === canonical(b).toLowerCase(); }
function contains(a, b) {
const rel = path.relative(canonical(a).toLowerCase(), canonical(b).toLowerCase());
return rel === '' || (!rel.startsWith('..' + path.sep) && rel !== '..' && !path.isAbsolute(rel));
}
function validateConfig(config, gameDir) {
const next = { ...config };
for (const key of ['cdpPort', 'webPort']) {
const n = Number(next[key]);
if (!Number.isInteger(n) || n < 1024 || n > 65535) throw new Error(`${key} 必须是 1024~65535 的整数`);
next[key] = n;
}
if (next.cdpPort === next.webPort) throw new Error('游戏调试端口和控制面板端口不能相同');
next.sandboxDir = canonical(String(next.sandboxDir || '').trim());
if (contains(gameDir, next.sandboxDir) || contains(next.sandboxDir, gameDir)) {
throw new Error('沙盒与原版目录必须完全分开,不能相同,也不能互相包含');
}
return next;
}
function readConfig(file, defaults, gameDir) {
let patch = {};
if (fs.existsSync(file)) {
try { patch = JSON.parse(fs.readFileSync(file, 'utf8')); }
catch { throw new Error('config.json 损坏,请修正配置后重试;不会静默换用其他目录'); }
}
return validateConfig({ ...defaults, ...patch }, gameDir);
}
module.exports = { canonical, samePath, contains, validateConfig, readConfig };
+78
View File
@@ -0,0 +1,78 @@
// 发布版专用。全文索引只存在于内存,不读写台词文件。
class StoryCache {
constructor(cdp, ops, triggers, { retryMs = 3000, maxAttempts = 4, now = Date.now } = {}) {
Object.assign(this, { cdp, ops, triggers, retryMs, maxAttempts, now });
this.revision = 0;
this.reset();
}
key() {
return this.cdp.ws?.readyState === 1 && this.cdp.sessionId
? `${this.cdp.port}:${this.cdp.generation}:${this.cdp.sessionId}` : null;
}
reset(key = null) {
this.connection = key;
this.index = null;
this.pending = null;
this.attempts = 0;
this.nextTryAt = 0;
this.error = '';
this.at = 0;
++this.revision;
}
sync() {
const key = this.key();
if (key !== this.connection) this.reset(key);
return key;
}
status() {
const key = this.sync();
const loaded = !!this.index;
return {
state: !key ? 'disconnected' : loaded ? 'ready' : this.pending ? 'loading'
: this.error ? (this.attempts >= this.maxAttempts ? 'error' : 'retrying') : 'waiting',
loaded, revision: this.revision, connection: key, error: this.error,
attempts: this.attempts, at: this.at,
count: loaded ? Object.keys(this.index).length : 0,
triggersWithLine: loaded ? this.triggers.filter(t => this.index[String(t.storyId)]).length : 0,
};
}
get(id) { this.sync(); return this.index?.[String(id)] || null; }
async ensure({ force = false } = {}) {
let key = this.sync();
if (!key) {
if (!(await this.cdp.isAlive())) return null;
try { await this.cdp.connect(); } catch { this.sync(); return null; }
key = this.sync();
}
if (!key) return null;
if (this.pending) return this.pending;
if (force) { this.reset(key); }
else if (this.index || this.attempts >= this.maxAttempts || this.now() < this.nextTryAt) return this.index;
const revision = this.revision;
++this.attempts;
const task = (async () => {
try {
const result = await this.cdp.evalJson(this.ops.readStoryIndex());
if (this.key() !== key || this.revision !== revision) return null;
if (!result?.ok || !result.index || !Object.keys(result.index).length) {
throw new Error(result?.error || '故事表尚未就绪或没有可读台词');
}
this.index = result.index;
this.error = '';
this.at = this.now();
++this.revision;
return this.index;
} catch (e) {
if (this.key() !== key || this.revision !== revision) return null;
this.error = String(e.message || e);
this.nextTryAt = this.now() + this.retryMs;
++this.revision;
return null;
}
})();
this.pending = task;
try { return await task; }
finally { if (this.pending === task) this.pending = null; }
}
}
module.exports = { StoryCache };
+82
View File
@@ -0,0 +1,82 @@
// 已核对的剧情落脚点。控制事件的位置不一定是角色演出的位置。
// Map181 EV002 第 5 页将玩家送到 Map182 (11,11),随后由 EV003 自动执行
// 298/299 -> 305。EV003 本身放在 (0,0),仅用于控制剧情。
// 此表只有结构坐标,不含台词;发布版可直接共用,无需本地解包数据。
function storyPosition(trigger) {
const { x, y } = trigger;
const entries = [
{ map: 182, event: 3, page: 0, stories: [298, 299, 305], from: [0, 0], to: [11, 11] },
// 原游戏 Map006 EV017 第 1 页的入场位置。
{ map: 9, event: 10, page: 5, stories: [449], from: [0, 0], to: [11, 9] },
// 原游戏 Map301 EV005 第 1 页的村落入口。
{ map: 296, event: 34, page: 5, stories: [449], from: [4, 0], to: [28, 13] },
// 原游戏 Map004 EV005 第 5 页的梦境入场位置。
{ map: 254, event: 2, page: 0, stories: [467], from: [0, 0], to: [6, 5] },
];
const entry = entries.find(e => Number(trigger.mapId) === e.map && Number(trigger.eventId) === e.event &&
trigger.pageIndex !== null && trigger.pageIndex !== undefined && Number(trigger.pageIndex) === e.page &&
e.stories.includes(Number(trigger.storyId)) &&
x !== null && y !== null && x !== '' && y !== '' && Number(x) === e.from[0] && Number(y) === e.from[1]);
if (entry) {
return { x: entry.to[0], y: entry.to[1], positionNote: `使用原游戏入场位置;剧情控制事件位于 (${entry.from.join(',')})` };
}
return { x, y };
}
// 在游戏运行时调用;只读取当前地图与碰撞,不加载/导出台词或解包文件。
function chooseStoryPosition({ map, player, data, eventId, pageIndex, storyId, sameMap, previous, preferred, requested }) {
const event = data.events?.[eventId];
const containsStory = page => page.list?.some(c => c.code === 357 && c.parameters?.[1] === 'call_story' && Number(c.parameters[3]?.id) === Number(storyId));
const page = event?.pages?.[pageIndex] || event?.pages?.find(containsStory);
const hasBody = pg => !!(pg?.image?.characterName || pg?.image?.tileId || pg?.list?.some(c => c.code === 357 && c.parameters?.[1] === 'ai' && Number(c.parameters[3]?.battleObject) > 0));
if (!page || ![3, 4].includes(page.trigger) || hasBody(page)) return { ok: true, ...requested, controller: false };
if (!preferred && (requested.x !== event.x || requested.y !== event.y)) preferred = requested;
const tw = map.tileWidth(), th = map.tileHeight(), step = Math.max(8, Math.floor(th / 4));
let probes = 0;
const floor = (x, y, depth) => {
x = Math.round(x); y = Math.round(y);
if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || y < 0 || x >= map.width() || y >= map.height()) return null;
for (let dy = 0; dy <= Math.min(depth * th, (map.height() - y) * th); dy += step) {
if (++probes > 800) return null;
const hits = (player.hitPreview((x - player._x) * tw, (y - player._y) * th + dy) || []).filter(o => o?.terrain === true);
if (!hits.length) continue;
if (hits.some(o => o.type === 2)) return null;
return { x, y: y + Math.max(0, Math.floor((dy - step) / th)) };
}
return null;
};
// 同图已站在正常场景里时,不因点击控制事件而把人重新送到角落。
let pick = sameMap && previous ? floor(previous.x, previous.y, 1) : null;
let reason = pick ? '保留当前可落地位置' : '';
if (!pick && preferred) { pick = floor(preferred.x, preferred.y, 2); if (pick) reason = '使用已核实的入场位置'; }
const events = (map.events() || []).filter(e => e && e.eventId() !== Number(eventId));
const refs = new Set((page.list || []).filter(c => [203, 205, 213].includes(c.code)).map(c => Number(c.parameters?.[0])).filter(id => id > 0));
const ordered = [
...events.filter(e => refs.has(e.eventId())),
...events.filter(e => e.characterName?.()),
...events.filter(e => e.event()?.pages?.some(hasBody)),
];
const seen = new Set();
for (const ev of ordered) {
if (pick || probes >= 600) break;
if (seen.has(ev)) continue;
seen.add(ev);
for (const dx of [-1, 1, -2, 2]) {
pick = floor(ev._x + dx, Math.max(0, ev._y - 1), 4);
if (pick) { reason = '按场景人物附近的安全地面定位'; break; }
}
}
// 场景人物不可用时,仅在地图内部做有上限的地形扫描,不猜测原作站位。
if (!pick) {
const xs = Array.from({ length: Math.min(map.width(), 31) }, (_, i) => Math.round((i + 0.5) * map.width() / Math.min(map.width(), 31)))
.sort((a, b) => Math.abs(a - map.width() / 2) - Math.abs(b - map.width() / 2));
for (const x of xs) {
if (probes >= 800) break;
pick = floor(x, 0, map.height());
if (pick) { reason = '按当前地图的安全地面定位'; break; }
}
}
if (!pick) return { ok: false, controller: true, error: '这是无形剧情控制事件,未找到可确认的安全落脚点;已保留悬浮,请手动定位后再运行过场' };
return { ok: true, ...pick, controller: true, positionNote: reason };
}
module.exports = { storyPosition, chooseStoryPosition };
+148
View File
@@ -0,0 +1,148 @@
// Injected into the game. Uses NYA's actor inventory/battle values, not RPG Maker HP/gold.
function installTrainer() {
if (window.__nyaruruTrainer) return window.__nyaruruTrainer;
const fields = { coin: '_coin', hp: '_hp', sp: 'sp', zp: 'zp' };
const locks = new Map();
const ids = new WeakMap();
let serial = 0, touched = Date.now(), actors = $gameActors, party = $gameParty;
const id = o => { if (!ids.has(o)) ids.set(o, ++serial); return ids.get(o); };
const active = () => {
const actor = $gamePlayer.actor(), battle = $gamePlayer.battleObject();
if (!actor || !battle) throw new Error('当前角色数据尚未就绪');
return { actor, battle, subject: `${id(actor)}:${id(battle)}:${!!$gamePlayer.isLilyMode()}` };
};
const maximum = (field, b) => field === 'coin' ? 99999 : Math.max(0, Math.floor(b['m' + field]));
const integer = (value, max) => {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > max) {
throw new Error(`请输入 0~${max} 的整数`);
}
return value;
};
// Accessor intercepts the actual storage slot, so even lethal damage cannot reach zero
// before a later polling refill. Descriptor flags and the current value survive unlock.
function detach(lock) {
if (!lock.object) return;
const value = lock.value();
Object.defineProperty(lock.object, fields[lock.field], { ...lock.descriptor, value });
lock.object = null;
}
function clear() {
for (const lock of locks.values()) detach(lock);
locks.clear();
}
function sync() {
if (actors !== $gameActors || party !== $gameParty || Date.now() - touched > 120000) {
clear(); actors = $gameActors; party = $gameParty;
}
if (!locks.size) return;
const { actor, battle } = active();
for (const lock of locks.values()) {
const object = lock.field === 'coin' ? actor : battle;
if (lock.object === object) continue;
detach(lock);
const key = fields[lock.field], descriptor = Object.getOwnPropertyDescriptor(object, key);
if (!descriptor?.configurable || !descriptor.writable || !('value' in descriptor)) {
throw new Error('当前游戏的数值结构不支持锁定');
}
lock.object = object; lock.descriptor = descriptor;
lock.value = () => Math.min(lock.target, maximum(lock.field, battle));
Object.defineProperty(object, key, {
configurable: true, enumerable: descriptor.enumerable,
get: () => lock.value(), set: () => {},
});
}
}
function touch() { sync(); touched = Date.now(); }
// Only one timer per game page; neither hooks nor lock settings enter save data.
setInterval(() => { try { sync(); } catch { clear(); } }, 100);
const categories = ['consumables', 'weapons', 'stones', 'ornaments'];
const specials = {
joycoin: ['joyCoinData', 'joyCoinNum', '_joyCoin'],
hpst: ['hpStrengthData', 'hpStrengthNum', '_hpStrengthItem'],
skillst: ['skillStrengthData', 'skillStrengthNum', '_skillStrengthItem'],
};
const localized = key => String(TextManager[key] ?? key ?? '');
function read() {
touch();
const { actor, battle, subject } = active();
const stats = Object.fromEntries(Object.keys(fields).map(field => [field, {
value: field === 'coin' ? actor.coin() : battle[field],
max: maximum(field, battle), locked: locks.has(field), target: locks.get(field)?.target ?? null,
}]));
const items = [];
for (const type of categories) {
const container = actor['_' + type];
for (const [key, data] of Object.entries(container.data())) {
const itemId = Number(key);
if (!Number.isSafeInteger(itemId) || itemId < 0 || !data) continue;
items.push({ type, id: itemId, name: localized(data.name), desc: localized(data.desc),
count: type === 'consumables' ? container.itemNum(itemId) : Number(container.isUnlock(itemId)),
max: type === 'consumables' ? container.maxNum(itemId) : 1,
equipped: type === 'weapons' ? container.currentWeapon() === itemId : !!container.isEquip?.(itemId),
});
}
}
for (const [type, [dataMethod, countMethod]] of Object.entries(specials)) {
const data = actor[dataMethod]();
items.push({ type, id: 0, name: localized(data.name), desc: localized(data.desc), count: actor[countMethod](), max: 99999, equipped: false });
}
return { ok: true, subject, role: $gamePlayer.isLilyMode() ? '莉莉娅' : actor.name(), stats, items };
}
function change(body) {
touch();
const { actor, battle, subject } = active();
if (body.subject !== subject) throw new Error('操作角色已变化,请刷新角色与背包后重试');
if (body.action === 'stat') {
const field = body.field;
if (!Object.prototype.hasOwnProperty.call(fields, field)) throw new Error('未知数值');
if (body.locked !== undefined && typeof body.locked !== 'boolean') throw new Error('锁定参数无效');
if (body.locked === false) {
const old = locks.get(field);
if (old) { detach(old); locks.delete(field); }
return read();
}
const value = integer(body.value, maximum(field, battle));
if (field === 'hp' && battle.hp === 0 && value > 0) throw new Error('角色已倒下,请先在游戏里复活或读档,再修改血量');
const old = locks.get(field), keepLocked = body.locked === true || !!old;
if (old) { detach(old); locks.delete(field); }
if (field === 'coin') {
const delta = value - actor.coin();
if (delta >= 0) actor.addCoin(delta); else actor.deductCoin(-delta);
} else battle['add' + field[0].toUpperCase() + field.slice(1)](value - battle[field]);
if (keepLocked) {
locks.set(field, { field, target: value, object: null });
try { sync(); } catch (e) { clear(); throw e; }
}
} else if (body.action === 'item') {
const { type } = body;
const itemId = integer(body.id, 99999);
if (Object.prototype.hasOwnProperty.call(specials, type)) {
if (itemId !== 0) throw new Error('物品编号无效');
actor[specials[type][2]] = integer(body.count, 99999);
} else {
if (!categories.includes(type)) throw new Error('物品分类无效');
const container = actor['_' + type], data = container.data();
if (!Object.prototype.hasOwnProperty.call(data, itemId) || !data[itemId]) throw new Error('物品不存在');
const max = type === 'consumables' ? (body.overCap === true ? 99999 : container.maxNum(itemId)) : 1;
const count = integer(body.count, max);
if (type === 'consumables') container.add(itemId, count - container.itemNum(itemId), body.overCap === true);
else if (count) container.unlock(itemId);
else if (type === 'weapons') {
const remaining = container._unlock.filter(n => n !== itemId);
if (!remaining.length) throw new Error('至少需要保留一件武器,避免游戏攻击时找不到武器');
if (container.currentWeapon() === itemId) { actor.changeWeapon(remaining[0]); $gamePlayer.setWeaponChange(); }
container._unlock = remaining;
} else if (type === 'ornaments') container.remove(itemId);
else {
if (container.isEquip(itemId)) container.equip(itemId);
container._unlock = container._unlock.filter(n => n !== itemId);
}
}
} else throw new Error('未知修改操作');
return read();
}
return window.__nyaruruTrainer = { read, change, touch, clear };
}
module.exports = { installTrainer };
+497
View File
@@ -0,0 +1,497 @@
// 咸鱼喵喵 · 截图辅助工具 —— 本地服务
//
// 职责:
// 1. 给浏览器提供一个控制面板页面
// 2. 通过 CDP 把面板上的操作转成游戏里的 JavaScript
// 3. 管存档备份 / 恢复、沙盒副本
//
// 安全:
// - 只监听 127.0.0.1,同一个 WiFi 下的别人连不上
// - 不改程序和素材;明确选择后可保存/还原存档,复制沙盒。
const http = require('http');
const fs = require('fs');
const path = require('path');
const { CdpClient } = require('./lib/cdp.js');
const { OPS } = require('./lib/ops.js');
const { storyPosition } = require('./lib/story-position');
const { loadAll } = require('./lib/data.js');
const { StoryCache } = require('./lib/story-cache');
const SAFETY = require('./lib/safety');
const FILES = require('./lib/files');
const { assertGamesStopped } = require('./lib/processes');
// ---------- 路径与配置 ----------
const TOOL_DIR = __dirname;
const AITEMP_DIR = path.resolve(TOOL_DIR, '..'); // aitemp/
const GAME_DIR = path.resolve(AITEMP_DIR, '..'); // 游戏根目录
const WEB_DIR = path.join(TOOL_DIR, 'web');
const BACKUP_DIR = path.join(AITEMP_DIR, 'backups');
const CONFIG_FILE = path.join(TOOL_DIR, 'config.json');
// 沙盒默认位置:和游戏同一个盘的根目录下。
// ⚠️ 不要写死具体盘符 —— 别人的游戏不一定装在 L 盘。
// 放在盘根是为了**避开 Steam 库**(放库里 Steam 会扫到,云同步也可能够得着)。
const DEFAULT_SANDBOX = path.join(path.parse(GAME_DIR).root, 'Nyaruru_shots');
const DEFAULTS = {
cdpPort: 9223, // 沙盒实例的调试端口
sandboxDir: DEFAULT_SANDBOX,
webPort: 8787,
};
function loadConfig() { return SAFETY.readConfig(CONFIG_FILE, DEFAULTS, GAME_DIR); }
const CONFIG = loadConfig();
function classifyGameDir(dir) {
if (!dir) return 'unknown';
try {
if (SAFETY.samePath(dir, GAME_DIR)) return 'original';
if (SAFETY.samePath(dir, CONFIG.sandboxDir)) return 'sandbox';
} catch { return 'unknown'; }
return 'other';
}
/** 校验并写回 config.json。只接受已知字段,避免前端传进来的杂项污染配置 */
function saveConfig(patch) {
if (sandboxJob.running) throw new Error('沙盒复制期间不能修改配置');
const allowed = Object.fromEntries(Object.entries(patch).filter(([k]) => ['cdpPort', 'webPort', 'sandboxDir'].includes(k)));
const next = SAFETY.validateConfig({ ...CONFIG, ...allowed }, GAME_DIR);
// 面板端口修改要重启,因此也不能让 CDP 占用当前正在监听的旧端口。
if (server?.listening && next.cdpPort === server.address().port) throw new Error('调试端口与当前正在使用的面板端口冲突,请先重启面板');
const temp = CONFIG_FILE + '.tmp';
fs.writeFileSync(temp, JSON.stringify(next, null, 2), 'utf8');
fs.renameSync(temp, CONFIG_FILE);
const portChanged = next.cdpPort !== CONFIG.cdpPort;
const webPortChanged = next.webPort !== CONFIG.webPort;
Object.assign(CONFIG, next);
if (portChanged) { cdp.close(); cdp.port = CONFIG.cdpPort; erasedCache.clear(); storyCache.reset(); }
return { config: CONFIG, cdpReconnected: portChanged, webPortNeedsRestart: webPortChanged };
}
// ---------- 静态数据(启动时载入一次)----------
let DATA;
try {
DATA = loadAll(AITEMP_DIR);
console.log(`[数据] 开关 ${DATA.stats.switches} · 变量 ${DATA.stats.variables} · 地图 ${DATA.stats.maps}`);
console.log(`[数据] 触发点 ${DATA.stats.triggersUnique} 条(可跳转 ${DATA.stats.triggersActionable} 条)· 常用开关 ${DATA.stats.commonSwitches} 个`);
} catch (e) {
console.error('[数据] 载入失败:', e.message);
console.error(' 请确认 aitemp/out/triggers.csv 与 aitemp/unpacked/data/ 存在。');
process.exit(1);
}
const cdp = new CdpClient(CONFIG.cdpPort);
const storyCache = new StoryCache(cdp, OPS, DATA.triggers);
// "mapId:eventId" → 该事件是否被游戏自己抹除(_erased)。
// 每次只保留当前地图扫描结果,避免切换存档后沿用旧标记。
const erasedCache = new Map();
// ---------- 存档备份 ----------
const backupSaves = (dir, label) => FILES.backupSaves(BACKUP_DIR, dir, label);
const listBackups = () => FILES.listBackups(BACKUP_DIR);
let sandboxJob = { running: false, done: false, error: null, message: '', startedAt: 0 };
function sandboxExists() { return FILES.sandboxStatus(GAME_DIR, CONFIG.sandboxDir, AITEMP_DIR).ready; }
function createSandbox() {
if (sandboxJob.running) throw new Error('已有拷贝任务在进行中');
const dest = CONFIG.sandboxDir;
const promise = FILES.copySandbox(GAME_DIR, dest, AITEMP_DIR);
sandboxJob = { running: true, done: false, error: null, message: '正在拷贝并验证…', startedAt: Date.now(), dest };
promise.then(() => { sandboxJob = { ...sandboxJob, running: false, done: true, message: '拷贝及验证完成' }; }, e => {
sandboxJob = { ...sandboxJob, running: false, done: false, error: e.message, message: '拷贝失败,不能启动该副本' };
});
return { started: true, dest };
}
function targetDir(body) {
if (!['original', 'sandbox'].includes(body.target)) throw new Error('必须明确选择原版或沙盒目标');
return body.target === 'sandbox' ? CONFIG.sandboxDir : GAME_DIR;
}
let operationTail = Promise.resolve();
const offlineActions = new Set(['/api/config', '/api/backup', '/api/restore-backup', '/api/sandbox', '/api/shutdown', '/api/story-text']);
const getRoutes = new Set(['/api/trainer', '/api/status', '/api/snapshot', '/api/maps', '/api/switches', '/api/config', '/api/ground', '/api/events/lost', '/api/events', '/api/triggers', '/api/backups', '/api/sandbox/status', '/api/health', '/api/story-text']);
async function identity() {
const r = await cdp.evalJson(OPS.selfPath());
if (!r?.ok) throw new Error(r?.error || '无法识别游戏实例');
return { ...r, dir: r.gameDir, kind: classifyGameDir(r.gameDir), context: `${cdp.generation}:${r.mapToken}` };
}
function guarded(script, token) {
return `(async()=>{ const i=JSON.parse(await ${OPS.selfPath()}); if(i.mapToken!==${JSON.stringify(token)}) return JSON.stringify({ok:false,error:'地图或存档已经变化,请刷新后重试'}); return await ${script}; })()`;
}
// ---------- 工具函数 ----------
function readBody(req) {
return new Promise((resolve, reject) => {
let buf = '';
req.on('data', c => { buf += c; if (buf.length > 1e6) req.destroy(); });
req.on('end', () => { try { resolve(buf ? JSON.parse(buf) : {}); } catch { reject(new Error('请求 JSON 格式错误')); } });
req.on('error', reject);
req.on('aborted', () => reject(new Error('请求已取消')));
});
}
function sendJson(res, obj, code = 200) {
const body = JSON.stringify(obj);
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(body);
}
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.png': 'image/png', '.ico': 'image/x-icon' };
function serveStatic(res, urlPath) {
const rel = urlPath === '/' ? 'index.html' : urlPath.replace(/^\/+/, '');
const file = path.join(WEB_DIR, rel);
// 防止 ../ 穿越到 web 目录之外
if (!SAFETY.contains(WEB_DIR, file)) { res.writeHead(403); res.end('forbidden'); return; }
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) { res.writeHead(404); res.end('not found'); return; }
res.writeHead(200, { 'Content-Type': MIME[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-store' });
fs.createReadStream(file).pipe(res);
}
// ---------- 路由 ----------
async function handleApi(req, res, urlPath, query) {
if (req.method !== 'GET' && req.method !== 'POST') return sendJson(res, { ok: false, error: '不支持的请求方法' }, 405);
if (req.method === 'GET' && !getRoutes.has(urlPath)) return sendJson(res, { ok: false, error: '修改操作必须使用 POST' }, 405);
if (req.method === 'POST' && req.headers.origin && req.headers.origin !== `http://${req.headers.host}`) return sendJson(res, { ok: false, error: '拒绝跨站修改请求' }, 403);
const body = req.method === 'POST' ? await readBody(req) : {};
if (req.method === 'POST') {
const task = operationTail.then(() => executeApi(req, res, urlPath, body));
operationTail = task.catch(() => {});
return task;
}
return executeApi(req, res, urlPath, body);
}
async function executeApi(req, res, urlPath, body) {
let current = null;
if (req.method === 'POST' && !offlineActions.has(urlPath)) {
current = await identity();
if (!['sandbox', 'original'].includes(current.kind)) throw new Error('无法确认游戏身份,停止修改操作');
if (!body.context || body.context !== current.context) throw new Error('连接、地图或存档已变化,请刷新后重试');
}
const game = async script => {
if (current && current.context.split(':')[0] !== String(cdp.generation)) throw new Error('连接已变化,操作已取消');
return cdp.evalJson(current ? guarded(script, current.mapToken) : script);
};
switch (urlPath) {
case '/api/shutdown': {
if (sandboxJob.running) throw new Error('沙盒仍在复制,请等待任务结束再停止面板');
sendJson(res, { ok: true });
setTimeout(() => { cdp.close(); server.close(() => { if (require.main === module) process.exit(0); }); }, 100);
return;
}
case '/api/health': return sendJson(res, { ok: true, toolDir: TOOL_DIR, version: 2, config: CONFIG });
// --- 连接状态 ---
case '/api/status': {
const alive = await cdp.isAlive();
// 检测到调试端口就顺手建立会话(首次之后会复用,开销很小),
// 这样面板一打开就能显示"已连接",而不是等到第一次操作
let connected = false;
if (alive) {
try { await cdp.connect(); connected = !!cdp.sessionId; } catch { connected = false; }
}
// 顺手问一句:游戏窗口自己是从哪个目录加载的?
// 面板据此显示"当前连接:沙盒 / 原版",把"以为在沙盒、其实改了原版"这种
// 误用摆在明面上(见 复查与隐患.md 坑 5)。
let gameSelf = null;
if (connected) { try { gameSelf = await identity(); } catch { connected = false; } }
if (!connected) {
erasedCache.clear(); cdp.close(); storyCache.reset();
} else { void storyCache.ensure().catch(() => {}); }
const storyText = storyCache.status();
return sendJson(res, {
ok: true,
gameRunning: alive,
connected,
cdpPort: CONFIG.cdpPort,
gameDir: GAME_DIR,
sandboxDir: CONFIG.sandboxDir,
sandboxExists: sandboxExists(),
sandboxJob,
gameSelf,
stats: { ...DATA.stats, storyLoaded: storyText.count, triggersWithLine: storyText.triggersWithLine },
dataMode: 'runtime', storyText,
context: gameSelf?.context || null,
});
}
// --- 游戏状态快照 ---
case '/api/trainer': {
if (req.method === 'GET') current = await identity();
const r = await game(OPS.trainer(req.method === 'POST' ? body : null));
return sendJson(res, { ...r, context: current.context });
}
case '/api/snapshot': {
const snap = await game(OPS.snapshot());
return sendJson(res, snap);
}
// --- 地图列表 ---
case '/api/maps':
return sendJson(res, { ok: true, maps: DATA.maps });
// --- 开关 ---
case '/api/switches': {
let values = {};
try { values = (await game(OPS.readSwitches())).values || {}; } catch { /* 没连上就只给名字 */ }
const common = new Set(DATA.commonSwitchIds);
return sendJson(res, {
ok: true,
switches: DATA.switches.map(s => ({ ...s, common: common.has(s.id) })),
values,
connected: Object.keys(values).length > 0,
});
}
case '/api/switch': {
const r = await game(OPS.setSwitch(body.id, body.value));
return sendJson(res, r);
}
// 批量设置开关("一键前往"用:一次把该对话需要的条件全部打开)
case '/api/switches/set': {
const pairs = Array.isArray(body.pairs) ? body.pairs : [];
if (!pairs.length) return sendJson(res, { ok: true, applied: 0 });
return sendJson(res, await game(OPS.setSwitches(pairs)));
}
// --- 传送 ---
// body.float 默认 true:传送后进入"悬浮安全模式"(暂停重力 + 穿墙),
// 避免落进坑里触发游戏的坠落复位。详见 ops.js 里 teleport 的注释。
case '/api/teleport': {
const r = await game(OPS.teleport(body.x, body.y, {
float: body.float !== false,
// mapId 不传或与当前地图相同 → 地图内定位;
// 不同 → 走 reserveTransfer 跨地图(见 ops.js 的 teleport 注释)
mapId: body.mapId ?? null,
}));
return sendJson(res, r);
}
// --- 直接播放一段剧情序列 ---
// 绕开地图事件与开关条件,用于通关存档上复现"错过就没了"的对话
case '/api/story/start': {
const position = storyPosition(body);
const tp = await game(OPS.teleport(position.x, position.y, { mapId: body.mapId, story: body }));
if (!tp.ok) return sendJson(res, tp);
const next = await identity();
if (next.context.split(':')[0] !== current.context.split(':')[0] || !SAFETY.samePath(next.dir, current.dir)) throw new Error('传送期间连接已变化');
current = next;
const r = await game(body.mode === 'scene' ? OPS.runStoryScene(body.storyId, body.eventId, body.pageIndex) : OPS.playStory(body.storyId));
r.positionNote = tp.positionNote;
// 传送及补角色会临时开启悬浮;过场准备完成后恢复安全落地。
// 放在 runStoryScene 之后,避免其避让角色逻辑再次开启悬浮。
if (r.ok && body.mode === 'scene') {
r.landing = await game(OPS.land());
if (!r.landing.ok) r.landingWarning = '当前落点未能自动落地:' + r.landing.error;
else if (r.landing.warning) r.landingWarning = r.landing.warning;
}
return sendJson(res, r);
}
case '/api/story/goto': {
// 验证所有参数后才修改开关,并把开关及传送放在同一排队任务中。
const position = storyPosition(body);
const teleport = OPS.teleport(position.x, position.y, { mapId: body.mapId, story: body });
const pairs = Array.isArray(body.pairs) ? body.pairs : [];
if (pairs.some(p => !Array.isArray(p) || !DATA.switches.some(s => s.id === p[0]) || typeof p[1] !== 'boolean')) throw new Error('开关参数无效');
if (pairs.length) {
const r = await game(OPS.setSwitches(pairs));
if (!r.ok) return sendJson(res, r);
}
return sendJson(res, await game(teleport));
}
case '/api/story/play':
return sendJson(res, await game(OPS.playStory(body.storyId)));
// --- 运行整段过场(含 NPC 站位与演出),而不是只念台词 ---
case '/api/story/scene':
return sendJson(res, await game(OPS.runStoryScene(body.storyId)));
// --- 关掉当前的消息窗口(截完图收尾用)---
case '/api/story/close': return sendJson(res, await game(OPS.closeMessage()));
// --- 莉莉娅显示 / 隐藏 ---
case '/api/lily': return sendJson(res, await game(OPS.setLily(body.show !== false)));
// --- 拍照辅助:隐藏 / 显示 对话框、立绘、HUD ---
// 只藏不关,随时能显示回来(要"真的关掉对话"请用 /api/story/close)
case '/api/ui-hidden':
return sendJson(res, await game(OPS.setUiHidden({
message: typeof body.message === 'boolean' ? body.message : null,
artwork: typeof body.artwork === 'boolean' ? body.artwork : null,
hud: typeof body.hud === 'boolean' ? body.hud : null,
})));
// --- 落地:从悬浮状态站到实地上(会先探测脚下是否安全)---
case '/api/land': return sendJson(res, await game(OPS.land()));
// --- 探测脚下地形("落地"按钮的预检,也可单独用)---
case '/api/ground': return sendJson(res, await game(OPS.probeGround()));
// --- 配置 ---
case '/api/config': {
if (req.method === 'POST') {
try {
const r = saveConfig(body);
return sendJson(res, { ok: true, ...r, defaults: DEFAULTS });
} catch (e) {
return sendJson(res, { ok: false, error: String(e.message) }, 400);
}
}
return sendJson(res, { ok: true, config: CONFIG, defaults: DEFAULTS, configFile: CONFIG_FILE });
}
// --- 作弊开关 ---
case '/api/gravity': return sendJson(res, await game(OPS.setGravity(!!body.on)));
case '/api/invincible': return sendJson(res, await game(OPS.setInvincible(!!body.on)));
case '/api/noclip': return sendJson(res, await game(OPS.setNoclip(!!body.on)));
case '/api/restore': return sendJson(res, await game(OPS.restoreAll()));
// --- 场景还原(摆拍):扫描本图丢失的角色 → 强行切页让它们出现 ---
// 静态摆拍与撤销由 photo-state 管理;自动和手动存档照常,仅提示风险。
case '/api/events/lost': {
const before = await identity();
const r = await cdp.evalJson(guarded(OPS.scanLostEvents(), before.mapToken));
return sendJson(res, { ...r, context: before.context });
}
case '/api/events/force-page':
return sendJson(res, await game(OPS.forcePage(body.eventId, body.page)));
// 取消本图所有"钉住"的页号,恢复游戏自己的选页
case '/api/events/unpin':
return sendJson(res, await game(OPS.unpinPages()));
case '/api/events/restore-cast':
// includeHidden=false(默认)只恢复"被抹除"的,那些是明确的该在不在;
// true 才连"游戏有意隐藏"的一起拉出来 —— 会凭空多出人物,界面上要警告
return sendJson(res, await game(OPS.restoreLostCast({
includeHidden: body.includeHidden === true,
})));
// --- 存"拍照专用档" ---
// ⚠️ 会覆盖该槽位原有进度,所以这里先自动备份整个存档目录再存
case '/api/save-photo': {
// 先在服务端做个粗校验,避免参数写错时白备份一次存档目录
// (真正的合法性由游戏侧按 DataManager.maxSavefiles() 判断)
const slot = Number(body.slot);
if (!Number.isInteger(slot) || slot < 1 || slot > 23) {
return sendJson(res, { ok: false, error: `槽位必须是 1~23 之间的整数(0 是自动存档槽,不能存)` }, 400);
}
const target = targetDir(body);
if (current.kind !== body.target || !SAFETY.samePath(current.dir, target) || !current.saveDir || !SAFETY.samePath(current.saveDir, path.join(target, 'save'))) throw new Error('实际连接的游戏或存档目录与所选目标不一致,未保存');
const backup = backupSaves(target, 'presave');
const r = await game(OPS.savePhotoSlot(slot));
return sendJson(res, { ...r, target: current.saveDir, safetyBackup: backup.name });
}
// --- 事件列表(当前地图)---
// 把事件页里 call_story 的故事序号翻译成台词,这样列表上显示的是
// 「台词」— 说话人 而不是 EV058 这种内部编号(见开发文档第 6 节)
case '/api/events': {
await storyCache.ensure();
const before = await identity();
const r = await cdp.evalJson(guarded(OPS.listEvents(), before.mapToken));
r.context = before.context;
if (r && r.ok) {
for (const ev of r.events) {
const lines = (ev.storyIds || [])
.map(id => ({ id, ...(storyCache.get(id) || {}) }))
.filter(s => s.first);
ev.lines = lines;
// 有剧情的事件优先展示,UI 也据此排序
ev.hasStory = (ev.storyIds || []).length > 0;
}
}
return sendJson(res, r);
}
// --- 剧情触发点 ---
// 顺便抓一次**当前地图**的"抹除状态"并缓存(开发文档第 6 节):
// 被游戏自己抹除的事件页号钉死在 -1,走过去也触发不了,
// 只标记当前地图的本次扫描,不跨地图或存档保留旧标记。
case '/api/story-text': {
await storyCache.ensure({ force: body.refresh === true });
return sendJson(res, { ok: true, ...storyCache.status() });
}
case '/api/triggers': {
await storyCache.ensure();
erasedCache.clear();
let scannedMap = null;
if (await cdp.isAlive()) {
try {
const ev = await game(OPS.listEvents());
if (ev && ev.ok && ev.mapId) {
scannedMap = ev.mapId;
for (const e of ev.events) {
erasedCache.set(`${ev.mapId}:${e.id}`, !!e.erased);
}
}
} catch { /* 没连上就只给静态数据 */ }
}
const triggers = DATA.triggers.map(t => {
const key = (t.mapId !== null && t.eventId !== '') ? `${t.mapId}:${t.eventId}` : null;
const known = key !== null && erasedCache.has(key);
const line = storyCache.get(t.storyId);
return { ...t, triggerX: t.x, triggerY: t.y, ...storyPosition(t), line: line?.first || '', speaker: line?.speaker || '',
lineCount: line?.count || 0, lines: line?.lines || [], searchText: line?.searchText || '',
erased: known ? erasedCache.get(key) : null };
});
return sendJson(res, { ok: true, triggers, scannedMap, knownErased: erasedCache.size, storyText: storyCache.status() });
}
// --- 存档备份 ---
case '/api/backups':
return sendJson(res, { ok: true, backups: listBackups(), backupDir: BACKUP_DIR });
case '/api/backup': {
const target = targetDir(body);
const label = body.target;
return sendJson(res, { ok: true, ...backupSaves(target, label) });
}
case '/api/restore-backup': {
if (!body.confirm) return sendJson(res, { ok: false, error: '需要确认(会覆盖当前存档)' }, 400);
const target = targetDir(body);
await assertGamesStopped();
return sendJson(res, { ok: true, ...FILES.restoreBackup(BACKUP_DIR, body.name, target) });
}
// --- 沙盒 ---
case '/api/sandbox': return sendJson(res, { ok: true, ...createSandbox() });
case '/api/sandbox/status': return sendJson(res, { ok: true, ...sandboxJob, exists: sandboxExists() });
default:
return sendJson(res, { ok: false, error: '未知接口: ' + urlPath }, 404);
}
}
const server = http.createServer(async (req, res) => {
try {
const u = new URL(req.url, `http://127.0.0.1:${CONFIG.webPort}`);
if (u.pathname.startsWith('/api/')) await handleApi(req, res, u.pathname, u.searchParams);
else serveStatic(res, u.pathname);
} catch (e) {
sendJson(res, { ok: false, error: String(e && e.message || e) }, 500);
}
});
// 只监听回环地址 —— 局域网内的其他人访问不到
if (require.main === module) server.listen(CONFIG.webPort, '127.0.0.1', async () => {
fs.writeFileSync(path.join(TOOL_DIR, '.server-runtime.json'), JSON.stringify({ port: server.address().port, pid: process.pid }));
console.log('');
console.log(' 咸鱼喵喵 · 截图辅助工具');
console.log(' ────────────────────────────────────────');
console.log(` 控制面板: http://127.0.0.1:${CONFIG.webPort}`);
console.log(` 游戏目录: ${GAME_DIR}`);
console.log(` 沙盒目录: ${CONFIG.sandboxDir} ${sandboxExists() ? '(已存在)' : '(未创建)'}`);
console.log(` 调试端口: ${CONFIG.cdpPort}`);
const alive = await cdp.isAlive();
console.log(` 游戏连接: ${alive ? '已检测到调试端口' : '未检测到(请先启动游戏)'}`);
console.log(' ────────────────────────────────────────');
console.log(' 按 Ctrl+C 退出');
console.log('');
});
// 退出时主动断开 CDP,不给游戏留悬挂连接
if (require.main === module) process.on('SIGINT', () => {
console.log('\n正在退出…');
cdp.close();
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 1000);
});
module.exports = { server, cdp, CONFIG, saveConfig, handleApi, executeApi, identity, storyCache };
+1046
View File
File diff suppressed because it is too large Load Diff
+335
View File
@@ -0,0 +1,335 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>咸鱼喵喵 · 截图辅助工具</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="topsticky">
<header class="topbar">
<div class="brand">
<span class="brand-name">咸鱼喵喵 · 截图辅助工具</span>
<span class="brand-sub">粉丝向 · 仅供个人截图与内容创作</span>
</div>
<div class="status-wrap">
<span id="connDot" class="dot"></span>
<span id="connText">正在检测…</span>
</div>
</header>
<!-- 游戏状态条 -->
<section class="statusbar">
<div class="stat"><label>地图</label><b id="st-map">—</b></div>
<div class="stat"><label>坐标</label><b id="st-pos">—</b></div>
<div class="stat"><label>血量</label><b id="st-hp">—</b></div>
<div class="stat"><label>已开开关</label><b id="st-sw">—</b></div>
<div class="stat"><label>重力</label><b id="st-grav">—</b></div>
<div class="stat"><label>无敌</label><b id="st-inv">—</b></div>
<!-- 当前连的是沙盒还是原版。连到原版时会变红 —— 那时任何操作都在动正式存档 -->
<div class="stat game-src" id="st-src-wrap"><label>当前连接</label><b id="st-src">—</b></div>
</section>
<!-- 常驻快捷开关:不放在二级页面里,任何标签页下都能直接点 -->
<section class="quickbar">
<span class="qb-label">状态</span>
<button class="chip" id="q-gravity" title="高亮 = 重力正常;点一下关掉重力,角色会悬空">重力</button>
<button class="chip" id="q-invincible" title="高亮 = 无敌中(不会掉血)">无敌</button>
<button class="chip" id="q-noclip" title="高亮 = 穿墙中(无视碰撞体)">穿墙</button>
<button class="chip on" id="q-lily" title="高亮 = 莉莉娅在画面里;点一下把她藏起来">莉莉娅</button>
<span class="qb-sep"></span>
<span class="qb-label">拍照</span>
<button class="chip on" id="q-msg" title="高亮 = 对话框显示中;点一下藏起来拍干净的场景(只是藏,随时能显示回来)">对话框</button>
<button class="chip on" id="q-art" title="高亮 = 立绘显示中">立绘</button>
<button class="chip on" id="q-hud" title="高亮 = 游戏界面(血条、小地图等)显示中">游戏界面</button>
<span class="qb-sep"></span>
<button class="chip danger" id="q-restore" title="恢复重力、碰撞、无敌,撤销摆拍并解除数值锁定(已修改的数值和物品不回退)">全部还原</button>
</section>
</div>
<div class="note" id="photo-state" role="status"></div>
<nav class="tabs">
<button class="tab active" data-panel="teleport">传送</button>
<button class="tab" data-panel="story">对话剧情</button>
<button class="tab" data-panel="trainer">角色与背包</button>
<button class="tab" data-panel="switches">开关</button>
<button class="tab" data-panel="saves">存档与沙盒</button>
<button class="tab" data-panel="settings">设置</button>
</nav>
<main>
<section class="panel" id="panel-trainer">
<div class="card">
<h2>金币、生命与能量</h2>
<div class="row"><span id="trainer-role">请先连接游戏并进入地图</span><button id="trainer-refresh">刷新数值与背包</button></div>
<p class="hint">作用于当前操作的角色,喵露露/莉莉娅切换形态后仍有效。输入数值后点「设值」或「设值并锁定」;锁定后不随消耗或拾取变化。修改当前值,不改变最大值。</p>
<div id="trainer-stats" class="trainer-stats"></div>
<p class="hint">数值锁定只在本次游戏中有效;读档、新游戏或面板失联超过 2 分钟自动解除。「全部还原」也会解除锁定,已修改的数值与物品不回退。</p>
</div>
<div class="card">
<h2>背包物品</h2>
<p class="hint">直接修改当前背包,游戏正常存档时会保存。移除已装备的饰品/宝石会同时卸下;移除当前武器会换到另一件已有武器。新增宝石按游戏规则自动启用。</p>
<div class="row">
<input id="trainer-search" type="search" placeholder="搜索物品名称、描述或编号" aria-label="搜索背包物品">
<select id="trainer-category" aria-label="物品分类"><option value="">全部分类</option><option value="consumables">消耗品</option><option value="weapons">武器</option><option value="stones">宝石</option><option value="ornaments">饰品</option><option value="special">特殊材料</option></select>
<label><input id="trainer-owned" type="checkbox">只看已拥有</label>
<label><input id="trainer-overcap" type="checkbox">允许超过消耗品携带上限</label>
</div>
<div id="trainer-items" class="list tall"><div class="empty">连接后读取背包</div></div>
</div>
</section>
<!-- ========== 传送 ========== -->
<section class="panel active" id="panel-teleport">
<div class="card">
<h2>坐标传送</h2>
<p class="hint">
输入目标格子的横纵坐标。<b>坐标超出地图范围会被自动夹到边界。</b>
</p>
<div class="note">
<b>传送默认进入「悬浮」状态</b>(暂停重力 + 穿墙)。<br>
这是为了避开游戏的<b>坠落复位</b>机制 —— 直接落到坑洞地形上,游戏会判定你掉下去了,
播掉落音效并把你弹回"上次站立的位置",如果这个记录还是上一张地图的,人就会直接消失。<br>
想站到地上走动时,点下面的<b>「落地」</b>(会先探测脚下安不安全)。
</div>
<div class="note warn-note">
⚠️ <b>悬浮时别按跳跃键</b> —— 跳跃给了向上的速度,而重力是关掉的,
<b>没有任何力把它拉回来,人会一直往上飘</b>。<br>
想恢复正常走动:点 <b>「落地」</b>,或顶部 <b>「全部还原」</b>。
</div>
<div class="row mt">
<label>X <input type="number" id="tp-x" min="0" step="1" value="0"></label>
<label>Y <input type="number" id="tp-y" min="0" step="1" value="0"></label>
<button class="primary" id="tp-go">传送(悬浮)</button>
<button id="tp-here">填入当前坐标</button>
<button id="tp-land">落地</button>
</div>
<div class="row mt">
<label>微调</label>
<button data-nudge="-1,0">←</button>
<button data-nudge="1,0">→</button>
<button data-nudge="0,-1">↑</button>
<button data-nudge="0,1">↓</button>
<span class="pill" id="tp-state">—</span>
</div>
</div>
<div class="card">
<h2>本图事件</h2>
<p class="hint">
默认只列出<b>带剧情的事件</b>(显示台词),也就是截图真正要用的那些。
金币、平台、装饰这类走「显示全部事件」。
</p>
<div class="row">
<button id="ev-load">读取本图事件</button>
<input type="search" id="ev-filter" placeholder="按台词 / 说话人 / 立绘名筛选…">
<label class="chk"><input type="checkbox" id="ev-all"> 显示全部事件</label>
</div>
<div class="list" id="ev-list"><div class="empty">点「读取本图事件」加载</div></div>
</div>
<div class="card warn-card">
<h2>场景还原(摆拍)</h2>
<p class="hint">
找出本图<b>本该可见却没出现</b>的角色,强行让它们出现。
用于「对话框在说话、画面里却没人」的情况。
</p>
<div class="note">
<b>⚠️ 这是摆拍,不是把游戏改回当时的样子。</b><br>
· 被游戏标记为「已抹除」的事件强行拉出来,它<b>不会执行任何指令</b>,
只是一个站着的立绘;站位也不一定和原作一致。<br>
· 摆拍会固定角色,自动和手动存档照常。不推荐摆拍时保存:读档后状态可能无法完整恢复。完成后可点<b>「撤销场景还原」</b>恢复原来的事件状态。
切图、读档或面板失联两分钟也会撤销摆拍。<br>
· 如果这条对话有「运行过场」可用,<b>优先用那个</b>——那个是真的在重现演出。
</div>
<div class="row">
<button id="lost-scan">扫描本图角色</button>
<button class="primary" id="lost-restore-all">恢复被抹除的</button>
<button id="lost-restore-hidden">连同游戏隐藏的一起</button>
<button id="lost-unpin">撤销场景还原</button>
</div>
<div class="row mt">
<span class="pill" id="lost-hint">还没扫描</span>
</div>
<div class="list" id="lost-list"><div class="empty">点「扫描本图角色」看看本图现在有谁、缺谁</div></div>
</div>
</section>
<!-- ========== 对话跳转点 ========== -->
<section class="panel" id="panel-story">
<div class="card">
<h2>对话剧情</h2>
<p class="hint">
连接后自动读取台词,支持全文搜索。<br>从游戏数据里解析出的 <b id="story-count">—</b> 条剧情触发点。
</p>
<div class="note">
<b>三种复现方式,优先试「运行过场」</b><br>
· <b>运行过场</b> —— 执行含这段对话的<b>整个事件页</b>。
NPC 站位、演出、对白全按原样走,<b>画面最接近原作</b>。通关存档也能用。<br>
&nbsp;&nbsp;&nbsp;注意:一整段过场会从头播,可能包含好几段对话,一路截图即可。<br>
· <b>只播台词</b> —— 只调那一段对白,跳过节目前的演出。快,但
<b>场景里的 NPC 可能不在场</b>(那些角色是靠前面的指令摆出来的)。<br>
· <b>前往</b> —— 打开所需开关 + 传送,你自己走过去。存档没通关时场景最自然。
</div>
<p class="hint" id="story-text-hint"></p>
<div class="row">
<input type="search" id="story-filter" placeholder="全文搜索:台词 / 说话人 / 地图 / 开关名…">
<label class="chk"><input type="checkbox" id="story-only-actionable" checked> 只看可跳转的</label>
<label class="chk"><input type="checkbox" id="story-need-switch"> 只看需要开关的</label>
</div>
<div class="row mt">
<button id="story-load-text">重新读取台词</button>
<button id="story-close-msg">关闭对话窗口</button>
<span class="pill">截完图用它收尾</span>
</div>
<div class="list tall" id="story-list"><div class="empty">正在载入…</div></div>
</div>
</section>
<!-- ========== 开关 ========== -->
<section class="panel" id="panel-switches">
<div class="card">
<h2>开关</h2>
<p class="hint">
默认只显示<b>常用开关</b>——即"隐藏对话触发条件里真正会用到的那 114 个",
比翻全部 360 个高效得多。需要时可以展开全部。
</p>
<div class="row">
<input type="search" id="sw-filter" placeholder="按开关名或编号搜索…">
<button id="sw-toggle-all">展开全部 360 个</button>
<button id="sw-reload">刷新状态</button>
</div>
<div class="row mt">
<span class="pill" id="sw-mode">当前:常用开关</span>
</div>
<div class="list tall" id="sw-list"><div class="empty">正在载入…</div></div>
</div>
</section>
<!-- ========== 存档与沙盒 ========== -->
<section class="panel" id="panel-saves">
<div class="card warn-card">
<h2>⚠️ 用之前先读这段</h2>
<ul class="warn-list">
<li>本工具会改游戏<b>运行时状态</b>(坐标、开关、物理),<b>不改游戏程序和素材;保存、还原会写入明确选定的存档目录</b>。</li>
<li>作弊状态下游戏可能自动存盘,落到 <code>file0</code>(自动存档槽)。</li>
<li>本游戏启用了 <b>Steam 云存档</b>。直接在原版游戏上折腾,被污染的存档可能被同步上去且追不回来。</li>
<li><b>所以推荐用沙盒:把游戏整体拷一份,在副本里折腾。</b>副本不在 Steam 库里,云同步够不着。</li>
</ul>
</div>
<div class="card">
<h2>沙盒副本</h2>
<p class="hint">复制游戏及存档(排除工具和发布版目录),所有操作都在副本里进行。</p>
<div class="row">
<button class="primary" id="sb-create">创建沙盒副本</button>
<button id="sb-status">刷新状态</button>
</div>
<div class="note" id="sb-info">—</div>
</div>
<div class="card">
<h2>存档备份</h2>
<p class="hint">把 <code>save/</code> 整个目录复制一份存档。原版和沙盒可以分别备份。</p>
<div class="row">
<button id="bk-original">备份原版存档</button>
<button id="bk-sandbox">备份沙盒存档</button>
<button id="bk-reload">刷新列表</button>
</div>
<div class="row"><label>还原目标 <select id="bk-target"><option value="">请选择目标</option><option value="sandbox">沙盒存档</option><option value="original">原版存档</option></select></label></div>
<div class="list" id="bk-list"><div class="empty">—</div></div>
</div>
<div class="card">
<h2>存「拍照专用档」</h2>
<p class="hint">
把当前游戏状态存进一个存档槽。摆拍时也可保存,但不保证读档后完整恢复角色、UI 或对白。
工具会先自动备份整个存档目录,再让游戏自己存。
</p>
<div class="note">
<b>⚠️ 会覆盖该槽位原有的进度。</b>
你的 24 个槽位(0 是自动存档,1~23 是手动)目前<b>全部占用</b>,
没有空槽可用——所以请自己挑一个不在乎的槽。
</div>
<div class="row">
<label>存到槽位 <input type="number" id="photo-slot" min="1" max="23" step="1" value="23"></label>
<span>实际保存目录:<code id="photo-target">未连接</code></span>
<button class="danger" id="photo-save">存为拍照档</button>
</div>
</div>
<div class="card">
<h2>关于这个工具</h2>
<p class="hint">
粉丝向的截图辅助工具,用于个人复现「错过就没了」的剧情并截图。<br>
不包含、不打包任何游戏素材;不提供成就解锁功能;不修改游戏任何文件。<br>
按作者 readme 的要求,<b>请勿用本工具提取或传播游戏素材</b>。
</p>
</div>
</section>
<!-- ========== 设置 ========== -->
<section class="panel" id="panel-settings">
<div class="card">
<h2>端口与路径</h2>
<p class="hint">
改完点保存即可生效,配置文件写在 <code id="set-path">tool/config.json</code>。
</p>
<div class="form">
<label class="field">
<span>游戏调试端口</span>
<input type="number" id="set-cdpPort" min="1024" max="65535">
<em>工具靠这个端口连游戏。原版通常 9222,沙盒建议 9223,两个别撞车。</em>
</label>
<label class="field">
<span>控制面板端口</span>
<input type="number" id="set-webPort" min="1024" max="65535">
<em>浏览器打开面板用的端口。<b>改这个要重启工具才生效。</b></em>
</label>
<label class="field">
<span>沙盒副本目录</span>
<input type="text" id="set-sandboxDir">
<em>把游戏拷一份到这里。建议放在 Steam 库外面,云同步才够不着。</em>
</label>
</div>
<div class="row mt">
<button class="primary" id="set-save">保存设置</button>
<button id="set-reset">恢复默认值</button>
</div>
</div>
<div class="card">
<h2>怎么启动这个工具</h2>
<ol class="steps">
<li>双击 <code>tool\启动.bat</code></li>
<li>它会自动:检查 SDK 版 NW.js → 备份存档 → 启动游戏 → 启动本服务 → 打开浏览器</li>
<li>在游戏里<b>正常读档</b>进入地图(工具不能替你读档,见开发文档第 6 节)</li>
</ol>
<div class="note">
<b>只想启动某一部分?</b><br>
· 只起控制面板(游戏已经在跑):在这个目录执行 <code>node server.js</code><br>
· 只启动游戏:<code>nw.exe "沙盒目录" --remote-debugging-port=9223</code><br>
· 改了控制面板端口后,要关掉旧的服务窗口再重新 <code>node server.js</code>
</div>
</div>
<div class="card">
<h2>当前状态</h2>
<div class="list" id="set-info"><div class="empty">—</div></div>
</div>
</section>
</main>
<div id="toast" class="toast"></div>
<script src="app.js"></script>
</body>
</html>
+308
View File
@@ -0,0 +1,308 @@
/* 咸鱼喵喵 · 截图辅助工具 —— 控制面板样式 */
:root {
--bg: #14121a;
--bg-card: #1e1b26;
--bg-input: #2a2634;
--bg-hover: #332e40;
--border: #35303f;
--text: #e9e6f0;
--text-dim: #9d97ac;
--accent: #ff8ab8;
--accent-dk: #d96a96;
--ok: #5fd39a;
--warn: #f0b849;
--danger: #f07070;
--radius: 10px;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 14px/1.6 "Microsoft YaHei", "PingFang SC", system-ui, sans-serif;
padding-bottom: 48px;
}
/* ---------- 顶栏 ---------- */
/* 顶部三件套(标题栏 + 状态条 + 快捷开关)整体吸顶 */
.topsticky {
position: sticky; top: 0; z-index: 50;
box-shadow: 0 4px 14px rgba(0,0,0,.35);
}
.topbar {
display: flex; align-items: center; justify-content: space-between;
flex-wrap: wrap; gap: 12px;
padding: 14px 22px;
background: linear-gradient(180deg, #241f2e, #1a1722);
border-bottom: 1px solid var(--border);
}
.brand-name { font-size: 17px; font-weight: 700; color: var(--accent); }
.brand-sub { display: block; font-size: 12px; color: var(--text-dim); font-weight: 400; }
.status-wrap { display: flex; align-items: center; gap: 8px; font-size: 13px; }
.dot {
width: 9px; height: 9px; border-radius: 50%;
background: var(--text-dim); display: inline-block;
box-shadow: 0 0 0 0 rgba(95,211,154,.6);
}
.dot.on { background: var(--ok); animation: pulse 2.4s infinite; }
.dot.off { background: var(--danger); }
@keyframes pulse {
0% { box-shadow: 0 0 0 0 rgba(95,211,154,.5); }
70% { box-shadow: 0 0 0 8px rgba(95,211,154,0); }
100% { box-shadow: 0 0 0 0 rgba(95,211,154,0); }
}
/* ---------- 状态条 ---------- */
.statusbar {
display: flex; flex-wrap: wrap; gap: 10px;
padding: 12px 22px;
background: #191623;
border-bottom: 1px solid var(--border);
}
.stat {
display: flex; align-items: baseline; gap: 7px;
background: var(--bg-card); border: 1px solid var(--border);
border-radius: 8px; padding: 5px 12px;
}
.stat label { font-size: 12px; color: var(--text-dim); }
.stat b { font-size: 14px; font-variant-numeric: tabular-nums; }
/* 「当前连接」——整行独占,连到原版时整块变红 */
.stat.game-src { flex: 1 1 100%; }
.stat.game-src b {
font-family: Consolas, monospace; font-size: 12px;
word-break: break-all;
}
.stat.game-src.sandbox b { color: var(--ok); }
.stat.game-src.original {
background: #3a2222; border-color: var(--danger);
}
.stat.game-src.original b { color: #ff9b9b; font-weight: 700; }
.stat.game-src.other b { color: var(--warn); }
/* ---------- 常驻快捷开关条 ---------- */
.quickbar {
display: flex; align-items: center; flex-wrap: wrap; gap: 6px;
padding: 9px 22px;
background: #1d1a27;
border-bottom: 1px solid var(--border);
}
.qb-label {
font-size: 12px; color: var(--text-dim);
margin-right: 2px; user-select: none;
}
.qb-sep {
width: 1px; height: 18px; background: var(--border);
margin: 0 8px;
}
/* 胶囊开关:高亮 = 这个开关是"开着/显示着"的 */
.chip {
padding: 5px 14px; font-size: 13px;
border-radius: 999px;
background: #262231; border: 1px solid var(--border);
color: var(--text-dim);
transition: background .12s, color .12s, border-color .12s;
}
.chip:hover:not(:disabled) { background: var(--bg-hover); border-color: var(--accent); color: var(--text); }
.chip.on {
background: #4a2a3c; border-color: var(--accent);
color: #ffd7e8; font-weight: 700;
}
.chip.on::before {
content: '●'; font-size: 9px; margin-right: 5px;
color: var(--accent); vertical-align: 1px;
}
.chip.danger { border-color: #7a3a3a; color: #ffc9c9; }
.chip.danger:hover { background: #6a3232; border-color: var(--danger); }
/* ---------- 标签页 ---------- */
.tabs {
display: flex; gap: 4px; flex-wrap: wrap;
padding: 14px 22px 0;
}
.tab {
background: transparent; color: var(--text-dim);
border: 1px solid transparent; border-bottom: none;
border-radius: 8px 8px 0 0;
padding: 9px 18px; cursor: pointer; font-size: 14px;
font-family: inherit;
}
.tab:hover { background: var(--bg-hover); color: var(--text); }
.tab.active {
background: var(--bg-card); color: var(--accent);
border-color: var(--border); font-weight: 700;
}
/* ---------- 面板 ---------- */
main { padding: 0 22px; }
.panel { display: none; }
.panel.active { display: block; }
.card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 18px 20px;
margin: 16px 0;
}
.card h2 {
margin: 0 0 6px; font-size: 15px; color: var(--accent);
font-weight: 700;
}
.hint { margin: 0 0 14px; font-size: 13px; color: var(--text-dim); }
.hint b { color: var(--text); }
.note {
margin-top: 14px; padding: 10px 14px;
background: #232030; border-left: 3px solid var(--accent);
border-radius: 6px; font-size: 13px; color: var(--text-dim);
}
.note b { color: var(--text); }
/* 警告性质的提示条 */
.note.warn-note {
border-left-color: var(--warn);
background: #2b2620;
color: #e0d5c2;
}
.note.warn-note b { color: var(--warn); }
.warn-card { border-color: #5a4630; background: #241f1a; }
.warn-card h2 { color: var(--warn); }
.warn-list { margin: 0; padding-left: 20px; font-size: 13px; color: #d8cfc0; }
.warn-list li { margin: 6px 0; }
.warn-list b { color: var(--warn); }
code {
background: #2a2634; padding: 1px 6px; border-radius: 4px;
font-family: Consolas, monospace; font-size: 12px; color: var(--accent);
}
/* ---------- 控件 ---------- */
.row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.row.mt { margin-top: 12px; }
.row label { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--text-dim); }
input[type="number"], input[type="search"], input[type="text"] {
background: var(--bg-input); color: var(--text);
border: 1px solid var(--border); border-radius: 7px;
padding: 8px 11px; font: inherit; font-size: 13px;
}
input[type="number"] { width: 92px; }
input[type="search"] { flex: 1; min-width: 200px; }
input:focus { outline: none; border-color: var(--accent); }
button {
background: var(--bg-input); color: var(--text);
border: 1px solid var(--border); border-radius: 7px;
padding: 8px 15px; cursor: pointer; font: inherit; font-size: 13px;
transition: background .12s, border-color .12s;
}
button:hover:not(:disabled) { background: var(--bg-hover); border-color: var(--accent); }
button:disabled { opacity: .45; cursor: not-allowed; }
button.primary { background: var(--accent-dk); border-color: var(--accent); color: #fff; font-weight: 700; }
button.primary:hover:not(:disabled) { background: var(--accent); }
button.danger { background: #4a2626; border-color: #7a3a3a; color: #ffc9c9; }
button.danger:hover:not(:disabled) { background: #6a3232; }
.chk { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--text-dim); cursor: pointer; }
input[type="checkbox"] { accent-color: var(--accent); width: 15px; height: 15px; cursor: pointer; }
.toggles { display: flex; flex-direction: column; gap: 10px; }
.toggle {
display: flex; align-items: center; gap: 10px;
background: var(--bg-input); border: 1px solid var(--border);
border-radius: 8px; padding: 11px 15px; cursor: pointer;
font-size: 14px; transition: border-color .12s;
}
.toggle:hover { border-color: var(--accent); }
.toggle input { width: 17px; height: 17px; }
.pill {
display: inline-block; background: var(--bg-input);
border: 1px solid var(--border); border-radius: 999px;
padding: 3px 12px; font-size: 12px; color: var(--text-dim);
}
/* ---------- 设置表单 ---------- */
.form { display: flex; flex-direction: column; gap: 16px; }
.field { display: grid; grid-template-columns: 160px 1fr; gap: 6px 14px; align-items: center; }
.field > span { font-size: 13px; color: var(--text); }
.field > em {
grid-column: 2; font-style: normal;
font-size: 12px; color: var(--text-dim); line-height: 1.5;
}
.field > em b { color: var(--warn); }
.field input { width: 100%; max-width: 420px; }
.steps { margin: 0; padding-left: 22px; font-size: 13px; color: var(--text-dim); }
.steps li { margin: 7px 0; }
.steps b { color: var(--text); }
/* ---------- 列表 ---------- */
.list {
margin-top: 12px; max-height: 320px; overflow-y: auto;
border: 1px solid var(--border); border-radius: 8px;
background: #191623;
}
.list.tall { max-height: 560px; }
.empty { padding: 26px; text-align: center; color: var(--text-dim); font-size: 13px; }
.item {
display: flex; align-items: center; gap: 12px;
padding: 9px 14px; border-bottom: 1px solid #241f2e;
font-size: 13px;
}
.item:last-child { border-bottom: none; }
.item:hover { background: var(--bg-hover); }
.item .grow { flex: 1; min-width: 0; }
.item .name { color: var(--text); }
.item .meta { font-size: 12px; color: var(--text-dim); }
.item .num {
font-family: Consolas, monospace; font-size: 12px;
color: var(--text-dim); min-width: 44px;
}
.item .tag {
font-size: 11px; padding: 1px 7px; border-radius: 4px;
background: #2f2a3c; color: var(--text-dim); white-space: nowrap;
}
.item .tag.common { background: #3a2a38; color: var(--accent); }
.item .tag.ok { background: #1f3a2c; color: var(--ok); }
.item .tag.danger { background: #4a2626; color: #ff9b9b; }
/* 分类小标题行 */
.item.cat-head {
background: #221e2c; color: var(--text-dim);
font-size: 12px; font-weight: 700;
padding: 7px 14px;
position: sticky; top: 0; z-index: 2;
}
.item.cat-head.warn-head { background: #2b2420; color: var(--warn); }
.item button { padding: 4px 11px; font-size: 12px; }
/* 开关行 */
.switch-on { color: var(--ok); font-weight: 700; }
.switch-off { color: var(--text-dim); }
/* ---------- 提示条 ---------- */
.toast {
position: fixed; left: 50%; bottom: 28px; transform: translateX(-50%) translateY(20px);
background: #2a2634; border: 1px solid var(--accent);
color: var(--text); padding: 11px 22px; border-radius: 9px;
font-size: 13px; opacity: 0; pointer-events: none;
transition: opacity .2s, transform .2s; z-index: 999;
max-width: 80vw;
}
.toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
.toast.err { border-color: var(--danger); background: #3a2222; }
.toast.ok { border-color: var(--ok); background: #1f3329; }
.trainer-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 12px; margin-top: 16px; }
.trainer-stat { padding: 14px; border: 1px solid var(--border); border-radius: 8px; }
.trainer-stat .row { margin-top: 12px; flex-wrap: wrap; }
.trainer-stat input, #trainer-items input[type=number] { width: 95px; }
#trainer-items .item { flex-wrap: wrap; }
+76
View File
@@ -0,0 +1,76 @@
# 使用须知(发布版,2026-10-03 修订)
## 确认当前操作哪份游戏
看顶部“当前连接”和存档页“实际保存目录”。身份从游戏的 Node 入口及 StorageManager 存档路径读取,不依赖网页 URL。实机网页 URL 是 chrome-extension 地址。
调试端口可达不等于已连接,更不等于已进入地图。标题画面请正常读档;不要从外部直接调用 DataManager.loadGame 绕过游戏的 completeLoad 流程。
## 常见提示
| 提示或现象 | 处理 |
|---|---|
| 调试端口和面板端口相同 | 设置两个不同的端口,再启动 |
| 端口上的游戏与目标不符/无法识别 | 关闭占用该端口的游戏,或为各实例配置不同端口;不会自动放行 |
| 旧服务或旧配置占用面板端口 | 停止旧面板后再启动;本次升级前的旧服务需关闭原来的命令行窗口 |
| 副本缺失/复制未完成 | 不启动残缺副本;选择新的空目录重建。不会覆盖已有目录 |
| 地图、存档或连接已变化 | 刷新状态并重新读取本图事件/扫描角色,旧列表不能用于新地图 |
| 莉莉娅脚下不安全 | 她保持悬浮;移动到安全地面再点“落地” |
| 跨地图超时 | 工具会取消尚未完成的传送请求;确认游戏是否被菜单或演出占用,再重试 |
| 备份失败 | 不会继续启动需要备份的游戏或覆盖槽位。检查目录、磁盘空间及是否仍在写档 |
| 当前有摆拍角色,提示不推荐保存 | 读档后摆拍状态可能无法完整恢复;可自行决定继续保存,不要求先撤销 |
悬浮时按跳跃仍可能一直向上运动;关重力没有取消跳跃输入。落地会检查地形,“全部还原”会直接恢复正常物理状态,使用时应处于安全位置。
## 搜索和剧情
发布版从游戏运行时读取全文台词,全部在内存中使用,不写剧本或缓存文件。先开面板再开游戏也会自动读取;故事表未就绪时最多尝试四次、间隔至少三秒,仍失败会显示原因,可手动重新读取。断线、换实例或重连都会使旧台词失效,重连成功后自动补齐。
搜索覆盖整段台词和说话人,并显示命中句;未连接时仍可搜索地图、坐标、事件和条件。
“运行过场”包含剧情指令,可能改变游戏开关和进度。分支剧情可能跳过先前的演出;前往只自动设置普通开关,不承诺还原完整历史进度。没有任何一页提供角色形象的事件,也不能凭空生成合适 NPC。
## 场景还原与撤销
恢复的角色是固定的摆拍对象,不再自动执行原事件、移动或参与物理碰撞。清除“已抹除”状态只是临时操作;撤销会恢复修改前的字段、原有抹除状态及方法。
“被抹除”不证明这个人应该出现在当前剧情。选择哪些角色和站位仍需核对画面;不要把全部恢复后的画面当成原作的准确复现。
摆拍期间自动和手动存档照常,工具不拦截游戏自身的保存。顶部提示不推荐摆拍时保存;面板保存的原有确认框会说明风险,仍可确定继续。完成后可撤销;切图或正常读档自动撤销。面板关闭或失联超过两分钟也会撤销,恢复事件原有行为。
这次没有实现“保存并读回完整摆拍布局”。临时函数、UI 显示状态、剧情解释器不承诺跨存档复现。
## 备份与还原
- 新备份记录来源,使用唯一目录并校验每个 .rmmzsave 文件。未完成或损坏备份不列为可恢复项。
- 旧时间戳备份仍可读取,但显示来源未知。还原时必须明确选目标,不能凭备份名称猜。
- 还原前先退出游戏和 NW.js 游戏窗口,防止运行中的游戏把旧状态写回。
- 还原得到所选备份中的完整存档集合;备份没有的槽位不会继续留在当前 save 目录。
- 当前存档会先备份;原 save 目录保留为游戏目录下的 `.save-before-restore-…`,不会直接删除。
- steam_autocloud.vdf 等非存档文件保留目标目录自己的版本,不从另一份游戏的备份覆盖。
## 已知画面限制
先前记录的“切换剧情分支时角色短暂抽动”,没有足够实机证据保证所有地图均已解决;本轮不把它标成已修。相同立绘的多个事件、剧情自身的移动与刷新仍可能影响演出效果。
并非全部剧情均已验收。遇到问题请记录故事编号、地图、事件页、存档进度和使用的按钮。
## 本轮剧情显示与定位修复
#370 横排重复角色的原因是动画图整张显示,现已同步单帧裁切修复。升级后需重启面板和游戏,再刷新网页,才会加载新的游戏内 helper。
运行无形自动/并行控制事件时,会优先保留同图的安全站位,或在目标地图寻找可落地位置。找不到安全地面会停止启动剧情并提示手动定位。运行过场在准备完成后尝试落地;普通手动传送仍默认悬浮。自动选点不等于还原原作站位。
#305 的“运行过场”仍可能先播同页的 #298/#299;直接查看 #305 请用“只播台词”。
## 角色与背包、锁定
“角色与背包”页可设置并分别锁定金币、HP、SP、ZP,以及搜索、添加、移除背包物品。作用于当前操作角色,包含切换后的莉莉娅形态,不修改独立跟随的莉莉娅。金币范围 0~99999,其余不能超过当前最大值;不会改变上限。已倒下时请先在游戏里复活或读档。
消耗品默认遵循携带上限,可勾选超上限(最多 99999)。移除装备会同步卸下,移除当前武器会换到另一件已有武器,至少保留一件。铃铛容量、任务及收集进度不在修改范围内。
锁定立即阻止该数值的消耗和增加。读档、新游戏、面板失联超过两分钟或点“全部还原”会解除锁定;已修改的数值和背包不会回退,正常保存会把当前数值和物品写进存档。
本轮同时更新了摆拍人物贴地、原图待机动画和面向主角。仅对原页要求贴地的人物小范围探地,飞行角色和固定摆件不强制落地;撤销恢复原始位置和朝向。首次升级这批摆拍修复,需要重启面板和游戏后刷新网页。
+5
View File
@@ -0,0 +1,5 @@
@echo off
chcp 65001 >nul
setlocal DisableDelayedExpansion
node "%~dp0launcher.js" --stop
if errorlevel 1 pause
+33
View File
@@ -0,0 +1,33 @@
{
"version": 1,
"files": [
"tool/启动.bat",
"tool/停止面板.bat",
"tool/launcher.js",
"tool/server.js",
"tool/lib/safety.js",
"tool/lib/files.js",
"tool/lib/processes.js",
"tool/lib/cdp.js",
"tool/lib/probe-game.js",
"tool/lib/ops.js",
"tool/lib/photo-state.js",
"tool/lib/trainer.js",
"tool/lib/story-position.js",
"tool/lib/data.js",
"tool/lib/story-cache.js",
"tool/web/app.js",
"tool/web/index.html",
"tool/web/style.css",
"tool/README.md",
"tool/使用须知.md",
"tool/发布清单.json",
"out/triggers.csv",
"unpacked/data/System.json",
"unpacked/data/MapInfos.json",
"README.md",
".gitignore"
],
"optionalRuntime": "nwjs-sdk-v0.64.1-win-x64/",
"note": "本包仅含工具及必要结构索引;台词从游戏运行时读取。Node.js 和 NW.js SDK 需另行安装。"
}
+15
View File
@@ -0,0 +1,15 @@
@echo off
chcp 65001 >nul
setlocal DisableDelayedExpansion
where node >nul 2>&1
if errorlevel 1 (
echo 找不到 Node.js。请安装 Node.js 22 或更新版本后重试。
pause
exit /b 1
)
node "%~dp0launcher.js"
if errorlevel 1 (
pause
exit /b 1
)
exit /b 0