-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathmiracle.js
More file actions
334 lines (294 loc) · 9.08 KB
/
miracle.js
File metadata and controls
334 lines (294 loc) · 9.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import { SoundChip } from "./soundchip";
import { sms } from "./sms";
import { showDebug, debugKeyPress } from "./debug";
export { sms };
let breakpointHit = false;
let running = false;
export let canvas;
let ctx;
let imageData;
let fb8;
export let fb32;
let soundChip;
const framesPerSecond = 50;
const scanLinesPerFrame = 313; // 313 lines in PAL TODO: unify all this
const scanLinesPerSecond = scanLinesPerFrame * framesPerSecond;
const cpuHz = 3.58 * 1000 * 1000; // According to Sega docs.
const tstatesPerHblank = Math.ceil(cpuHz / scanLinesPerSecond) | 0;
export function clearBreakpoint() {
breakpointHit = false;
}
export function cycleCallback(tstates) {
soundChip.polltime(tstates);
}
function line() {
sms.z80.eventNextEvent = tstatesPerHblank;
sms.z80.tstates -= tstatesPerHblank;
sms.z80_do_opcodes(cycleCallback);
const vdp_status = sms.vdp.hblank();
sms.z80.setIrq(!!(vdp_status & 3));
if (breakpointHit) {
running = false;
showDebug(sms.z80.pc);
} else if (vdp_status & 4) {
paintScreen();
}
}
export function start() {
breakpointHit = false;
if (running) return;
running = true;
document.getElementById("menu").className = "running";
audio_enable(true);
document.getElementById("debug").style.display = "none";
run();
}
const targetTimeout = 1000 / framesPerSecond;
let adjustedTimeout = targetTimeout;
let lastFrame = null;
function run() {
if (!running) {
showDebug(sms.z80.pc);
return;
}
const now = Date.now();
if (lastFrame) {
// Try and tweak the timeout to achieve target frame rate.
const timeSinceLast = now - lastFrame;
if (timeSinceLast < 2 * targetTimeout) {
// Ignore huge delays (e.g. trips in and out of the debugger)
const diff = timeSinceLast - targetTimeout;
adjustedTimeout -= 0.1 * diff;
// Clamp to a sane range so adjustedTimeout can't drift negative (causing
// run() to fire as fast as possible) or become uselessly large.
adjustedTimeout = Math.max(
1,
Math.min(targetTimeout * 2, adjustedTimeout),
);
}
}
lastFrame = now;
setTimeout(run, adjustedTimeout);
try {
for (let i = 0; i < scanLinesPerFrame && running; i++) line();
} catch (e) {
running = false;
audio_enable(true);
throw e;
}
if (running) audio_push_frame();
}
export function stop() {
running = false;
audio_enable(false);
}
let audioContext = null;
let _audioNode = null;
let _samplesPerFrame = 0;
function _showAudioBanner(msg) {
const banner = document.getElementById("audio-warning");
if (banner) {
banner.textContent = msg;
banner.style.display = "block";
}
}
function _hideAudioBanner() {
const banner = document.getElementById("audio-warning");
if (banner) banner.style.display = "none";
}
function _checkAudioStatus() {
if (!audioContext) return;
if (audioContext.state === "suspended") {
_showAudioBanner("🔈 Audio suspended — click here to enable sound");
} else if (audioContext.state === "running") {
_hideAudioBanner();
}
}
function audio_init() {
const AudioCtx =
typeof AudioContext !== "undefined"
? AudioContext
: typeof webkitAudioContext !== "undefined"
? webkitAudioContext
: null;
if (!AudioCtx) {
// No Web Audio API at all.
soundChip = new SoundChip(10000, cpuHz);
return;
}
audioContext = new AudioCtx();
// Create soundChip immediately so audio_reset() works synchronously.
soundChip = new SoundChip(audioContext.sampleRate, cpuHz);
// Use floor so we never request more samples than the soundchip has actually
// advanced (ceil would synthesise a phantom extra sample on non-integer rates
// and cause long-term pitch drift). A fractional accumulator would be ideal
// for exact rate matching but floor is safe and correct in practice.
_samplesPerFrame = Math.floor(audioContext.sampleRate / framesPerSecond);
if (!audioContext.audioWorklet) {
// AudioWorklet unavailable (non-secure context, old browser, etc.)
console.log("AudioWorklet not available — no audio");
_showAudioBanner(
"⚠️ Audio unavailable — serve over https or use localhost",
);
audioContext.close();
audioContext = null;
_samplesPerFrame = 0; // Prevent audio_push_frame() doing work with no output
return;
}
audioContext.onstatechange = () => _checkAudioStatus();
_checkAudioStatus();
// Async worklet setup; soundChip is already usable above.
audioContext.audioWorklet
.addModule("/audio-processor.js")
.then(() => {
_audioNode = new AudioWorkletNode(
audioContext,
"miracle-audio-processor",
{
numberOfOutputs: 1,
outputChannelCount: [1],
processorOptions: { samplesPerFrame: _samplesPerFrame },
},
);
_audioNode.connect(audioContext.destination);
})
.catch((err) => {
console.warn("Failed to load audio worklet:", err);
_showAudioBanner("⚠️ Audio failed to load — see console for details");
if (audioContext) audioContext.close();
audioContext = null;
_audioNode = null;
_samplesPerFrame = 0; // Prevent audio_push_frame() doing work with no output
});
}
function audio_push_frame() {
if (!_samplesPerFrame) return;
const buf = new Float32Array(_samplesPerFrame);
// Always drain the soundchip's internal buffer every frame, regardless of
// whether the worklet is ready yet. Skipping render() allows pending cycles
// to accumulate and overflow the soundchip's internal cap, causing desynced
// audio once the worklet eventually initialises.
soundChip.render(buf, 0, buf.length);
// Only push to the worklet while the context is actually running and the
// node is ready. While suspended or still initialising we drain (above) but
// discard the samples — otherwise they'd queue up and cause latency on resume.
if (_audioNode && audioContext && audioContext.state === "running") {
// Transfer the underlying ArrayBuffer to avoid a copy.
_audioNode.port.postMessage({ buffer: buf }, [buf.buffer]);
}
}
export function audio_enable(enable) {
soundChip.enable(enable);
// Only resume the AudioContext when actually enabling audio; calling
// resume() while disabling would wrongly hide the suspended banner.
if (enable && audioContext) audioContext.resume();
}
export function miracle_init() {
canvas = document.getElementById("screen");
ctx = canvas.getContext("2d");
if (ctx.getImageData) {
imageData = ctx.getImageData(0, 0, 256, 192);
fb8 = imageData.data;
fb32 = new Uint32Array(fb8.buffer);
} else {
alert("Unsupported browser...");
// Unsupported....
}
audio_init();
sms.init(canvas, fb32, paintScreen, breakpoint, soundChip);
miracle_reset();
// Scale the canvas to fill its container while maintaining the native aspect ratio.
// ResizeObserver fires whenever the container's size changes (initial layout,
// window resize, panel show/hide, etc.) — more reliable than a one-shot setTimeout.
function resizeCanvas() {
const border = parseInt(window.getComputedStyle(canvas).borderWidth) || 0;
const container = canvas.parentElement;
const scale = Math.min(
(container.clientWidth - border * 2) / canvas.width,
(container.clientHeight - border * 2) / canvas.height,
);
if (scale > 0) {
canvas.style.width = `${Math.floor(canvas.width * scale)}px`;
canvas.style.height = `${Math.floor(canvas.height * scale)}px`;
}
}
new ResizeObserver(resizeCanvas).observe(canvas.parentElement);
resizeCanvas();
document.onkeydown = keyDown;
document.onkeyup = keyUp;
document.onkeypress = keyPress;
const audioBanner = document.getElementById("audio-warning");
if (audioBanner) {
audioBanner.addEventListener("click", () => {
if (audioContext) audioContext.resume();
});
}
}
export function miracle_reset() {
sms.reset();
}
const keys = {
87: 1, // W = JP1 up
83: 2, // S = JP1 down
65: 4, // A = JP1 left
68: 8, // D = JP1 right
32: 16, // Space = JP1 fire 1
13: 32, // Enter = JP1 fire 2
38: 1, // Arrow keys
40: 2,
37: 4,
39: 8,
90: 16, // Z/Y and X for fire
89: 16,
88: 32,
82: 1 << 12, // R for reset button
};
function keyCode(evt) {
return evt.which || evt.charCode || evt.keyCode;
}
function keyDown(evt) {
if (!running) return;
const key = keys[keyCode(evt)];
if (key) {
sms.bus.joystick &= ~key;
if (!evt.metaKey) {
evt.preventDefault();
return;
}
}
switch (evt.keyCode) {
case 80: // 'P' for pause
sms.z80.nmi();
break;
case 8: // 'Backspace' is debug
breakpoint();
evt.preventDefault();
break;
}
}
function keyUp(evt) {
if (!running) return;
const key = keys[keyCode(evt)];
if (key) {
sms.bus.joystick |= key;
if (!evt.metaKey) {
evt.preventDefault();
}
}
}
function keyPress(evt) {
if (!running) {
return debugKeyPress(keyCode(evt));
}
if (!evt.metaKey) {
evt.preventDefault();
}
}
export function paintScreen() {
ctx.putImageData(imageData, 0, 0);
}
export function breakpoint() {
sms.z80.eventNextEvent = 0;
breakpointHit = true;
audio_enable(false);
}