EmulatorJS/data/GameManager.js

378 lines
15 KiB
JavaScript
Raw Normal View History

class EJS_GameManager {
2023-07-03 17:24:25 +00:00
constructor(Module, EJS) {
this.EJS = EJS;
this.Module = Module;
this.FS = this.Module.FS;
this.functions = {
restart: this.Module.cwrap('system_restart', '', []),
getStateInfo: this.Module.cwrap('get_state_info', 'string', []), //these names are dumb
saveStateInfo: this.Module.cwrap('save_state_info', 'null', []),
loadState: this.Module.cwrap('load_state', 'number', ['string', 'number']),
2023-06-23 16:33:20 +00:00
screenshot: this.Module.cwrap('cmd_take_screenshot', '', []),
simulateInput: this.Module.cwrap('simulate_input', 'null', ['number', 'number', 'number']),
2023-06-27 16:54:35 +00:00
toggleMainLoop: this.Module.cwrap('toggleMainLoop', 'null', ['number']),
2023-06-28 18:27:06 +00:00
getCoreOptions: this.Module.cwrap('get_core_options', 'string', []),
setVariable: this.Module.cwrap('ejs_set_variable', 'null', ['string', 'string']),
2023-06-29 15:35:25 +00:00
setCheat: this.Module.cwrap('set_cheat', 'null', ['number', 'number', 'string']),
2023-06-29 16:49:48 +00:00
resetCheat: this.Module.cwrap('reset_cheat', 'null', []),
2023-07-01 16:46:52 +00:00
toggleShader: this.Module.cwrap('shader_enable', 'null', ['number']),
getDiskCount: this.Module.cwrap('get_disk_count', 'number', []),
getCurrentDisk: this.Module.cwrap('get_current_disk', 'number', []),
2023-07-01 21:21:48 +00:00
setCurrentDisk: this.Module.cwrap('set_current_disk', 'null', ['number']),
2023-07-03 14:31:38 +00:00
getSaveFilePath: this.Module.cwrap('save_file_path', 'string', []),
saveSaveFiles: this.Module.cwrap('cmd_savefiles', '', []),
2023-07-07 17:22:20 +00:00
supportsStates: this.Module.cwrap('supports_states', 'number', []),
2023-07-14 16:43:13 +00:00
loadSaveFiles: this.Module.cwrap('refresh_save_files', 'null', []),
2023-08-07 16:31:20 +00:00
toggleFastForward: this.Module.cwrap('toggle_fastforward', 'null', ['number']),
2023-08-10 21:40:25 +00:00
setFastForwardRatio: this.Module.cwrap('set_ff_ratio', 'null', ['number']),
toggleRewind: this.Module.cwrap('toggle_rewind', 'null', ['number']),
2023-08-11 16:20:11 +00:00
setRewindGranularity: this.Module.cwrap('set_rewind_granularity', 'null', ['number']),
toggleSlowMotion: this.Module.cwrap('toggle_slow_motion', 'null', ['number']),
2023-09-18 18:02:56 +00:00
setSlowMotionRatio: this.Module.cwrap('set_sm_ratio', 'null', ['number']),
getFrameNum: this.Module.cwrap('get_current_frame_count', 'number', [''])
}
this.writeFile("/home/web_user/retroarch/userdata/config/Beetle PSX HW/Beetle PSX HW.opt", 'beetle_psx_hw_renderer = "software"\n');
2023-06-28 17:57:02 +00:00
2023-07-07 15:02:00 +00:00
this.mkdir("/data");
this.mkdir("/data/saves");
this.writeFile("/home/web_user/retroarch/userdata/retroarch.cfg", this.getRetroArchCfg());
2023-06-29 16:49:48 +00:00
2023-07-07 17:22:20 +00:00
this.FS.mount(IDBFS, {}, '/data/saves');
this.FS.syncfs(true, () => {});
2023-06-29 16:49:48 +00:00
this.initShaders();
2023-07-07 17:22:20 +00:00
this.EJS.addEventListener(window, "beforeunload", () => {
this.saveSaveFiles();
this.FS.syncfs(() => {});
})
2023-06-28 17:57:02 +00:00
}
loadExternalFiles() {
return new Promise((resolve, reject) => {
if (this.EJS.config.externalFiles && this.EJS.config.externalFiles.constructor.name === 'Object') {
for (const key in this.EJS.config.externalFiles) {
let path = key;
if (key.trim().endsWith("/")) {
const invalidCharacters = /[#<$+%>!`&*'|{}/\\?"=@:^\r\n]/ig;
let name = this.EJS.config.externalFiles[key].split("/").pop().split("#")[0].split("?")[0].replace(invalidCharacters, "").trim();
if (!name) continue;
path += name;
}
this.EJS.downloadFile(this.EJS.config.externalFiles[key], (res) => {
if (res === -1) {
if (this.EJS.debug) console.warn("Failed to fetch file from '" + this.EJS.config.externalFiles[key] + "'. Make sure the file exists.");
return resolve();
}
try {
this.writeFile(path, this.EJS.config.externalFiles[key]);
} catch(e) {
if (this.EJS.debug) console.warn("Failed to write file to '" + path + "'. Make sure there are no conflicting files.");
}
resolve();
}, null, true, {responseType: "text", method: "GET"});
}
} else resolve();
});
}
writeFile(path, data) {
const parts = path.split("/");
let current = "/";
for (let i=0; i<parts.length-1; i++) {
if (!parts[i].trim()) continue;
current += parts[i] + "/";
this.mkdir(current);
}
this.FS.writeFile(path, data);
}
2023-06-28 17:57:02 +00:00
mkdir(path) {
try {
this.FS.mkdir(path);
} catch(e) {}
}
getRetroArchCfg() {
2023-07-07 17:22:20 +00:00
return "autosave_interval = 60\n" +
2023-07-21 14:54:49 +00:00
"screenshot_directory = \"/\"\n" +
2023-07-07 17:22:20 +00:00
"block_sram_overwrite = false\n" +
"video_gpu_screenshot = false\n" +
"audio_latency = 64\n" +
"video_top_portrait_viewport = true\n" +
2023-07-07 17:22:20 +00:00
"video_vsync = true\n" +
"video_smooth = false\n" +
2023-08-07 16:31:20 +00:00
"fastforward_ratio = 3.0\n" +
2023-08-11 16:20:11 +00:00
"slowmotion_ratio = 3.0\n" +
(this.EJS.rewindEnabled ? "rewind_enable = true\n" : "") +
(this.EJS.rewindEnabled ? "rewind_granularity = 6\n" : "") +
2023-07-07 17:22:20 +00:00
"savefile_directory = \"/data/saves\"\n";
}
2023-06-29 16:49:48 +00:00
initShaders() {
if (!window.EJS_SHADERS) return;
this.mkdir("/shader");
for (const shader in window.EJS_SHADERS) {
this.FS.writeFile('/shader/'+shader, window.EJS_SHADERS[shader]);
}
}
2023-10-03 00:41:16 +00:00
clearEJSResetTimer() {
if (this.EJS.resetTimeout) {
clearTimeout(this.EJS.resetTimeout);
delete this.EJS.resetTimeout;
}
}
restart() {
2023-10-03 00:41:16 +00:00
this.clearEJSResetTimer();
this.functions.restart();
}
getState() {
return new Promise(async (resolve, reject) => {
const stateInfo = (await this.getStateInfo()).split('|')
let state;
let size = stateInfo[0] >> 0;
if (size > 0) {
state = new Uint8Array(size);
let start = stateInfo[1] >> 0;
for (let i=0; i<size; i++) state[i] = this.Module.getValue(start + i);
}
resolve(state);
})
}
getStateInfo() {
this.functions.saveStateInfo();
return new Promise((resolve, reject) => {
let a;
let b = setInterval(() => {
a = this.functions.getStateInfo();
if (a) {
clearInterval(b);
resolve(a);
}
}, 50)
});
}
loadState(state) {
try {
this.FS.unlink('game.state');
} catch(e){}
this.FS.writeFile('/game.state', state);
2023-10-03 00:41:16 +00:00
this.clearEJSResetTimer();
this.functions.loadState("game.state", 0);
setTimeout(() => {
2023-07-03 17:03:00 +00:00
try {
this.FS.unlink('game.state');
} catch(e){}
}, 5000)
}
screenshot() {
this.functions.screenshot();
return this.FS.readFile('screenshot.png');
}
2023-07-03 17:03:00 +00:00
quickSave(slot) {
if (!slot) slot = 1;
(async () => {
let name = slot + '-quick.state';
try {
this.FS.unlink(name);
} catch (e) {}
let data = await this.getState();
this.FS.writeFile('/'+name, data);
})();
}
2023-07-03 17:03:00 +00:00
quickLoad(slot) {
if (!slot) slot = 1;
(async () => {
let name = slot + '-quick.state';
2023-10-03 00:41:16 +00:00
this.clearEJSResetTimer();
this.functions.loadState(name, 0);
})();
}
2023-06-23 16:33:20 +00:00
simulateInput(player, index, value) {
2023-07-17 16:10:34 +00:00
if (this.EJS.isNetplay) {
this.EJS.netplay.simulateInput(player, index, value);
return;
}
2023-08-11 16:20:11 +00:00
if ([24, 25, 26, 27, 28, 29].includes(index)) {
2023-07-03 17:24:25 +00:00
if (index === 24 && value === 1) {
const slot = this.EJS.settings['save-state-slot'] ? this.EJS.settings['save-state-slot'] : "1";
this.quickSave(slot);
this.EJS.displayMessage(this.EJS.localization("SAVED STATE TO SLOT")+" "+slot);
}
if (index === 25 && value === 1) {
const slot = this.EJS.settings['save-state-slot'] ? this.EJS.settings['save-state-slot'] : "1";
this.quickLoad(slot);
this.EJS.displayMessage(this.EJS.localization("LOADED STATE FROM SLOT")+" "+slot);
}
if (index === 26 && value === 1) {
let newSlot;
try {
newSlot = parseFloat(this.EJS.settings['save-state-slot'] ? this.EJS.settings['save-state-slot'] : "1") + 1;
} catch(e) {
newSlot = 1;
}
if (newSlot > 9) newSlot = 1;
this.EJS.displayMessage(this.EJS.localization("SET SAVE STATE SLOT TO")+" "+newSlot);
this.EJS.changeSettingOption('save-state-slot', newSlot.toString());
}
2023-08-07 16:31:20 +00:00
if (index === 27) {
2023-08-08 14:04:13 +00:00
this.functions.toggleFastForward(this.EJS.isFastForward ? !value : value);
2023-08-07 16:31:20 +00:00
}
2023-08-11 16:20:11 +00:00
if (index === 29) {
this.functions.toggleSlowMotion(this.EJS.isSlowMotion ? !value : value);
}
2023-08-10 21:40:25 +00:00
if (index === 28) {
2023-08-11 10:54:58 +00:00
if (this.EJS.rewindEnabled) {
2023-08-10 21:40:25 +00:00
this.functions.toggleRewind(value);
}
}
2023-07-03 17:24:25 +00:00
return;
}
2023-06-23 16:33:20 +00:00
this.functions.simulateInput(player, index, value);
}
2023-08-04 16:52:11 +00:00
getFileNames() {
if (this.EJS.getCore() === "picodrive") {
return ["bin", "gen", "smd", "md", "32x", "cue", "iso", "sms", "68k", "chd"];
} else {
return ["toc", "ccd", "exe", "pbp", "chd", "img", "bin", "iso"];
}
}
2023-07-06 16:33:12 +00:00
createCueFile(fileNames) {
try {
2023-07-09 00:46:06 +00:00
if (fileNames.length > 1) {
fileNames = fileNames.filter((item) => {
2023-08-04 16:52:11 +00:00
return this.getFileNames().includes(item.split(".").pop().toLowerCase());
2023-07-09 00:46:06 +00:00
})
fileNames = fileNames.sort((a, b) => {
if (isNaN(a.charAt()) || isNaN(b.charAt())) throw new Error("Incorrect file name format");
return (parseInt(a.charAt()) > parseInt(b.charAt())) ? 1 : -1;
})
}
2023-07-06 16:33:12 +00:00
} catch(e) {
if (fileNames.length > 1) {
console.warn("Could not auto-create cue file(s).");
return null;
}
}
for (let i=0; i<fileNames.length; i++) {
if (fileNames[i].split(".").pop().toLowerCase() === "ccd") {
console.warn("Did not auto-create cue file(s). Found a ccd.");
return null;
}
}
if (fileNames.length === 0) {
console.warn("Could not auto-create cue file(s).");
return null;
}
let baseFileName = fileNames[0].split("/").pop();
if (baseFileName.includes(".")) {
baseFileName = baseFileName.substring(0, baseFileName.length - baseFileName.split(".").pop().length - 1);
}
for (let i=0; i<fileNames.length; i++) {
const contents = " FILE \""+fileNames[i]+"\" BINARY\n TRACK 01 MODE1/2352\n INDEX 01 00:00:00";
FS.writeFile("/"+baseFileName+"-"+i+".cue", contents);
}
if (fileNames.length > 1) {
let contents = "";
for (let i=0; i<fileNames.length; i++) {
contents += "/"+baseFileName+"-"+i+".cue\n";
}
FS.writeFile("/"+baseFileName+".m3u", contents);
}
return (fileNames.length === 1) ? baseFileName+"-0.cue" : baseFileName+".m3u";
}
loadPpssppAssets() {
return new Promise(resolve => {
this.EJS.downloadFile('cores/ppsspp-assets.zip', (res) => {
this.EJS.checkCompression(new Uint8Array(res.data), this.EJS.localization("Decompress Game Data")).then((pspassets) => {
if (pspassets === -1) {
this.EJS.textElem.innerText = this.localization('Network Error');
this.EJS.textElem.style.color = "red";
return;
}
this.mkdir("/PPSSPP");
for (const file in pspassets) {
const data = pspassets[file];
const path = "/PPSSPP/"+file;
const paths = path.split("/");
let cp = "";
for (let i=0; i<paths.length-1; i++) {
if (paths[i] === "") continue;
cp += "/"+paths[i];
if (!FS.analyzePath(cp).exists) {
FS.mkdir(cp);
}
}
this.FS.writeFile(path, data);
}
resolve();
})
}, null, false, {responseType: "arraybuffer", method: "GET"});
})
}
2023-06-23 16:33:20 +00:00
toggleMainLoop(playing) {
2023-08-10 19:15:01 +00:00
this.functions.toggleMainLoop(playing);
2023-06-23 16:33:20 +00:00
}
2023-06-27 16:54:35 +00:00
getCoreOptions() {
return this.functions.getCoreOptions();
}
2023-06-28 18:27:06 +00:00
setVariable(option, value) {
this.functions.setVariable(option, value);
}
2023-06-29 15:35:25 +00:00
setCheat(index, enabled, code) {
this.functions.setCheat(index, enabled, code);
}
resetCheat() {
this.functions.resetCheat();
}
2023-06-29 16:49:48 +00:00
toggleShader(active) {
this.functions.toggleShader(active);
}
2023-07-01 16:46:52 +00:00
getDiskCount() {
return this.functions.getDiskCount();
}
getCurrentDisk() {
return this.functions.getCurrentDisk();
}
setCurrentDisk(disk) {
this.functions.setCurrentDisk(disk);
}
2023-07-03 14:31:38 +00:00
getSaveFilePath() {
return this.functions.getSaveFilePath();
}
saveSaveFiles() {
this.functions.saveSaveFiles();
2023-07-07 17:22:20 +00:00
this.FS.syncfs(false, () => {});
2023-07-03 14:31:38 +00:00
}
supportsStates() {
return !!this.functions.supportsStates();
2023-07-01 21:21:48 +00:00
}
2023-07-07 15:02:00 +00:00
getSaveFile() {
2023-07-07 17:22:20 +00:00
this.saveSaveFiles();
const exists = FS.analyzePath(this.getSaveFilePath()).exists;
return (exists ? FS.readFile(this.getSaveFilePath()) : null);
}
loadSaveFiles() {
2023-10-03 00:41:16 +00:00
this.clearEJSResetTimer();
2023-07-07 17:22:20 +00:00
this.functions.loadSaveFiles();
2023-07-07 15:02:00 +00:00
}
2023-08-07 16:31:20 +00:00
setFastForwardRatio(ratio) {
this.functions.setFastForwardRatio(ratio);
}
toggleFastForward(active) {
this.functions.toggleFastForward(active);
}
2023-08-11 16:20:11 +00:00
setSlowMotionRatio(ratio) {
this.functions.setSlowMotionRatio(ratio);
}
toggleSlowMotion(active) {
this.functions.toggleSlowMotion(active);
}
2023-08-10 21:40:25 +00:00
setRewindGranularity(value) {
this.functions.setRewindGranularity(value);
}
2023-09-18 18:02:56 +00:00
getFrameNum() {
return this.functions.getFrameNum();
}
}
window.EJS_GameManager = EJS_GameManager;