zx81

Emulateur Sinclair ZX81 dans le navigateur : Z80, ROM Sinclair, tout en JavaScript
git clone https://git.schurger.org/zx81.git
Log | Files | Refs | README

app.js (12941B)


      1 // Interface de l'émulateur : boucle temps réel, écran, claviers (physique et à l'écran),
      2 // chargement/sauvegarde de .P, saisie automatique de LOAD "".
      3 import { ZX81, FRAME_T, CPU_HZ, KEYS, COLS, ROWS } from './zx81.js';
      4 
      5 const $ = (id) => document.getElementById(id);
      6 const canvas = $('screen');
      7 const ctx = canvas.getContext('2d', { alpha: false });
      8 const img = ctx.createImageData(COLS * 8, ROWS * 8);
      9 const status = $('status');
     10 
     11 const PAPER = [0xe4, 0xe4, 0xe0], INK = [0x10, 0x10, 0x10];
     12 const CURSORS = [0xb0, 0xb1, 0xab, 0xa8];   // K, L, F, G inversés
     13 
     14 let machine = null;
     15 let dirty = false, lastFrameAt = 0, noSignal = false;
     16 let paused = false, speed = 1;
     17 let lastTick = 0, fpsFrames = 0, fpsAt = 0, fps = 0;
     18 
     19 // ---------------------------------------------------------------- écran
     20 
     21 function draw() {
     22   const px = machine.pixels, d = img.data;
     23   for (let i = 0, o = 0; i < px.length; i++, o += 4) {
     24     const c = px[i] ? INK : PAPER;
     25     d[o] = c[0]; d[o + 1] = c[1]; d[o + 2] = c[2]; d[o + 3] = 255;
     26   }
     27   ctx.putImageData(img, 0, 0);
     28   noSignal = false;
     29 }
     30 
     31 // Mode FAST (ou machine plantée) : pas de signal vidéo, le téléviseur montre de la neige.
     32 function drawNoSignal() {
     33   const d = img.data;
     34   for (let o = 0; o < d.length; o += 4) {
     35     const v = 150 + ((Math.random() * 70) | 0);
     36     d[o] = d[o + 1] = d[o + 2] = v; d[o + 3] = 255;
     37   }
     38   ctx.putImageData(img, 0, 0);
     39   noSignal = true;
     40 }
     41 
     42 // ---------------------------------------------------------------- saisie automatique
     43 
     44 // File d'attente de touches « tapées » par la page (LOAD "" après un reset…).
     45 // Chaque entrée : { keys: [...], frames } ou { wait: () => bool, timeout }.
     46 const typist = {
     47   queue: [], current: null, left: 0, gap: 0, acc: 0,
     48   clear() { if (this.current?.keys) this.current.keys.forEach((k) => machine.keyUp(k)); this.queue = []; this.current = null; this.gap = 0; },
     49   type(seqs) { for (const keys of seqs) this.queue.push({ keys, frames: 3 }); },
     50   wait(fn, timeoutFrames = 1000) { this.queue.push({ wait: fn, timeout: timeoutFrames }); },
     51   tick(tstates) {
     52     this.acc += tstates;
     53     while (this.acc >= FRAME_T) { this.acc -= FRAME_T; this.step(); }
     54   },
     55   step() {
     56     const c = this.current;
     57     if (c) {
     58       if (c.wait) {
     59         if (c.wait() || --c.timeout <= 0) { this.current = null; this.gap = 2; }
     60         return;
     61       }
     62       if (--c.left <= 0) { c.keys.forEach((k) => machine.keyUp(k)); this.current = null; this.gap = 3; }
     63       return;
     64     }
     65     if (this.gap > 0) { this.gap--; return; }
     66     if (!this.queue.length) return;
     67     const n = this.queue.shift();
     68     this.current = n;
     69     if (n.keys) { n.keys.forEach((k) => machine.keyDown(k)); n.left = n.frames; }
     70   },
     71 };
     72 
     73 const cursorShown = () => CURSORS.some((c) => machine.screen.includes(c));
     74 
     75 // Réinitialise la machine et fait charger `bytes` par la ROM (LOAD "").
     76 function loadProgram(bytes, label) {
     77   typist.clear();
     78   machine.reset();
     79   machine.tape = bytes;
     80   typist.wait(cursorShown, 600);
     81   typist.type([['J'], ['SHIFT', 'P'], ['SHIFT', 'P'], ['NEWLINE']]);
     82   setStatus(`Démarrage puis LOAD "" de ${label} (${bytes.length} octets)…`);
     83 }
     84 
     85 // ---------------------------------------------------------------- boucle
     86 
     87 function loop(now) {
     88   if (!paused) {
     89     const dt = Math.min(now - (lastTick || now), 100);
     90     const t = Math.round(dt * (CPU_HZ / 1000) * speed);
     91     if (t > 0) { machine.run(t); typist.tick(t); }
     92   }
     93   lastTick = now;
     94   if (dirty) { draw(); dirty = false; }
     95   else if (!paused && now - lastFrameAt > 300 && (!noSignal || Math.random() < 0.3)) drawNoSignal();
     96   if (now - fpsAt > 1000) {
     97     fps = fpsFrames; fpsFrames = 0; fpsAt = now;
     98     updateStatus();
     99   }
    100   requestAnimationFrame(loop);
    101 }
    102 
    103 let statusMsg = '';
    104 function setStatus(m) { statusMsg = m; updateStatus(); }
    105 function updateStatus() {
    106   if (!machine) return;
    107   const cd = machine.ram[0x403b - 0x4000];
    108   const mode = (cd & 0x40) ? 'SLOW' : 'FAST';
    109   const base = paused ? 'En pause' : `${mode} · ${fps} trames/s · ${(CPU_HZ * speed / 1e6).toFixed(2)} MHz`;
    110   status.textContent = statusMsg ? `${base} — ${statusMsg}` : base;
    111 }
    112 
    113 // ---------------------------------------------------------------- clavier physique
    114 
    115 // Symboles obtenus avec SHIFT sur le ZX81 (table K-SHIFTED de la ROM).
    116 const SYMBOLS = {
    117   '"': ['SHIFT', 'P'], '£': ['SHIFT', 'SPACE'], '$': ['SHIFT', 'U'], ':': ['SHIFT', 'Z'], '?': ['SHIFT', 'C'],
    118   '(': ['SHIFT', 'I'], ')': ['SHIFT', 'O'], '>': ['SHIFT', 'M'], '<': ['SHIFT', 'N'], '=': ['SHIFT', 'L'],
    119   '+': ['SHIFT', 'K'], '-': ['SHIFT', 'J'], '*': ['SHIFT', 'B'], '/': ['SHIFT', 'V'], ';': ['SHIFT', 'X'],
    120   ',': ['SHIFT', '.'], '.': ['.'],
    121 };
    122 const SPECIAL = {
    123   Enter: ['NEWLINE'], NumpadEnter: ['NEWLINE'], Backspace: ['SHIFT', '0'], Delete: ['SHIFT', '0'],
    124   ArrowLeft: ['SHIFT', '5'], ArrowDown: ['SHIFT', '6'], ArrowUp: ['SHIFT', '7'], ArrowRight: ['SHIFT', '8'],
    125   Escape: ['SHIFT', 'SPACE'], Space: ['SPACE'], ShiftLeft: ['SHIFT'], ShiftRight: ['SHIFT'], Tab: ['SHIFT', 'NEWLINE'],
    126 };
    127 
    128 function mapKey(e) {
    129   if (SPECIAL[e.code]) return SPECIAL[e.code];
    130   const k = e.key;
    131   if (k.length === 1) {
    132     if (/[a-z]/i.test(k)) return [k.toUpperCase()];
    133     if (/[0-9]/.test(k)) return [k];
    134     if (SYMBOLS[k]) return SYMBOLS[k];
    135   }
    136   let m;
    137   if ((m = /^Key([A-Z])$/.exec(e.code))) return [m[1]];
    138   if ((m = /^(?:Digit|Numpad)([0-9])$/.exec(e.code))) return [m[1]];
    139   return null;
    140 }
    141 
    142 const held = new Map();     // e.code → touches ZX81 enfoncées
    143 
    144 function applyHeld() {
    145   machine.releaseAll();
    146   for (const keys of held.values()) keys.forEach((k) => machine.keyDown(k));
    147   for (const k of stickyKeys) machine.keyDown(k);
    148   refreshKeyboardHighlight();
    149 }
    150 
    151 window.addEventListener('keydown', (e) => {
    152   if (!machine || e.ctrlKey || e.metaKey || e.altKey) return;
    153   if (['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON'].includes(e.target.tagName) && e.code !== 'Escape') return;
    154   const keys = mapKey(e);
    155   if (!keys) return;
    156   e.preventDefault();
    157   if (e.repeat) return;
    158   held.set(e.code, keys);
    159   applyHeld();
    160 });
    161 window.addEventListener('keyup', (e) => {
    162   if (!machine) return;
    163   if (held.delete(e.code)) applyHeld();
    164 });
    165 window.addEventListener('blur', () => { held.clear(); if (machine) applyHeld(); });
    166 
    167 // ---------------------------------------------------------------- clavier à l'écran
    168 
    169 // Ordre des touches dans les tables de la ROM (K-UNSHIFTED à 0x007E).
    170 const TABLE_ORDER = ['Z', 'X', 'C', 'V', 'A', 'S', 'D', 'F', 'G', 'Q', 'W', 'E', 'R', 'T', '1', '2', '3', '4', '5',
    171   '0', '9', '8', '7', '6', 'P', 'O', 'I', 'U', 'Y', 'NEWLINE', 'L', 'K', 'J', 'H', 'SPACE', '.', 'M', 'N', 'B'];
    172 const LAYOUT = [
    173   ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],
    174   ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'],
    175   ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'NEWLINE'],
    176   ['SHIFT', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '.', 'SPACE'],
    177 ];
    178 const CHARSET = ' \0\0\0\0\0\0\0\0\0\0"£$:?()><=+-*/;,.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    179 const CONTROL = { 0x70: '↑', 0x71: '↓', 0x72: '←', 0x73: '→', 0x74: 'GRAPHICS', 0x75: 'EDIT', 0x76: 'NEWLINE', 0x77: 'RUBOUT', 0x78: '', 0x79: 'FUNCTION' };
    180 
    181 // Décode la table des mots-clés de la ROM (0x0111, dernier caractère de chaque mot inversé).
    182 function decodeTokens(rom) {
    183   const tokens = []; let cur = '';
    184   for (let a = 0x0112; tokens.length < 64; a++) {
    185     const b = rom[a];
    186     cur += CHARSET[b & 0x3f] ?? '?';
    187     if (b & 0x80) { tokens.push(cur); cur = ''; }
    188   }
    189   return tokens;   // tokens[i] = texte du code 0xC0 + i
    190 }
    191 
    192 function codeText(code, tokens) {
    193   if (code >= 0xc0) return tokens[code - 0xc0];
    194   if (code === 0x40) return 'RND';
    195   if (code === 0x41) return 'INKEY$';
    196   if (code === 0x42) return 'PI';
    197   if (code >= 0x70 && code <= 0x79) return CONTROL[code];
    198   if (code < 0x40) return CHARSET[code] === '\0' ? '▞' : CHARSET[code];
    199   return '';
    200 }
    201 
    202 const stickyKeys = new Set();   // SHIFT « collant » du clavier à l'écran
    203 const keyEls = new Map();
    204 
    205 function buildKeyboard(rom) {
    206   const tokens = decodeTokens(rom);
    207   const kb = $('keyboard');
    208   for (const row of LAYOUT) {
    209     for (const name of row) {
    210       const el = document.createElement('div');
    211       el.className = 'key';
    212       el.dataset.key = name;
    213       let kw = '', sh = '', fn = '', main = name, small = false;
    214       const idx = TABLE_ORDER.indexOf(name);
    215       if (idx >= 0) {
    216         const unsh = rom[0x007e + idx];
    217         if (unsh >= 0x26 && unsh <= 0x3f) kw = tokens[unsh + 0xc0 - 0xc0];   // mot-clé = lettre + 0xC0
    218         sh = codeText(rom[0x00a5 + idx], tokens);
    219         fn = codeText(rom[0x00cc + idx], tokens);
    220         if (name === 'NEWLINE' || name === 'SPACE') { main = name === 'SPACE' ? 'SPACE' : 'NEW LINE'; small = true; }
    221       } else { main = 'SHIFT'; small = true; }
    222       el.innerHTML = `<div class="top"><span class="kw">${kw}</span><span class="sh">${sh}</span></div>` +
    223         `<div class="main${small ? ' small' : ''}">${main}</div><div class="fn">${fn}</div>`;
    224       el.title = name === 'SHIFT' ? 'SHIFT (reste enfoncé jusqu’à la touche suivante)' : [kw && `K : ${kw}`, sh && `SHIFT : ${sh}`, fn && `FUNCTION : ${fn}`].filter(Boolean).join(' · ');
    225       kb.appendChild(el);
    226       keyEls.set(name, el);
    227 
    228       const press = (ev) => {
    229         ev.preventDefault();
    230         if (ev.button !== undefined && ev.button !== 0) return;
    231         canvas.focus({ preventScroll: true });
    232         if (name === 'SHIFT') {
    233           if (stickyKeys.has('SHIFT')) stickyKeys.delete('SHIFT'); else stickyKeys.add('SHIFT');
    234           applyHeld();
    235           return;
    236         }
    237         el.setPointerCapture?.(ev.pointerId);
    238         held.set('ui:' + name, stickyKeys.has('SHIFT') ? ['SHIFT', name] : [name]);
    239         applyHeld();
    240       };
    241       const release = () => {
    242         if (!held.has('ui:' + name)) return;
    243         held.delete('ui:' + name);
    244         stickyKeys.delete('SHIFT');
    245         applyHeld();
    246       };
    247       el.addEventListener('pointerdown', press);
    248       el.addEventListener('pointerup', release);
    249       el.addEventListener('pointercancel', release);
    250       el.addEventListener('lostpointercapture', release);
    251       el.addEventListener('contextmenu', (ev) => ev.preventDefault());
    252     }
    253   }
    254 }
    255 
    256 function refreshKeyboardHighlight() {
    257   const down = new Set();
    258   for (const keys of held.values()) keys.forEach((k) => down.add(k));
    259   for (const [name, el] of keyEls) {
    260     el.classList.toggle('down', down.has(name));
    261     el.classList.toggle('sticky', name === 'SHIFT' && stickyKeys.has('SHIFT'));
    262   }
    263 }
    264 
    265 // ---------------------------------------------------------------- boutons
    266 
    267 function download(bytes, name) {
    268   const a = document.createElement('a');
    269   a.href = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));
    270   a.download = name;
    271   a.click();
    272   setTimeout(() => URL.revokeObjectURL(a.href), 5000);
    273 }
    274 
    275 async function fetchBytes(url) {
    276   const r = await fetch(url, { cache: 'no-cache' });
    277   if (!r.ok) throw new Error(`${url} : HTTP ${r.status}`);
    278   return new Uint8Array(await r.arrayBuffer());
    279 }
    280 
    281 $('btn-demo').addEventListener('click', async () => loadProgram(await fetchBytes('programs/demo.p'), 'demo.p'));
    282 $('btn-load').addEventListener('click', () => $('file').click());
    283 $('file').addEventListener('change', async (e) => {
    284   const f = e.target.files[0];
    285   if (!f) return;
    286   loadProgram(new Uint8Array(await f.arrayBuffer()), f.name);
    287   e.target.value = '';
    288 });
    289 $('btn-save').addEventListener('click', () => {
    290   if (!cursorShown()) { setStatus('SAVE : il faut d’abord revenir au curseur (BREAK = Échap)'); return; }
    291   typist.clear();
    292   typist.type([['S'], ['SHIFT', 'P'], ['Z'], ['X'], ['8'], ['1'], ['SHIFT', 'P'], ['NEWLINE']]);   // SAVE "ZX81"
    293 });
    294 $('btn-reset').addEventListener('click', () => { typist.clear(); machine.reset(); setStatus('Réinitialisé'); });
    295 $('speed').addEventListener('change', (e) => { speed = Number(e.target.value); updateStatus(); });
    296 $('btn-pause').addEventListener('click', (e) => {
    297   paused = !paused;
    298   e.target.textContent = paused ? 'Reprendre' : 'Pause';
    299   e.target.classList.toggle('on', paused);
    300   updateStatus();
    301 });
    302 canvas.tabIndex = 0;
    303 
    304 // ---------------------------------------------------------------- démarrage
    305 
    306 (async () => {
    307   try {
    308     const rom = await fetchBytes('zx81.rom');
    309     machine = new ZX81(rom);
    310     window.zx81 = machine;   // pour les essais et la console
    311     machine.onFrame = () => { dirty = true; lastFrameAt = performance.now(); fpsFrames++; };
    312     machine.onSave = (bytes) => { download(bytes, 'zx81.p'); setStatus(`SAVE : ${bytes.length} octets téléchargés (zx81.p)`); };
    313     machine.onLoad = () => setStatus('Programme chargé');
    314     buildKeyboard(rom);
    315     setStatus('');
    316     requestAnimationFrame(loop);
    317     try { loadProgram(await fetchBytes('programs/demo.p'), 'demo.p'); }
    318     catch (err) { setStatus(`Démo indisponible : ${err.message}`); }
    319   } catch (err) {
    320     status.textContent = `Impossible de démarrer : ${err.message}`;
    321   }
    322 })();