Music with a live player, Last.fm, video downloads, games, AI chat, moderation, logging, a web dashboard and a Game Boy Activity. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
913 lines
36 KiB
JavaScript
913 lines
36 KiB
JavaScript
/* Dezio Game Boy — a Discord Activity.
|
||
*
|
||
* The emulator (binjgb, WebAssembly) runs right here in the player's Discord client; the bot only
|
||
* serves the page, the ROMs and the saves (core/activity.py). Controls: keyboard, game controllers
|
||
* (Gamepad API) and on-screen touch buttons. In-game (battery) saves upload by themselves; save
|
||
* states are gzipped and kept per account in 4 slots (slot 0 = "continue where I left off").
|
||
*/
|
||
'use strict';
|
||
|
||
const BASE = location.pathname.startsWith('/activity') ? '/activity' : '';
|
||
const $ = (s) => document.querySelector(s);
|
||
const CPU_HZ = 4194304;
|
||
const AUDIO_FRAMES = 4096;
|
||
const AUDIO_LATENCY = 0.1;
|
||
const MAX_STEP = 5 / 60;
|
||
const EV_FRAME = 1, EV_AUDIO = 2, EV_UNTIL = 4;
|
||
const PALETTES = 84;
|
||
const MIN_HOLD = 4; // frames
|
||
const AUTOSTATE_MS = 300000;
|
||
const CATEGORY_COLOURS = { pokemon: '#e03131', zelda: '#2f9e44', mario: '#d9480f', kirby: '#e64980', other: '#5c7cfa' };
|
||
const BUTTONS = ['UP', 'DOWN', 'LEFT', 'RIGHT', 'A', 'B', 'START', 'SELECT'];
|
||
|
||
const app = {
|
||
session: null, user: null, sdk: null, games: [], category: 'all',
|
||
game: null, emu: null, nextModule: null, audio: null,
|
||
};
|
||
|
||
/* ---- small helpers ------------------------------------------------------------------ */
|
||
const prefs = {
|
||
get(key, fallback) { try { const v = localStorage.getItem('gb.' + key); return v === null ? fallback : JSON.parse(v); } catch { return fallback; } },
|
||
set(key, value) { try { localStorage.setItem('gb.' + key, JSON.stringify(value)); } catch { /* storage off */ } },
|
||
};
|
||
|
||
let toastTimer = 0;
|
||
function toast(text, ms = 2200) {
|
||
const el = $('#toast');
|
||
el.textContent = text;
|
||
el.classList.add('show');
|
||
clearTimeout(toastTimer);
|
||
toastTimer = setTimeout(() => el.classList.remove('show'), ms);
|
||
}
|
||
|
||
function ago(seconds) {
|
||
const d = Math.max(0, Date.now() / 1000 - seconds);
|
||
if (d < 60) return 'just now';
|
||
if (d < 3600) return `${Math.floor(d / 60)} min ago`;
|
||
if (d < 86400) return `${Math.floor(d / 3600)} h ago`;
|
||
return new Date(seconds * 1000).toLocaleDateString();
|
||
}
|
||
|
||
function ask(text, buttons) {
|
||
return new Promise((resolve) => {
|
||
$('#dialog-text').textContent = text;
|
||
const row = $('#dialog-btns');
|
||
row.replaceChildren();
|
||
for (const [label, value, primary] of buttons) {
|
||
const b = document.createElement('button');
|
||
b.className = 'chip' + (primary ? ' on' : '');
|
||
b.textContent = label;
|
||
b.onclick = () => { $('#dialog').hidden = true; resolve(value); };
|
||
row.append(b);
|
||
}
|
||
$('#dialog').hidden = false;
|
||
});
|
||
}
|
||
|
||
async function api(path, options = {}) {
|
||
const headers = { ...(options.headers || {}) };
|
||
if (app.session) headers.Authorization = 'Bearer ' + app.session;
|
||
const response = await fetch(`${BASE}/api/${path}`, { ...options, headers });
|
||
if (response.status === 401) throw new Error('Your session ran out — close and reopen the Activity.');
|
||
return response;
|
||
}
|
||
|
||
async function gzip(bytes) {
|
||
if (typeof CompressionStream === 'undefined') return bytes;
|
||
const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream('gzip'));
|
||
return new Uint8Array(await new Response(stream).arrayBuffer());
|
||
}
|
||
|
||
async function gunzip(bytes) {
|
||
if (bytes[0] !== 0x1f || bytes[1] !== 0x8b) return bytes;
|
||
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'));
|
||
return new Uint8Array(await new Response(stream).arrayBuffer());
|
||
}
|
||
|
||
/* ---- ROM cache (IndexedDB: the Chromebook's upload is slow, fetch each ROM once) --------- */
|
||
const romCache = {
|
||
db: null,
|
||
open() {
|
||
if (this.db) return Promise.resolve(this.db);
|
||
return new Promise((resolve) => {
|
||
try {
|
||
const req = indexedDB.open('dezio-gb', 1);
|
||
req.onupgradeneeded = () => req.result.createObjectStore('roms');
|
||
req.onsuccess = () => resolve(this.db = req.result);
|
||
req.onerror = () => resolve(null);
|
||
} catch { resolve(null); }
|
||
});
|
||
},
|
||
async get(key) {
|
||
const db = await this.open();
|
||
if (!db) return null;
|
||
return new Promise((resolve) => {
|
||
try {
|
||
const req = db.transaction('roms').objectStore('roms').get(key);
|
||
req.onsuccess = () => resolve(req.result || null);
|
||
req.onerror = () => resolve(null);
|
||
} catch { resolve(null); }
|
||
});
|
||
},
|
||
async put(key, buffer) {
|
||
const db = await this.open();
|
||
if (!db) return;
|
||
try { db.transaction('roms', 'readwrite').objectStore('roms').put(buffer, key); } catch { /* quota */ }
|
||
},
|
||
};
|
||
|
||
async function loadRom(game, onProgress) {
|
||
const key = `${game.id}:${game.version}`;
|
||
const cached = await romCache.get(key);
|
||
if (cached) return cached;
|
||
const response = await api(`rom/${game.id}?v=${game.version}`);
|
||
if (!response.ok) throw new Error('Couldn\'t download the game.');
|
||
const total = Number(response.headers.get('Content-Length')) || game.size;
|
||
const reader = response.body.getReader();
|
||
const parts = [];
|
||
let got = 0;
|
||
for (;;) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
parts.push(value);
|
||
got += value.length;
|
||
onProgress(Math.min(1, got / total));
|
||
}
|
||
const buffer = await new Blob(parts).arrayBuffer();
|
||
romCache.put(key, buffer);
|
||
return buffer;
|
||
}
|
||
|
||
/* ---- audio --------------------------------------------------------------------------- */
|
||
class Sound {
|
||
constructor() {
|
||
this.ctx = new (window.AudioContext || window.webkitAudioContext)();
|
||
this.gain = this.ctx.createGain();
|
||
this.gain.connect(this.ctx.destination);
|
||
this.volume = prefs.get('volume', 60);
|
||
this.next = 0;
|
||
}
|
||
set volume(v) { this._v = v; this.gain.gain.value = (v / 100) ** 2; }
|
||
get volume() { return this._v; }
|
||
unlock() { if (this.ctx.state !== 'running') this.ctx.resume().catch(() => {}); }
|
||
push(samples) {
|
||
const now = this.ctx.currentTime;
|
||
if (this.ctx.state !== 'running') return;
|
||
if (this.next < now) this.next = now + AUDIO_LATENCY;
|
||
if (this.next > now + 0.5) return; // running ahead (fast-forward): drop
|
||
const buffer = this.ctx.createBuffer(2, AUDIO_FRAMES, this.ctx.sampleRate);
|
||
const left = buffer.getChannelData(0), right = buffer.getChannelData(1);
|
||
for (let i = 0; i < AUDIO_FRAMES; i++) {
|
||
left[i] = samples[2 * i] / 255 - 0.5;
|
||
right[i] = samples[2 * i + 1] / 255 - 0.5;
|
||
}
|
||
const source = this.ctx.createBufferSource();
|
||
source.buffer = buffer;
|
||
source.connect(this.gain);
|
||
source.start(this.next);
|
||
this.next += AUDIO_FRAMES / this.ctx.sampleRate;
|
||
}
|
||
reset() { this.next = 0; }
|
||
}
|
||
|
||
/* ---- emulator wrapper -------------------------------------------------------------------- */
|
||
class Emulator {
|
||
constructor(module, romBuffer, sampleRate) {
|
||
this.m = module;
|
||
const size = (romBuffer.byteLength + 0x7fff) & ~0x7fff; // binjgb wants 32 KB multiples
|
||
this.romPtr = module._malloc(size);
|
||
this.heap(this.romPtr, size).fill(0).set(new Uint8Array(romBuffer));
|
||
this.e = module._emulator_new_simple(this.romPtr, size, sampleRate, AUDIO_FRAMES, 2);
|
||
if (!this.e) { module._free(this.romPtr); throw new Error('That ROM didn\'t load.'); }
|
||
// binjgb reads the buttons through a joypad callback; without it games only see some presses
|
||
this.joypadPtr = module._joypad_new();
|
||
module._emulator_set_default_joypad_callback(this.e, this.joypadPtr);
|
||
this.leftover = 0;
|
||
this.lastTime = 0;
|
||
this.speed = 1;
|
||
this.joy = Object.fromEntries(BUTTONS.map((b) => [b, false]));
|
||
this.downAt = {};
|
||
this.pendingUp = {};
|
||
this.frames = 0;
|
||
this.setters = {
|
||
UP: module._set_joyp_up, DOWN: module._set_joyp_down, LEFT: module._set_joyp_left, RIGHT: module._set_joyp_right,
|
||
A: module._set_joyp_A, B: module._set_joyp_B, START: module._set_joyp_start, SELECT: module._set_joyp_select,
|
||
};
|
||
this.ramDirty = false;
|
||
}
|
||
heap(ptr, size) { return new Uint8Array(this.m.HEAP8.buffer, ptr, size); }
|
||
get ticks() { return this.m._emulator_get_ticks_f64(this.e); }
|
||
frame() { return this.heap(this.m._get_frame_buffer_ptr(this.e), this.m._get_frame_buffer_size(this.e)); }
|
||
audioBuffer() { return this.heap(this.m._get_audio_buffer_ptr(this.e), this.m._get_audio_buffer_capacity(this.e)); }
|
||
/* A press lasts at least MIN_HOLD emulated frames: a quick tap (or a synthetic key event) would
|
||
otherwise come and go between two of the game's joypad reads. */
|
||
press(button, down) {
|
||
if (down) {
|
||
delete this.pendingUp[button];
|
||
if (this.joy[button]) return;
|
||
this.downAt[button] = this.frames;
|
||
} else {
|
||
if (!this.joy[button]) return;
|
||
if (this.frames - this.downAt[button] < MIN_HOLD) { this.pendingUp[button] = true; return; }
|
||
}
|
||
this.joy[button] = down;
|
||
this.setters[button](this.e, down ? 1 : 0);
|
||
}
|
||
flushReleases() {
|
||
for (const b of Object.keys(this.pendingUp)) {
|
||
if (this.frames - this.downAt[b] >= MIN_HOLD) {
|
||
delete this.pendingUp[b];
|
||
this.joy[b] = false;
|
||
this.setters[b](this.e, 0);
|
||
}
|
||
}
|
||
}
|
||
releaseAll() { for (const b of BUTTONS) this.press(b, false); }
|
||
palette(n) { this.m._emulator_set_builtin_palette(this.e, n); }
|
||
|
||
/** Run the CPU for `seconds` of game time; calls onFrame/onAudio as they happen. */
|
||
run(seconds, onFrame, onAudio) {
|
||
const until = this.ticks + seconds * CPU_HZ - this.leftover;
|
||
for (;;) {
|
||
const event = this.m._emulator_run_until_f64(this.e, until);
|
||
if (event & EV_FRAME) { this.frames++; this.flushReleases(); onFrame(); }
|
||
if (event & EV_AUDIO) onAudio();
|
||
if (event & EV_UNTIL) break;
|
||
}
|
||
this.leftover = this.ticks - until;
|
||
if (this.m._emulator_was_ext_ram_updated(this.e)) this.ramDirty = true;
|
||
}
|
||
|
||
withFile(ptr, fn) {
|
||
const buffer = this.heap(this.m._get_file_data_ptr(ptr), this.m._get_file_data_size(ptr));
|
||
try { return fn(ptr, buffer); } finally { this.m._file_data_delete(ptr); }
|
||
}
|
||
getRam() {
|
||
return this.withFile(this.m._ext_ram_file_data_new(this.e), (ptr, buf) => {
|
||
this.m._emulator_write_ext_ram(this.e, ptr);
|
||
return buf.slice();
|
||
});
|
||
}
|
||
setRam(bytes) {
|
||
return this.withFile(this.m._ext_ram_file_data_new(this.e), (ptr, buf) => {
|
||
if (buf.byteLength === 0) return false;
|
||
// older saves may carry a few extra bytes (RTC): load what fits
|
||
buf.set(bytes.subarray(0, buf.byteLength));
|
||
this.m._emulator_read_ext_ram(this.e, ptr);
|
||
return true;
|
||
});
|
||
}
|
||
get hasRam() {
|
||
return this.withFile(this.m._ext_ram_file_data_new(this.e), (ptr, buf) => buf.byteLength > 0);
|
||
}
|
||
getState() {
|
||
return this.withFile(this.m._state_file_data_new(this.e), (ptr, buf) => {
|
||
this.m._emulator_write_state(this.e, ptr);
|
||
return buf.slice();
|
||
});
|
||
}
|
||
setState(bytes) {
|
||
return this.withFile(this.m._state_file_data_new(this.e), (ptr, buf) => {
|
||
if (buf.byteLength !== bytes.byteLength) return false;
|
||
buf.set(bytes);
|
||
return this.m._emulator_read_state(this.e, ptr) === 0;
|
||
});
|
||
}
|
||
destroy() {
|
||
this.m._emulator_delete(this.e);
|
||
this.m._joypad_delete(this.joypadPtr);
|
||
this.m._free(this.romPtr);
|
||
}
|
||
}
|
||
|
||
/* ---- screen ------------------------------------------------------------------------------ */
|
||
const screen = {
|
||
canvas: null, ctx: null, image: null,
|
||
init() {
|
||
this.canvas = $('#screen');
|
||
this.ctx = this.canvas.getContext('2d', { alpha: false });
|
||
this.image = this.ctx.createImageData(160, 144);
|
||
},
|
||
draw(frame) {
|
||
this.image.data.set(frame);
|
||
this.ctx.putImageData(this.image, 0, 0);
|
||
},
|
||
fit() {
|
||
const stage = $('#stage');
|
||
const hint = $('#keys-hint');
|
||
const w = stage.clientWidth - 20;
|
||
const h = stage.clientHeight - 20 - (hint.offsetParent ? hint.offsetHeight + 6 : 0);
|
||
let scale = Math.min(w / 160, h / 144);
|
||
if (scale >= 2) scale = Math.floor(scale); // crisp pixels when there's room
|
||
scale = Math.max(scale, 1);
|
||
this.canvas.style.width = `${Math.round(160 * scale)}px`;
|
||
this.canvas.style.height = `${Math.round(144 * scale)}px`;
|
||
},
|
||
};
|
||
|
||
/* ---- input ---------------------------------------------------------------------------------- */
|
||
const KEYS = {
|
||
ArrowUp: 'UP', KeyW: 'UP', ArrowDown: 'DOWN', KeyS: 'DOWN', ArrowLeft: 'LEFT', KeyA: 'LEFT', ArrowRight: 'RIGHT', KeyD: 'RIGHT',
|
||
KeyX: 'A', KeyK: 'A', KeyZ: 'B', KeyJ: 'B', Enter: 'START', NumpadEnter: 'START',
|
||
ShiftLeft: 'SELECT', ShiftRight: 'SELECT', Backspace: 'SELECT',
|
||
};
|
||
const input = {
|
||
keys: new Set(), touch: new Map(), pad: new Set(), ffKey: false, ffPad: false, padMenu: false,
|
||
sync() {
|
||
const emu = app.emu;
|
||
if (!emu) return;
|
||
const held = new Set([...this.keys, ...this.pad]);
|
||
for (const set of this.touch.values()) for (const b of set) held.add(b);
|
||
for (const b of BUTTONS) emu.press(b, held.has(b));
|
||
// opposite directions at once confuse some games
|
||
if (held.has('UP') && held.has('DOWN')) emu.press('DOWN', false);
|
||
if (held.has('LEFT') && held.has('RIGHT')) emu.press('RIGHT', false);
|
||
document.querySelectorAll('[data-btn]').forEach((el) => el.classList.toggle('pressed', held.has(el.dataset.btn)));
|
||
const dirs = { up: 'UP', down: 'DOWN', left: 'LEFT', right: 'RIGHT' };
|
||
for (const [cls, b] of Object.entries(dirs)) $(`.dp.${cls}`).classList.toggle('pressed', held.has(b));
|
||
},
|
||
clear() { this.keys.clear(); this.touch.clear(); this.pad.clear(); this.ffKey = false; this.sync(); },
|
||
|
||
bindKeyboard() {
|
||
window.addEventListener('keydown', (e) => {
|
||
app.audio?.unlock();
|
||
if (!app.emu || !$('#dialog').hidden) return;
|
||
if (e.code === 'Escape' || e.code === 'KeyP') { e.preventDefault(); return toggleMenu(); }
|
||
if (!$('#menu').hidden) return;
|
||
if (e.code === 'Space') { e.preventDefault(); this.ffKey = true; return; }
|
||
if (e.code === 'F5') { e.preventDefault(); return saveState(1); }
|
||
if (e.code === 'F8') { e.preventDefault(); return loadState(1); }
|
||
const b = KEYS[e.code];
|
||
if (b) { e.preventDefault(); this.keys.add(b); this.sync(); }
|
||
});
|
||
window.addEventListener('keyup', (e) => {
|
||
if (e.code === 'Space') this.ffKey = false;
|
||
const b = KEYS[e.code];
|
||
if (b) { this.keys.delete(b); this.sync(); }
|
||
});
|
||
window.addEventListener('blur', () => { this.keys.clear(); this.ffKey = false; this.sync(); });
|
||
},
|
||
|
||
/* Every finger is tracked on its own; whatever is under it counts as held (slide between buttons works). */
|
||
buttonsAt(x, y) {
|
||
const out = new Set();
|
||
const dpad = $('#dpad').getBoundingClientRect();
|
||
const pad = 18;
|
||
if (x >= dpad.left - pad && x <= dpad.right + pad && y >= dpad.top - pad && y <= dpad.bottom + pad) {
|
||
const dx = x - (dpad.left + dpad.width / 2), dy = y - (dpad.top + dpad.height / 2);
|
||
const dead = dpad.width * 0.12;
|
||
if (Math.hypot(dx, dy) > dead) {
|
||
const angle = Math.atan2(dy, dx) * 180 / Math.PI; // 0 = right, 90 = down
|
||
if (angle > -67.5 && angle < 67.5) out.add('RIGHT');
|
||
if (angle > 22.5 && angle < 157.5) out.add('DOWN');
|
||
if (angle > 112.5 || angle < -112.5) out.add('LEFT');
|
||
if (angle > -157.5 && angle < -22.5) out.add('UP');
|
||
}
|
||
return out;
|
||
}
|
||
const el = document.elementFromPoint(x, y)?.closest('[data-btn]');
|
||
if (el) out.add(el.dataset.btn);
|
||
return out;
|
||
},
|
||
bindTouch() {
|
||
const zone = $('#body');
|
||
const update = (e) => {
|
||
if (!app.emu || e.pointerType === 'mouse' && e.buttons === 0 && e.type === 'pointermove') return;
|
||
const before = this.touch.get(e.pointerId);
|
||
const now = this.buttonsAt(e.clientX, e.clientY);
|
||
if (e.type === 'pointerdown' || (before && [...now].some((b) => !before.has(b)))) {
|
||
if (now.size && navigator.vibrate) navigator.vibrate(8);
|
||
}
|
||
this.touch.set(e.pointerId, now);
|
||
this.sync();
|
||
};
|
||
const end = (e) => { this.touch.delete(e.pointerId); this.sync(); };
|
||
zone.addEventListener('pointerdown', (e) => {
|
||
app.audio?.unlock();
|
||
if (!e.target.closest('.side, .sysrow')) return;
|
||
e.preventDefault();
|
||
zone.setPointerCapture?.(e.pointerId);
|
||
update(e);
|
||
});
|
||
zone.addEventListener('pointermove', (e) => { if (this.touch.has(e.pointerId)) update(e); });
|
||
zone.addEventListener('pointerup', end);
|
||
zone.addEventListener('pointercancel', end);
|
||
zone.addEventListener('lostpointercapture', end);
|
||
zone.addEventListener('contextmenu', (e) => e.preventDefault());
|
||
},
|
||
|
||
/* Standard mapping: Nintendo-style positions (right face button = A, bottom = B). */
|
||
pollGamepads() {
|
||
const pads = navigator.getGamepads ? navigator.getGamepads() : [];
|
||
const held = new Set();
|
||
let ff = false, menu = false;
|
||
for (const gp of pads) {
|
||
if (!gp || !gp.connected) continue;
|
||
const btn = (i) => gp.buttons[i] && (gp.buttons[i].pressed || gp.buttons[i].value > 0.5);
|
||
if (btn(1) || btn(3)) held.add('A');
|
||
if (btn(0) || btn(2)) held.add('B');
|
||
if (btn(8)) held.add('SELECT');
|
||
if (btn(9)) held.add('START');
|
||
if (btn(12) || gp.axes[1] < -0.5) held.add('UP');
|
||
if (btn(13) || gp.axes[1] > 0.5) held.add('DOWN');
|
||
if (btn(14) || gp.axes[0] < -0.5) held.add('LEFT');
|
||
if (btn(15) || gp.axes[0] > 0.5) held.add('RIGHT');
|
||
if (btn(5) || btn(7)) ff = true;
|
||
if (btn(16)) menu = true;
|
||
}
|
||
if (menu && !this.padMenu) toggleMenu();
|
||
this.padMenu = menu;
|
||
this.ffPad = ff;
|
||
const changed = held.size !== this.pad.size || [...held].some((b) => !this.pad.has(b));
|
||
if (changed) {
|
||
if (!this.pad.size && held.size && !this.toldPad) { this.toldPad = true; toast('🎮 Controller connected'); }
|
||
this.pad = held;
|
||
this.sync();
|
||
}
|
||
},
|
||
};
|
||
|
||
/* ---- main loop ------------------------------------------------------------------------------------ */
|
||
let raf = 0;
|
||
function loop(time) {
|
||
raf = requestAnimationFrame(loop);
|
||
const emu = app.emu;
|
||
if (!emu) return;
|
||
input.pollGamepads();
|
||
if (!$('#menu').hidden || !$('#dialog').hidden || document.hidden) { emu.lastTime = 0; return; }
|
||
const dt = emu.lastTime ? Math.min((time - emu.lastTime) / 1000, MAX_STEP) : 1 / 60;
|
||
emu.lastTime = time;
|
||
const speed = input.ffKey || input.ffPad ? Math.max(emu.speed, 3) : emu.speed;
|
||
let drew = false;
|
||
emu.run(dt * speed, () => { drew = true; }, () => { if (speed === 1) app.audio.push(emu.audioBuffer()); });
|
||
if (drew) screen.draw(emu.frame());
|
||
if (emu.ramDirty) scheduleRamUpload();
|
||
}
|
||
|
||
/* ---- saves ----------------------------------------------------------------------------------------- */
|
||
let ramTimer = 0, ramBusy = false;
|
||
function scheduleRamUpload() {
|
||
clearTimeout(ramTimer);
|
||
ramTimer = setTimeout(uploadRam, 2500); // games write their save in bursts
|
||
}
|
||
async function uploadRam({ keepalive = false } = {}) {
|
||
const emu = app.emu, game = app.game;
|
||
if (!emu || !emu.ramDirty || ramBusy) return;
|
||
emu.ramDirty = false;
|
||
ramBusy = true;
|
||
try {
|
||
const r = await api(`save/${game.id}`, { method: 'PUT', body: emu.getRam(), keepalive, headers: { 'Content-Type': 'application/octet-stream' } });
|
||
if (!r.ok) throw new Error();
|
||
game.save = Math.floor(Date.now() / 1000);
|
||
setStatus('💾 saved');
|
||
} catch {
|
||
emu.ramDirty = true;
|
||
setStatus('⚠ save not uploaded — retrying');
|
||
setTimeout(uploadRam, 15000);
|
||
} finally {
|
||
ramBusy = false;
|
||
}
|
||
}
|
||
|
||
async function saveState(slot, { quiet = false } = {}) {
|
||
const emu = app.emu, game = app.game;
|
||
if (!emu) return false;
|
||
try {
|
||
const body = await gzip(emu.getState());
|
||
const r = await api(`state/${game.id}/${slot}`, { method: 'PUT', body, headers: { 'Content-Type': 'application/octet-stream' } });
|
||
if (!r.ok) throw new Error();
|
||
game.states[slot] = Math.floor(Date.now() / 1000);
|
||
if (!quiet) toast(slot ? `Saved to slot ${slot}` : 'Saved');
|
||
renderSlots();
|
||
return true;
|
||
} catch {
|
||
if (!quiet) toast('⚠ Couldn\'t save the state');
|
||
return false;
|
||
}
|
||
}
|
||
|
||
async function loadState(slot) {
|
||
const emu = app.emu, game = app.game;
|
||
if (!emu || !game.states[slot]) return toast('That slot is empty');
|
||
try {
|
||
const r = await api(`state/${game.id}/${slot}`);
|
||
if (r.status !== 200) throw new Error();
|
||
const ok = emu.setState(await gunzip(new Uint8Array(await r.arrayBuffer())));
|
||
if (!ok) throw new Error();
|
||
app.audio.reset();
|
||
toast(slot ? `Loaded slot ${slot}` : 'Continuing where you left off');
|
||
closeMenu();
|
||
} catch {
|
||
toast('⚠ That save state didn\'t load');
|
||
}
|
||
}
|
||
|
||
async function deleteState(slot) {
|
||
const game = app.game;
|
||
await api(`state/${game.id}/${slot}`, { method: 'DELETE' }).catch(() => {});
|
||
delete game.states[slot];
|
||
renderSlots();
|
||
}
|
||
|
||
function setStatus(text) {
|
||
$('#game-status').textContent = text;
|
||
clearTimeout(setStatus.t);
|
||
setStatus.t = setTimeout(() => { $('#game-status').textContent = ''; }, 4000);
|
||
}
|
||
|
||
/* ---- menu ---------------------------------------------------------------------------------------- */
|
||
function renderSlots() {
|
||
const game = app.game;
|
||
if (!game) return;
|
||
const box = $('#slots');
|
||
box.replaceChildren();
|
||
for (const slot of [0, 1, 2, 3]) {
|
||
const row = document.createElement('div');
|
||
row.className = 'slot';
|
||
const name = document.createElement('div');
|
||
name.className = 'slot-name';
|
||
name.textContent = slot ? `Slot ${slot}` : 'Auto (on quit)';
|
||
const when = document.createElement('small');
|
||
when.textContent = game.states[slot] ? ago(game.states[slot]) : 'empty';
|
||
name.append(when);
|
||
row.append(name);
|
||
const add = (label, fn, title) => {
|
||
const b = document.createElement('button');
|
||
b.className = 'chip';
|
||
b.textContent = label;
|
||
b.title = title;
|
||
b.onclick = fn;
|
||
row.append(b);
|
||
};
|
||
if (slot) add('Save', () => saveState(slot), `Save to slot ${slot} (F5 = slot 1)`);
|
||
if (game.states[slot]) {
|
||
add('Load', () => loadState(slot), 'Load this state (F8 = slot 1)');
|
||
add('✕', async () => {
|
||
if (await ask(`Delete ${slot ? `slot ${slot}` : 'the auto save state'}?`, [['Cancel', false], ['Delete', true, true]])) deleteState(slot);
|
||
}, 'Delete');
|
||
}
|
||
box.append(row);
|
||
}
|
||
}
|
||
|
||
function openMenu() {
|
||
input.clear();
|
||
renderSlots();
|
||
const game = app.game;
|
||
$('#menu-title').textContent = game.title;
|
||
$('#vol').value = app.audio.volume;
|
||
$('#speed').value = String(app.emu.speed);
|
||
$('#touch').value = prefs.get('touch', 'auto');
|
||
$('#orient').value = prefs.get('orient', 'portrait');
|
||
$('#orient-row').hidden = !(app.sdk && app.platform === 'mobile');
|
||
$('#pal-row').hidden = game.cgb;
|
||
$('#pal-name').textContent = paletteName(prefs.get(`pal.${game.id}`, 0));
|
||
$('#btn-import').hidden = !(game.legacy && app.emu.hasRam);
|
||
$('#menu').hidden = false;
|
||
}
|
||
function closeMenu() { $('#menu').hidden = true; $('#screen').focus(); }
|
||
function toggleMenu() { if (!app.emu) return; if ($('#menu').hidden) openMenu(); else closeMenu(); }
|
||
function paletteName(n) { return `${n + 1}/${PALETTES}`; }
|
||
|
||
function setSpeed(speed) {
|
||
app.emu.speed = speed;
|
||
$('#btn-ff').textContent = `⏩ ${speed}×`;
|
||
$('#btn-ff').classList.toggle('on', speed > 1);
|
||
app.audio.reset();
|
||
}
|
||
|
||
/* On phones and tablets Discord opens Activities in landscape unless told otherwise: default to portrait
|
||
(screen on top, controls underneath), switchable in the menu. */
|
||
const ORIENTATION = { auto: 1, portrait: 2, landscape: 3 };
|
||
function applyOrientation() {
|
||
if (!app.sdk || app.platform !== 'mobile') return;
|
||
const state = ORIENTATION[prefs.get('orient', 'portrait')] || ORIENTATION.portrait;
|
||
app.sdk.commands.setOrientationLockState({ lock_state: state, picture_in_picture_lock_state: state, grid_lock_state: state })
|
||
.catch((err) => console.warn('orientation', err));
|
||
}
|
||
|
||
function applyTouchMode() {
|
||
const mode = prefs.get('touch', 'auto');
|
||
const coarse = matchMedia('(pointer: coarse)').matches || app.platform === 'mobile';
|
||
const show = mode === 'on' || (mode === 'auto' && coarse);
|
||
$('#player').classList.toggle('touch', show);
|
||
$('#player').classList.toggle('no-touch', !show);
|
||
sizePad();
|
||
requestAnimationFrame(() => screen.fit());
|
||
}
|
||
|
||
function sizePad() {
|
||
const w = innerWidth, h = innerHeight;
|
||
const landscape = w > h;
|
||
const size = landscape ? Math.min(170, Math.max(110, h * 0.42), w * 0.2) : Math.min(170, Math.max(110, w * 0.36), h * 0.24);
|
||
document.documentElement.style.setProperty('--pad', `${Math.round(size)}px`);
|
||
}
|
||
|
||
function bindMenu() {
|
||
$('#btn-menu').onclick = toggleMenu;
|
||
$('#menu-close').onclick = closeMenu;
|
||
$('#menu').addEventListener('click', (e) => { if (e.target.id === 'menu') closeMenu(); });
|
||
$('#btn-ff').onclick = () => setSpeed(app.emu.speed >= 4 ? 1 : app.emu.speed + 1);
|
||
$('#speed').onchange = (e) => setSpeed(Number(e.target.value));
|
||
$('#vol').oninput = (e) => { app.audio.volume = Number(e.target.value); prefs.set('volume', app.audio.volume); };
|
||
$('#touch').onchange = (e) => { prefs.set('touch', e.target.value); applyTouchMode(); };
|
||
$('#orient').onchange = (e) => { prefs.set('orient', e.target.value); applyOrientation(); };
|
||
const shiftPalette = (step) => {
|
||
const key = `pal.${app.game.id}`;
|
||
const n = (prefs.get(key, 0) + step + PALETTES) % PALETTES;
|
||
prefs.set(key, n);
|
||
app.emu.palette(n);
|
||
$('#pal-name').textContent = paletteName(n);
|
||
};
|
||
$('#pal-prev').onclick = () => shiftPalette(-1);
|
||
$('#pal-next').onclick = () => shiftPalette(1);
|
||
$('#btn-reset').onclick = async () => {
|
||
if (!await ask('Restart the game? Anything since your last in-game save is lost.', [['Cancel', false], ['Restart', true, true]])) return;
|
||
const game = app.game;
|
||
await quitGame({ save: false });
|
||
startGame(game, { fresh: true });
|
||
};
|
||
$('#btn-quit').onclick = () => quitGame({ save: true });
|
||
$('#btn-back').onclick = () => quitGame({ save: true });
|
||
$('#btn-import').onclick = async () => {
|
||
if (app.importing) return;
|
||
app.importing = true;
|
||
try { await importLegacy(); } finally { app.importing = false; }
|
||
};
|
||
}
|
||
|
||
async function importLegacy() {
|
||
if (app.game.save && !await ask('You already have a save for this game. Replace it with the old Dezio save?',
|
||
[['Keep mine', false], ['Replace', true, true]])) return;
|
||
const r = await api(`legacy/${app.game.id}`);
|
||
if (r.status !== 200) return toast('No old save found');
|
||
const game = app.game;
|
||
app.emu.setRam(new Uint8Array(await r.arrayBuffer()));
|
||
app.emu.ramDirty = true;
|
||
await uploadRam();
|
||
await quitGame({ save: false, keepRam: true });
|
||
await startGame(game, { fresh: true });
|
||
toast('Old save imported — load it from the game\'s menu');
|
||
}
|
||
|
||
/* ---- library ------------------------------------------------------------------------------------- */
|
||
function showLibrary() {
|
||
$('#player').hidden = true;
|
||
$('#library').hidden = false;
|
||
renderLibrary();
|
||
presence(null);
|
||
}
|
||
|
||
const CATEGORY_NAMES = { pokemon: 'Pokémon' };
|
||
const catName = (cat) => CATEGORY_NAMES[cat] || cat[0].toUpperCase() + cat.slice(1);
|
||
const byTitle = (a, b) => a.title.localeCompare(b.title, undefined, { numeric: true, sensitivity: 'base' });
|
||
|
||
function gameCard(game) {
|
||
const card = document.createElement('button');
|
||
card.className = 'cart';
|
||
card.style.setProperty('--c', CATEGORY_COLOURS[game.category] || CATEGORY_COLOURS.other);
|
||
card.title = game.title;
|
||
const grip = document.createElement('div');
|
||
grip.className = 'cart-grip';
|
||
const label = document.createElement('div');
|
||
label.className = 'cart-label';
|
||
const cover = document.createElement('div');
|
||
cover.className = 'cart-cover';
|
||
const big = document.createElement('div'); // shown when there's no cover art
|
||
big.className = 'cart-title-big';
|
||
big.textContent = game.title;
|
||
cover.append(big);
|
||
if (game.art) {
|
||
const img = document.createElement('img');
|
||
img.alt = '';
|
||
img.loading = 'lazy';
|
||
img.decoding = 'async';
|
||
img.src = `${BASE}/api/art/${game.id}`;
|
||
img.onload = () => cover.classList.add('has-art');
|
||
img.onerror = () => img.remove();
|
||
cover.append(img);
|
||
}
|
||
const title = document.createElement('div');
|
||
title.className = 'cart-title';
|
||
title.textContent = game.title;
|
||
const meta = document.createElement('div');
|
||
meta.className = 'cart-meta';
|
||
const tag = (text, cls) => { const t = document.createElement('span'); t.className = 'tag ' + cls; t.textContent = text; meta.append(t); };
|
||
tag(game.cgb ? 'COLOR' : 'GB', game.cgb ? 'cgb' : '');
|
||
if (game.states[0]) tag('▶ resume', 'resume');
|
||
else if (game.save) tag('💾 save', 'save');
|
||
label.append(cover, title, meta);
|
||
card.append(grip, label);
|
||
card.onclick = () => startGame(game);
|
||
return card;
|
||
}
|
||
|
||
function renderLibrary() {
|
||
const cats = [...new Set(app.games.map((g) => g.category))].sort();
|
||
const nav = $('#cats');
|
||
nav.replaceChildren();
|
||
for (const cat of ['all', ...cats]) {
|
||
const b = document.createElement('button');
|
||
b.className = 'cat' + (cat === app.category ? ' on' : '');
|
||
b.textContent = cat === 'all' ? 'All games' : catName(cat);
|
||
b.onclick = () => { app.category = cat; prefs.set('category', cat); renderLibrary(); };
|
||
nav.append(b);
|
||
}
|
||
const box = $('#grid');
|
||
box.replaceChildren();
|
||
const shown = app.category === 'all' ? cats : cats.filter((c) => c === app.category);
|
||
if (!app.games.length) {
|
||
const p = document.createElement('div');
|
||
p.className = 'empty';
|
||
p.textContent = 'No games here yet — the bot\'s owner can add .gb / .gbc files to assets/roms/<category>/.';
|
||
box.append(p);
|
||
}
|
||
for (const cat of shown) {
|
||
const games = app.games.filter((g) => g.category === cat).sort(byTitle);
|
||
const section = document.createElement('section');
|
||
section.className = 'shelf';
|
||
if (app.category === 'all') {
|
||
const head = document.createElement('h2');
|
||
head.className = 'shelf-head';
|
||
head.style.setProperty('--c', CATEGORY_COLOURS[cat] || CATEGORY_COLOURS.other);
|
||
head.textContent = catName(cat);
|
||
const count = document.createElement('span');
|
||
count.textContent = games.length;
|
||
head.append(count);
|
||
section.append(head);
|
||
}
|
||
const grid = document.createElement('div');
|
||
grid.className = 'grid';
|
||
games.forEach((g) => grid.append(gameCard(g)));
|
||
section.append(grid);
|
||
box.append(section);
|
||
}
|
||
$('#lib-hint').textContent = 'Keyboard, controllers and touch all work. Your saves are kept on Dezio for your account.';
|
||
}
|
||
|
||
async function refreshLibrary() {
|
||
const r = await api('library');
|
||
if (!r.ok) throw new Error('Couldn\'t load the game list.');
|
||
const data = await r.json();
|
||
app.games = data.games;
|
||
const keep = prefs.get('category', 'all');
|
||
app.category = keep === 'all' || app.games.some((g) => g.category === keep) ? keep : 'all';
|
||
// new games' names and covers are still being looked up: check again shortly
|
||
clearTimeout(app.pendingTimer);
|
||
if (data.pending && (app.pendingTries = (app.pendingTries || 0) + 1) <= 12) {
|
||
app.pendingTimer = setTimeout(async () => {
|
||
await refreshLibrary().catch(() => {});
|
||
if (!$('#library').hidden) renderLibrary();
|
||
}, 5000);
|
||
}
|
||
}
|
||
|
||
/* ---- playing --------------------------------------------------------------------------------------- */
|
||
async function startGame(game, { fresh = false } = {}) {
|
||
app.audio.unlock();
|
||
let resume = false;
|
||
if (!fresh && game.states[0]) {
|
||
resume = await ask(`Continue ${game.title} where you left off (${ago(game.states[0])})?`,
|
||
[['Start from the title screen', false], ['Continue ▶', true, true]]);
|
||
}
|
||
const boot = $('#boot');
|
||
boot.hidden = false;
|
||
$('#boot-text').classList.remove('error');
|
||
$('#boot-text').textContent = `Loading ${game.title}…`;
|
||
try {
|
||
const rom = await loadRom(game, (p) => { $('#boot-text').textContent = `Downloading ${game.title}… ${Math.round(p * 100)}%`; });
|
||
// binjgb's heap can't grow: every game gets a fresh instance (the next one is compiled ahead)
|
||
const module = await app.nextModule;
|
||
app.nextModule = window.Binjgb();
|
||
const emu = new Emulator(module, rom, app.audio.ctx.sampleRate);
|
||
const save = await api(`save/${game.id}`);
|
||
if (save.status === 200 && emu.hasRam) emu.setRam(new Uint8Array(await save.arrayBuffer()));
|
||
if (!game.cgb) emu.palette(prefs.get(`pal.${game.id}`, 0));
|
||
app.emu = emu;
|
||
app.game = game;
|
||
if (resume) await loadState(0);
|
||
app.emu.speed = 1;
|
||
setSpeed(1);
|
||
$('#game-title').textContent = game.title;
|
||
$('#library').hidden = true;
|
||
$('#player').hidden = false;
|
||
applyTouchMode();
|
||
screen.fit();
|
||
$('#screen').focus();
|
||
app.audio.reset();
|
||
presence(game);
|
||
clearInterval(app.autoTimer);
|
||
app.autoTimer = setInterval(() => saveState(0, { quiet: true }), AUTOSTATE_MS);
|
||
if (!prefs.get('seenHelp', false) && !$('#player').classList.contains('touch')) {
|
||
prefs.set('seenHelp', true);
|
||
toast('Click the screen if the keyboard doesn\'t react', 3500);
|
||
}
|
||
} catch (err) {
|
||
$('#boot-text').textContent = err.message || String(err);
|
||
$('#boot-text').classList.add('error');
|
||
setTimeout(() => { boot.hidden = true; }, 2500);
|
||
return;
|
||
}
|
||
boot.hidden = true;
|
||
}
|
||
|
||
async function quitGame({ save = true, keepRam = false } = {}) {
|
||
const emu = app.emu;
|
||
if (!emu) return showLibrary();
|
||
closeMenu();
|
||
clearInterval(app.autoTimer);
|
||
if (save) {
|
||
setStatus('saving…');
|
||
await saveState(0, { quiet: true });
|
||
}
|
||
if (!keepRam) { clearTimeout(ramTimer); await uploadRam(); }
|
||
input.clear();
|
||
app.emu = null;
|
||
emu.destroy();
|
||
await refreshLibrary().catch(() => {});
|
||
showLibrary();
|
||
}
|
||
|
||
/* ---- Discord ---------------------------------------------------------------------------------------- */
|
||
function presence(game) {
|
||
if (!app.sdk) return;
|
||
const activity = game
|
||
? { type: 0, details: `Playing ${game.title}`.slice(0, 128), state: game.cgb ? 'Game Boy Color' : 'Game Boy', timestamps: { start: Date.now() } }
|
||
: { type: 0, details: 'Picking a game', state: 'Dezio Game Boy' };
|
||
app.sdk.commands.setActivity({ activity }).catch(() => {});
|
||
}
|
||
|
||
async function signIn() {
|
||
const config = await (await fetch(`${BASE}/api/config`)).json();
|
||
const params = new URLSearchParams(location.search);
|
||
if (params.has('frame_id')) {
|
||
const sdk = new window.DiscordEmbedded.DiscordSDK(config.client_id);
|
||
await sdk.ready();
|
||
app.platform = sdk.platform;
|
||
const { code } = await sdk.commands.authorize({
|
||
client_id: config.client_id, response_type: 'code', state: '', prompt: 'none',
|
||
scope: ['identify', 'rpc.activities.write'],
|
||
});
|
||
const r = await fetch(`${BASE}/api/token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) });
|
||
const data = await r.json().catch(() => ({}));
|
||
if (!r.ok) throw new Error(data.error || 'Sign-in failed');
|
||
await sdk.commands.authenticate({ access_token: data.access_token });
|
||
app.sdk = sdk;
|
||
applyOrientation();
|
||
app.session = data.session;
|
||
app.user = data.user;
|
||
} else if (config.dev) {
|
||
const data = await (await fetch(`${BASE}/api/dev-session`, { method: 'POST' })).json();
|
||
app.session = data.session;
|
||
app.user = data.user;
|
||
} else {
|
||
// a normal browser: use the website's "Sign in with Discord"
|
||
const r = await fetch(`${BASE}/api/web-session`, { method: 'POST' });
|
||
const data = await r.json().catch(() => ({}));
|
||
if (r.status === 401 && data.login) {
|
||
$('#boot-text').textContent = 'Sign in with Discord to play — your saves are kept for your account.';
|
||
const link = document.createElement('a');
|
||
link.className = 'chip on signin';
|
||
link.href = data.login;
|
||
link.textContent = 'Sign in with Discord';
|
||
$('#boot').append(link);
|
||
throw Object.assign(new Error('signin'), { quiet: true });
|
||
}
|
||
if (!r.ok) throw new Error(data.error || 'Sign-in failed');
|
||
app.session = data.session;
|
||
app.user = data.user;
|
||
}
|
||
}
|
||
|
||
/* ---- start ---------------------------------------------------------------------------------------- */
|
||
async function main() {
|
||
screen.init();
|
||
input.bindKeyboard();
|
||
input.bindTouch();
|
||
bindMenu();
|
||
window.addEventListener('resize', () => { sizePad(); screen.fit(); });
|
||
document.addEventListener('pointerdown', () => app.audio?.unlock(), { capture: true });
|
||
document.addEventListener('visibilitychange', () => {
|
||
if (document.hidden && app.emu) { input.clear(); uploadRam({ keepalive: true }); saveState(0, { quiet: true }); }
|
||
});
|
||
window.addEventListener('pagehide', () => { if (app.emu) uploadRam({ keepalive: true }); });
|
||
try {
|
||
$('#boot-text').textContent = 'Signing in with Discord…';
|
||
app.nextModule = window.Binjgb();
|
||
await Promise.all([app.nextModule, signIn()]);
|
||
app.audio = new Sound();
|
||
$('#who').textContent = app.user ? `Playing as ${app.user.name}` : '';
|
||
$('#boot-text').textContent = 'Loading games…';
|
||
await refreshLibrary();
|
||
$('#boot').hidden = true;
|
||
showLibrary();
|
||
raf = requestAnimationFrame(loop);
|
||
} catch (err) {
|
||
if (err.quiet) return;
|
||
console.error(err);
|
||
$('#boot-text').textContent = err.message || String(err);
|
||
$('#boot-text').classList.add('error');
|
||
}
|
||
}
|
||
|
||
main();
|