c64-ready 2.5.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +32 -0
  2. package/bin/admin.mjs +7 -1
  3. package/bin/headless.mjs +1 -1
  4. package/dist/assets/BeachHead-CuSwFD4k.js +1 -0
  5. package/dist/assets/ChuckieEgg-CPqBnAOF.js +1 -0
  6. package/dist/assets/ForbiddenForest-DsQ9jsc8.js +1 -0
  7. package/dist/assets/Galaga-Cutc3p9s.js +1 -0
  8. package/dist/assets/Gribbly-DdZ_hHFt.js +1 -0
  9. package/dist/assets/Hercules-vZYKm7GG.js +1 -0
  10. package/dist/assets/LegendOfWilf-CxSMOjsj.js +1 -0
  11. package/dist/assets/MariosCementFactory-z0IZ0q30.js +1 -0
  12. package/dist/assets/MoleAttack-buC6ChYy.js +1 -0
  13. package/dist/assets/MunchyWorm-D2Zv7i0Q.js +1 -0
  14. package/dist/assets/ParkPatrol-CVj7hyoB.js +1 -0
  15. package/dist/assets/PottyPigeon-0SYpIUBa.js +1 -0
  16. package/dist/assets/RainbowIslands-BjfmJB8z.js +1 -0
  17. package/dist/assets/Stix-BU-qUCeC.js +1 -0
  18. package/dist/assets/Tilt-C5KtKisF.js +1 -0
  19. package/dist/assets/UpNDown-CATRO7Mz.js +1 -0
  20. package/dist/assets/Uridium-DanS2KoH.js +1 -0
  21. package/dist/assets/VegetablesDeluxe-C41ViimS.js +1 -0
  22. package/dist/assets/index-B8DSjPqI.js +243 -0
  23. package/dist/assets/src-DX0rJQsE.js +1 -0
  24. package/dist/assets/src-_trgwTvp.js +2 -0
  25. package/dist/assets/string-utils-CMVABfx0.js +1 -0
  26. package/dist/index.html +1 -1
  27. package/dist-ts/emulator/c64-emulator.d.ts +2 -2
  28. package/dist-ts/emulator/c64-emulator.js +2 -2
  29. package/dist-ts/emulator/c64-keys.d.ts +69 -0
  30. package/dist-ts/emulator/c64-keys.d.ts.map +1 -0
  31. package/dist-ts/emulator/c64-keys.js +69 -0
  32. package/dist-ts/emulator/c64-keys.js.map +1 -0
  33. package/dist-ts/emulator/c64-wasm.d.ts +1 -1
  34. package/dist-ts/emulator/gamepad-mapping.d.ts +64 -0
  35. package/dist-ts/emulator/gamepad-mapping.d.ts.map +1 -0
  36. package/dist-ts/emulator/gamepad-mapping.js +154 -0
  37. package/dist-ts/emulator/gamepad-mapping.js.map +1 -0
  38. package/dist-ts/emulator/input.d.ts +27 -78
  39. package/dist-ts/emulator/input.d.ts.map +1 -1
  40. package/dist-ts/emulator/input.js +94 -215
  41. package/dist-ts/emulator/input.js.map +1 -1
  42. package/dist-ts/headless/audio-capture.d.ts +1 -1
  43. package/dist-ts/headless/c64-headless.d.ts +2 -2
  44. package/dist-ts/headless/c64-headless.js +4 -4
  45. package/dist-ts/headless/frame-capture.d.ts +1 -1
  46. package/dist-ts/headless/input-bridge.d.ts +1 -1
  47. package/dist-ts/player/c64-player.d.ts +21 -5
  48. package/dist-ts/player/c64-player.d.ts.map +1 -1
  49. package/dist-ts/player/c64-player.js +32 -5
  50. package/dist-ts/player/c64-player.js.map +1 -1
  51. package/dist-ts/player/canvas-renderer.d.ts +2 -2
  52. package/dist-ts/player/cheevos-dev.d.ts +65 -0
  53. package/dist-ts/player/cheevos-dev.d.ts.map +1 -0
  54. package/dist-ts/player/cheevos-dev.js +237 -0
  55. package/dist-ts/player/cheevos-dev.js.map +1 -0
  56. package/dist-ts/player/cheevos-tracker-panel.d.ts +21 -0
  57. package/dist-ts/player/cheevos-tracker-panel.d.ts.map +1 -0
  58. package/dist-ts/player/cheevos-tracker-panel.js +242 -0
  59. package/dist-ts/player/cheevos-tracker-panel.js.map +1 -0
  60. package/dist-ts/player/index.d.ts +10 -7
  61. package/dist-ts/player/index.d.ts.map +1 -1
  62. package/dist-ts/player/index.js +6 -4
  63. package/dist-ts/player/index.js.map +1 -1
  64. package/dist-ts/player/input-handler.d.ts +7 -3
  65. package/dist-ts/player/input-handler.d.ts.map +1 -1
  66. package/dist-ts/player/input-handler.js +24 -1
  67. package/dist-ts/player/input-handler.js.map +1 -1
  68. package/dist-ts/player/load-formats.d.ts +1 -1
  69. package/dist-ts/player/local-rom-store.d.ts +23 -0
  70. package/dist-ts/player/local-rom-store.d.ts.map +1 -0
  71. package/dist-ts/player/local-rom-store.js +87 -0
  72. package/dist-ts/player/local-rom-store.js.map +1 -0
  73. package/dist-ts/player/startup-params.d.ts +7 -0
  74. package/dist-ts/player/startup-params.d.ts.map +1 -0
  75. package/dist-ts/player/startup-params.js +47 -0
  76. package/dist-ts/player/startup-params.js.map +1 -0
  77. package/dist-ts/player/ui-controller.d.ts +23 -1
  78. package/dist-ts/player/ui-controller.d.ts.map +1 -1
  79. package/dist-ts/player/ui-controller.js +665 -1
  80. package/dist-ts/player/ui-controller.js.map +1 -1
  81. package/package.json +2 -1
  82. package/src/emulator/c64-keys.ts +68 -0
  83. package/src/emulator/gamepad-mapping.ts +212 -0
  84. package/src/emulator/input.ts +106 -209
  85. package/src/headless/headless-cli.mjs +10 -4
  86. package/src/headless/input-server.mjs +92 -17
  87. package/src/headless/webrtc-server.mjs +344 -22
  88. package/src/main.ts +177 -12
  89. package/src/player/c64-player.ts +36 -0
  90. package/src/player/cheevos-dev.ts +340 -0
  91. package/src/player/cheevos-tracker-panel.ts +309 -0
  92. package/src/player/index.ts +19 -0
  93. package/src/player/input-handler.ts +32 -0
  94. package/src/player/local-rom-store.ts +126 -0
  95. package/src/player/startup-params.ts +40 -0
  96. package/src/player/ui-controller.ts +740 -0
  97. package/src/types/c64-cheevos.d.ts +6 -0
  98. package/dist/assets/index-BAsZcXuS.js +0 -178
  99. /package/dist/assets/{marked.esm--kBm026b.js → marked.esm-fTuuvbcB.js} +0 -0
  100. /package/dist/assets/{purify.es-BcoGFDcJ.js → purify.es-CRM-GE0Y.js} +0 -0
@@ -6,7 +6,10 @@ const css = `
6
6
  .c64-settings-tabs{display:flex;gap:8px;flex-wrap:wrap;margin:0 0 18px;padding:0;border:0;background:transparent}.c64-settings-tab{background:#2a2a3e;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:12px;padding:4px 10px;cursor:pointer}.c64-settings-tab.active{background:#3a335f;border-color:#7b71d5;color:#fff}
7
7
  .c64-section-label{display:block;margin:0 0 8px;color:#7b71d5;font-size:13px;letter-spacing:1px;text-transform:uppercase}.c64-form-row,.c64-radio-row,.c64-system-actions,.c64-menu-actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:0 0 12px}.c64-form-row label{color:#aaa;font-size:13px}
8
8
  .c64-select,.c64-file-input{background:#111827;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:13px;padding:5px 8px}.c64-btn{background:#2a2a3e;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:12px;padding:5px 10px;cursor:pointer}.c64-btn:hover:not(:disabled){border-color:#7b71d5;color:#fff}.c64-btn:disabled,.c64-select:disabled{opacity:.55;cursor:not-allowed}
9
+ .c64-btn.active{background:#3a335f;border-color:#7b71d5;color:#fff}
9
10
  .c64-dragarea{border:1px dashed #555;border-radius:6px;background:#111827;color:#aaa;padding:18px;margin:0 0 12px;text-align:center}.c64-dragarea.dragover{border-color:#7b71d5;background:#1f1b38;color:#fff}.c64-cart-preview,.c64-tools-section{background:#151527;border:1px solid #2a2a3e;border-radius:6px;padding:12px;margin:12px 0}.c64-section-hint{color:#888;font-size:12px;line-height:1.4;margin:4px 0 12px}.c64-checkbox-row{display:flex;align-items:center;gap:8px;color:#ccc;font-size:13px;margin:14px 0 4px}
11
+ .c64-text-input,.c64-textarea{background:#111827;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:13px;padding:5px 8px}.c64-text-input{min-width:180px}.c64-textarea{box-sizing:border-box;width:100%;min-height:120px;resize:vertical}.c64-cheevos-json-file{display:none}.c64-inline-status{color:#888;font-size:12px}
12
+ .c64-cheat-list{display:grid;gap:12px;margin:0 0 12px}.c64-cheat-card{background:#151527;border:1px solid #2a2a3e;border-radius:6px;padding:12px}.c64-cheat-card-header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 10px;color:#ddd;font-size:13px}.c64-cheat-remove{background:none;border:0;color:#ff9a9a;cursor:pointer;font:inherit;font-size:12px}.c64-cheat-grid{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:8px 10px;align-items:center}.c64-cheat-input{background:#111827;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:13px;min-width:0;padding:5px 8px}.c64-cheat-error{color:#ff9a9a;font-size:12px;margin:8px 0 0}.c64-cheat-status{color:#aaa;font-size:12px;line-height:1.4;margin:8px 0 0}.c64-cheat-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}@media (max-width:600px){.c64-cheat-grid{grid-template-columns:1fr}.c64-cheat-grid label{margin-top:4px}}
10
13
  `;
11
14
  function resolveAssetUrl(baseUrl, path) {
12
15
  const base = baseUrl ?? '/';
@@ -35,18 +38,163 @@ const SPECIAL_KEYS = [
35
38
  ['Comma / Period', ', . < >'],
36
39
  ['C64 function keys', 'F1-F8'],
37
40
  ];
38
- import { LOAD_FORMAT_OPTIONS, getAcceptForLoadTypeSelection, getLoadTypeLabel, inferLoadTypeFromFilename, resolveLoadTypeSelection, } from './load-formats';
41
+ import { chooseAndStoreCheevosRom, storeCheevosRomFile } from './local-rom-store.js';
42
+ import { toViteFsUrl } from './startup-params.js';
43
+ import { LOAD_FORMAT_OPTIONS, getAcceptForLoadTypeSelection, getLoadTypeLabel, inferLoadTypeFromFilename, isSupportedLoadType, resolveLoadTypeSelection, } from './load-formats.js';
39
44
  const CRT_PRELOAD_CHECKS_STORAGE_KEY = 'c64-disable-crt-preload-checks';
45
+ const CHEEVOS_DETECTOR_STORAGE_KEY = 'c64-cheevos-dev-detector';
46
+ const CHEEVOS_JSON_PATH_STORAGE_KEY = 'c64-cheevos-dev-json-path';
47
+ const CHEEVOS_TRACKER_VISIBLE_STORAGE_KEY = 'c64-cheevos-tracker-visible';
48
+ const CHEAT_CONFIG_STORAGE_KEY = 'c64cade.cheatMode.v1';
49
+ const CHEAT_NOTICE_MS = 1800;
50
+ const CHEAT_ACTIONS = [
51
+ { value: 'increment', label: 'Increment' },
52
+ { value: 'decrement', label: 'Decrement' },
53
+ { value: 'set', label: 'Set' },
54
+ ];
40
55
  function formatSnapshotFilename(now = new Date()) {
41
56
  const pad = (value) => String(value).padStart(2, '0');
42
57
  return `snapshot-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.c64`;
43
58
  }
59
+ function createCheatRow(overrides = {}) {
60
+ return {
61
+ id: overrides.id ?? `cheat-${Date.now()}-${Math.random().toString(36).slice(2)}`,
62
+ address: typeof overrides.address === 'string' ? overrides.address : '0x004e',
63
+ action: CHEAT_ACTIONS.some((action) => action.value === overrides.action)
64
+ ? overrides.action
65
+ : 'increment',
66
+ setValue: typeof overrides.setValue === 'string' ? overrides.setValue : '0xff',
67
+ keyBinding: normaliseCheatKeyBinding(overrides.keyBinding),
68
+ };
69
+ }
70
+ function normaliseCheatRow(value) {
71
+ if (!value || typeof value !== 'object')
72
+ return null;
73
+ return createCheatRow(value);
74
+ }
75
+ function isCheatRow(row) {
76
+ return !!row;
77
+ }
78
+ function loadCheatConfig() {
79
+ const fallback = [createCheatRow()];
80
+ try {
81
+ const raw = localStorage.getItem(CHEAT_CONFIG_STORAGE_KEY);
82
+ const parsed = raw ? JSON.parse(raw) : null;
83
+ const rows = Array.isArray(parsed?.cheats)
84
+ ? parsed.cheats.map(normaliseCheatRow).filter(isCheatRow)
85
+ : [normaliseCheatRow(parsed)].filter(isCheatRow);
86
+ return rows.length ? rows : fallback;
87
+ }
88
+ catch (error) {
89
+ console.warn('Failed to load cheat config:', error);
90
+ return fallback;
91
+ }
92
+ }
93
+ function getNextCheatId(rows) {
94
+ return rows.reduce((nextId, cheat) => {
95
+ const match = String(cheat.id).match(/^cheat-(\d+)$/);
96
+ return match ? Math.max(nextId, Number(match[1]) + 1) : nextId;
97
+ }, 1);
98
+ }
99
+ function parseC64Address(value) {
100
+ const raw = value.trim().toLowerCase();
101
+ if (!raw)
102
+ return null;
103
+ const hex = raw.startsWith('0x') ? raw.slice(2) : raw.startsWith('$') ? raw.slice(1) : raw;
104
+ if (!/^[0-9a-f]{1,4}$/.test(hex))
105
+ return null;
106
+ const address = Number.parseInt(hex, 16);
107
+ return Number.isInteger(address) && address >= 0 && address <= 0xffff ? address : null;
108
+ }
109
+ function parseCheatByte(value) {
110
+ const raw = value.trim().toLowerCase();
111
+ if (!raw)
112
+ return null;
113
+ const hex = raw.startsWith('0x') ? raw.slice(2) : raw.startsWith('$') ? raw.slice(1) : raw;
114
+ if (!/^[0-9a-f]{1,2}$/.test(hex))
115
+ return null;
116
+ const byte = Number.parseInt(hex, 16);
117
+ return Number.isInteger(byte) && byte >= 0 && byte <= 0xff ? byte : null;
118
+ }
119
+ function formatHexByte(value) {
120
+ return `0x${(value & 0xff).toString(16).padStart(2, '0')}`;
121
+ }
122
+ function formatHexAddress(value) {
123
+ return `0x${(value & 0xffff).toString(16).padStart(4, '0')}`;
124
+ }
125
+ function normaliseCheatKeyBinding(binding) {
126
+ if (!binding || typeof binding !== 'object' || !('code' in binding))
127
+ return null;
128
+ const value = binding;
129
+ if (!value.code)
130
+ return null;
131
+ return {
132
+ code: String(value.code),
133
+ key: String(value.key || value.code),
134
+ label: String(value.label || labelForKey(value.key, value.code)),
135
+ };
136
+ }
137
+ function keyBindingFromEvent(event) {
138
+ return {
139
+ code: event.code || event.key,
140
+ key: event.key,
141
+ label: labelForKey(event.key, event.code),
142
+ };
143
+ }
144
+ function labelForKey(key, code) {
145
+ if (code === 'ControlLeft')
146
+ return 'Left Ctrl';
147
+ if (code === 'ControlRight')
148
+ return 'Right Ctrl';
149
+ if (key === ' ')
150
+ return 'Space';
151
+ if (key?.startsWith('Arrow'))
152
+ return key.replace('Arrow', 'Arrow ');
153
+ if (/^Key[A-Z]$/.test(code || ''))
154
+ return (code || '').slice(3);
155
+ if (/^Digit[0-9]$/.test(code || ''))
156
+ return (code || '').slice(5);
157
+ return key || code || '';
158
+ }
159
+ function isEditableKeyTarget(target) {
160
+ const element = target;
161
+ const tagName = element?.tagName?.toLowerCase();
162
+ return (tagName === 'input' ||
163
+ tagName === 'select' ||
164
+ tagName === 'textarea' ||
165
+ !!element?.isContentEditable);
166
+ }
167
+ function formatRamDumpFilename(now = new Date()) {
168
+ const stamp = now
169
+ .toISOString()
170
+ .replace(/[-:]/g, '')
171
+ .replace(/\.\d{3}z$/i, 'z');
172
+ return `c64-ready-${stamp}-ram.bin`;
173
+ }
44
174
  export default class UIController {
175
+ static activeController = null;
45
176
  helpOverlay = null;
46
177
  settingsOverlay = null;
47
178
  fileInput = null;
48
179
  player = null;
49
180
  options;
181
+ cheats = loadCheatConfig();
182
+ recordingCheatId = null;
183
+ nextCheatId = getNextCheatId(this.cheats);
184
+ cheatStatus = '';
185
+ cheatNoticeTimer = null;
186
+ handleCheatKeyDown = (event) => {
187
+ if (UIController.activeController !== this)
188
+ return;
189
+ if (this.recordingCheatId || event.repeat || isEditableKeyTarget(event.target))
190
+ return;
191
+ const cheat = this.cheats.find((entry) => this.matchesCheatKey(event, entry));
192
+ if (!cheat)
193
+ return;
194
+ event.preventDefault();
195
+ event.stopPropagation();
196
+ this.applyCheatAction(cheat);
197
+ };
50
198
  // Save previous overflow styles so we can restore them when exiting full/stretch
51
199
  savedHtmlOverflow = null;
52
200
  savedBodyOverflow = null;
@@ -72,6 +220,7 @@ export default class UIController {
72
220
  this.options = options;
73
221
  }
74
222
  init(player) {
223
+ UIController.activeController = this;
75
224
  this.player = player ?? null;
76
225
  this.syncConnectedGamepads();
77
226
  this.injectCSS();
@@ -80,6 +229,7 @@ export default class UIController {
80
229
  this.createHamburger();
81
230
  this.createMenu();
82
231
  this.createUnmuteButton();
232
+ window.addEventListener('keydown', this.handleCheatKeyDown, true);
83
233
  window.addEventListener('c64-controller-connected', this.handleControllerConnected);
84
234
  window.addEventListener('c64-controller-disconnected', this.handleControllerDisconnected);
85
235
  }
@@ -140,6 +290,317 @@ export default class UIController {
140
290
  link.remove();
141
291
  URL.revokeObjectURL(url);
142
292
  }
293
+ downloadBytes(filename, bytes) {
294
+ const copy = new Uint8Array(bytes.byteLength);
295
+ copy.set(bytes);
296
+ const blob = new Blob([copy], { type: 'application/octet-stream' });
297
+ const url = URL.createObjectURL(blob);
298
+ const link = document.createElement('a');
299
+ link.href = url;
300
+ link.download = filename;
301
+ document.body.appendChild(link);
302
+ link.click();
303
+ link.remove();
304
+ URL.revokeObjectURL(url);
305
+ }
306
+ promptForCheevosJsonUrl(file, detectorInput, status) {
307
+ const fileWithPath = file;
308
+ const inferredPath = fileWithPath.path || fileWithPath.webkitRelativePath || '';
309
+ if (inferredPath) {
310
+ this.updateCheevosJsonUrl(inferredPath, file.name, detectorInput, status);
311
+ return;
312
+ }
313
+ const previousPath = localStorage.getItem(CHEEVOS_JSON_PATH_STORAGE_KEY) ?? '';
314
+ const path = window.prompt('Optional: enter the absolute path to this cheevos JSON to update the URL for refresh.', previousPath);
315
+ if (!path?.trim())
316
+ return;
317
+ this.updateCheevosJsonUrl(path, file.name, detectorInput, status);
318
+ }
319
+ updateCheevosJsonUrl(path, filename, detectorInput, status) {
320
+ const cheevosSet = toViteFsUrl(path, this.options.assetBaseUrl ?? '/');
321
+ if (!cheevosSet)
322
+ return;
323
+ localStorage.setItem(CHEEVOS_JSON_PATH_STORAGE_KEY, path.trim());
324
+ const searchParams = new URLSearchParams(window.location.search);
325
+ const detectorId = detectorInput?.value.trim() ?? '';
326
+ if (detectorId)
327
+ searchParams.set('cheevos', detectorId);
328
+ searchParams.set('cheevosSet', cheevosSet);
329
+ if (!searchParams.has('game'))
330
+ searchParams.delete('game');
331
+ const search = searchParams.toString();
332
+ window.history.replaceState(null, '', `${window.location.pathname}${search ? `?${search}` : ''}${window.location.hash}`);
333
+ status.textContent = `Loaded JSON from ${filename}; updated URL cheevosSet=${cheevosSet}`;
334
+ }
335
+ saveCheatConfig() {
336
+ localStorage.setItem(CHEAT_CONFIG_STORAGE_KEY, JSON.stringify({
337
+ cheats: this.cheats.map((cheat) => ({
338
+ id: cheat.id,
339
+ address: cheat.address,
340
+ action: cheat.action,
341
+ setValue: cheat.setValue,
342
+ keyBinding: cheat.keyBinding,
343
+ })),
344
+ }));
345
+ }
346
+ getCheatAddressError(cheat) {
347
+ if (!cheat.address.trim())
348
+ return 'Enter a C64 memory address.';
349
+ if (parseC64Address(cheat.address) === null)
350
+ return 'Use a valid address from 0x0000 to 0xffff.';
351
+ return '';
352
+ }
353
+ getCheatSetValueError(cheat) {
354
+ if (cheat.action !== 'set')
355
+ return '';
356
+ if (!cheat.setValue.trim())
357
+ return 'Enter a byte value to set.';
358
+ if (parseCheatByte(cheat.setValue) === null)
359
+ return 'Use a valid byte value from 0x00 to 0xff.';
360
+ return '';
361
+ }
362
+ isCheatReady(cheat) {
363
+ return (!this.getCheatAddressError(cheat) &&
364
+ !this.getCheatSetValueError(cheat) &&
365
+ !!cheat.keyBinding?.code);
366
+ }
367
+ matchesCheatKey(event, cheat) {
368
+ const binding = cheat.keyBinding;
369
+ if (!binding?.code || !this.isCheatReady(cheat))
370
+ return false;
371
+ if (event.code === binding.code)
372
+ return true;
373
+ return !!binding.key && event.key?.toLowerCase() === binding.key.toLowerCase();
374
+ }
375
+ setCheatStatus(message) {
376
+ this.cheatStatus = message;
377
+ const status = document.getElementById('c64-cheat-status');
378
+ if (status) {
379
+ status.textContent = message;
380
+ status.hidden = !message;
381
+ }
382
+ if (this.cheatNoticeTimer !== null)
383
+ window.clearTimeout(this.cheatNoticeTimer);
384
+ this.cheatNoticeTimer = window.setTimeout(() => {
385
+ this.cheatNoticeTimer = null;
386
+ }, CHEAT_NOTICE_MS);
387
+ }
388
+ applyCheatAction(cheat) {
389
+ const address = parseC64Address(cheat.address);
390
+ if (address === null) {
391
+ this.setCheatStatus(this.getCheatAddressError(cheat));
392
+ return;
393
+ }
394
+ const setValue = cheat.action === 'set' ? parseCheatByte(cheat.setValue) : null;
395
+ if (cheat.action === 'set' && setValue === null) {
396
+ this.setCheatStatus(this.getCheatSetValueError(cheat));
397
+ return;
398
+ }
399
+ if (!this.player ||
400
+ typeof this.player.cpuRead !== 'function' ||
401
+ typeof this.player.cpuWrite !== 'function') {
402
+ this.setCheatStatus('Emulator memory is not ready yet.');
403
+ return;
404
+ }
405
+ const currentValue = this.player.cpuRead(address) & 0xff;
406
+ const nextValue = cheat.action === 'set'
407
+ ? setValue
408
+ : cheat.action === 'decrement'
409
+ ? (currentValue + 0xff) & 0xff
410
+ : (currentValue + 1) & 0xff;
411
+ this.player.cpuWrite(address, nextValue);
412
+ const actionLabel = CHEAT_ACTIONS.find((action) => action.value === cheat.action)?.label ?? 'Updated';
413
+ this.setCheatStatus(`${actionLabel} ${formatHexAddress(address)}: ${formatHexByte(currentValue)} -> ${formatHexByte(nextValue)}`);
414
+ }
415
+ addCheat() {
416
+ this.cheats = [
417
+ ...this.cheats,
418
+ createCheatRow({ id: `cheat-${this.nextCheatId++}`, address: '' }),
419
+ ];
420
+ this.saveCheatConfig();
421
+ this.renderCheats();
422
+ }
423
+ removeCheat(cheatId) {
424
+ if (this.cheats.length <= 1)
425
+ return;
426
+ this.cheats = this.cheats.filter((cheat) => cheat.id !== cheatId);
427
+ if (this.recordingCheatId === cheatId)
428
+ this.recordingCheatId = null;
429
+ this.saveCheatConfig();
430
+ this.renderCheats();
431
+ }
432
+ renderCheats() {
433
+ const list = document.getElementById('c64-cheat-list');
434
+ if (!list)
435
+ return;
436
+ list.replaceChildren(...this.cheats.map((cheat, index) => {
437
+ const card = document.createElement('article');
438
+ card.className = 'c64-cheat-card';
439
+ card.addEventListener('keydown', (event) => event.stopPropagation());
440
+ card.addEventListener('keyup', (event) => event.stopPropagation());
441
+ const header = document.createElement('div');
442
+ header.className = 'c64-cheat-card-header';
443
+ const title = document.createElement('span');
444
+ title.textContent = `Cheat ${index + 1}`;
445
+ header.appendChild(title);
446
+ if (this.cheats.length > 1) {
447
+ const remove = document.createElement('button');
448
+ remove.type = 'button';
449
+ remove.className = 'c64-cheat-remove';
450
+ remove.textContent = 'Remove';
451
+ remove.addEventListener('click', () => this.removeCheat(cheat.id));
452
+ header.appendChild(remove);
453
+ }
454
+ const grid = document.createElement('div');
455
+ grid.className = 'c64-cheat-grid';
456
+ const addressInput = document.createElement('input');
457
+ addressInput.id = `c64-cheat-address-${cheat.id}`;
458
+ addressInput.className = 'c64-cheat-input';
459
+ addressInput.type = 'text';
460
+ addressInput.inputMode = 'text';
461
+ addressInput.spellcheck = false;
462
+ addressInput.autocomplete = 'off';
463
+ addressInput.placeholder = '0x004e';
464
+ addressInput.value = cheat.address;
465
+ addressInput.addEventListener('input', () => {
466
+ cheat.address = addressInput.value;
467
+ this.saveCheatConfig();
468
+ });
469
+ grid.appendChild(this.makeLabel(addressInput.id, 'Memory address'));
470
+ grid.appendChild(addressInput);
471
+ const actionSelect = document.createElement('select');
472
+ actionSelect.id = `c64-cheat-action-${cheat.id}`;
473
+ actionSelect.className = 'c64-cheat-input';
474
+ for (const action of CHEAT_ACTIONS) {
475
+ const option = document.createElement('option');
476
+ option.value = action.value;
477
+ option.textContent = action.label;
478
+ option.selected = cheat.action === action.value;
479
+ actionSelect.appendChild(option);
480
+ }
481
+ actionSelect.addEventListener('change', () => {
482
+ cheat.action = actionSelect.value;
483
+ this.saveCheatConfig();
484
+ this.renderCheats();
485
+ });
486
+ grid.appendChild(this.makeLabel(actionSelect.id, 'Action'));
487
+ grid.appendChild(actionSelect);
488
+ if (cheat.action === 'set') {
489
+ const setInput = document.createElement('input');
490
+ setInput.id = `c64-cheat-set-value-${cheat.id}`;
491
+ setInput.className = 'c64-cheat-input';
492
+ setInput.type = 'text';
493
+ setInput.inputMode = 'text';
494
+ setInput.spellcheck = false;
495
+ setInput.autocomplete = 'off';
496
+ setInput.placeholder = '0xff';
497
+ setInput.value = cheat.setValue;
498
+ setInput.addEventListener('input', () => {
499
+ cheat.setValue = setInput.value;
500
+ this.saveCheatConfig();
501
+ });
502
+ grid.appendChild(this.makeLabel(setInput.id, 'Set value'));
503
+ grid.appendChild(setInput);
504
+ }
505
+ const keyButton = document.createElement('button');
506
+ keyButton.id = `c64-cheat-key-${cheat.id}`;
507
+ keyButton.type = 'button';
508
+ keyButton.className = `c64-btn${this.recordingCheatId === cheat.id ? ' active' : ''}`;
509
+ keyButton.textContent =
510
+ this.recordingCheatId === cheat.id
511
+ ? 'Press a key...'
512
+ : (cheat.keyBinding?.label ?? 'Choose key...');
513
+ keyButton.addEventListener('click', () => {
514
+ this.recordingCheatId = cheat.id;
515
+ this.renderCheats();
516
+ document.getElementById(keyButton.id)?.focus();
517
+ });
518
+ keyButton.addEventListener('keydown', (event) => {
519
+ if (this.recordingCheatId !== cheat.id)
520
+ return;
521
+ event.preventDefault();
522
+ event.stopPropagation();
523
+ cheat.keyBinding = keyBindingFromEvent(event);
524
+ this.recordingCheatId = null;
525
+ this.saveCheatConfig();
526
+ this.renderCheats();
527
+ });
528
+ grid.appendChild(this.makeLabel(keyButton.id, 'Key press'));
529
+ grid.appendChild(keyButton);
530
+ const actions = document.createElement('div');
531
+ actions.className = 'c64-cheat-actions';
532
+ const apply = document.createElement('button');
533
+ apply.type = 'button';
534
+ apply.className = 'c64-btn';
535
+ apply.textContent = 'Apply Now';
536
+ apply.disabled = !this.isCheatReady(cheat);
537
+ apply.addEventListener('click', () => this.applyCheatAction(cheat));
538
+ actions.appendChild(apply);
539
+ if (this.recordingCheatId === cheat.id) {
540
+ const cancel = document.createElement('button');
541
+ cancel.type = 'button';
542
+ cancel.className = 'c64-btn';
543
+ cancel.textContent = 'Cancel Key';
544
+ cancel.addEventListener('click', () => {
545
+ this.recordingCheatId = null;
546
+ this.renderCheats();
547
+ });
548
+ actions.appendChild(cancel);
549
+ }
550
+ if (cheat.keyBinding) {
551
+ const clear = document.createElement('button');
552
+ clear.type = 'button';
553
+ clear.className = 'c64-btn';
554
+ clear.textContent = 'Clear Key';
555
+ clear.addEventListener('click', () => {
556
+ cheat.keyBinding = null;
557
+ this.saveCheatConfig();
558
+ this.renderCheats();
559
+ });
560
+ actions.appendChild(clear);
561
+ }
562
+ const error = this.getCheatAddressError(cheat) || this.getCheatSetValueError(cheat);
563
+ card.appendChild(header);
564
+ card.appendChild(grid);
565
+ card.appendChild(actions);
566
+ if (error) {
567
+ const errorEl = document.createElement('p');
568
+ errorEl.className = 'c64-cheat-error';
569
+ errorEl.textContent = error;
570
+ card.appendChild(errorEl);
571
+ }
572
+ return card;
573
+ }));
574
+ const status = document.getElementById('c64-cheat-status');
575
+ if (status) {
576
+ status.textContent = this.cheatStatus;
577
+ status.hidden = !this.cheatStatus;
578
+ }
579
+ }
580
+ makeLabel(htmlFor, text) {
581
+ const label = document.createElement('label');
582
+ label.htmlFor = htmlFor;
583
+ label.textContent = text;
584
+ return label;
585
+ }
586
+ dumpC64Ram() {
587
+ if (!this.player || typeof this.player.ramRead !== 'function') {
588
+ this.setCheatStatus('Emulator RAM is not ready yet.');
589
+ return;
590
+ }
591
+ try {
592
+ const bytes = new Uint8Array(0x10000);
593
+ for (let address = 0; address <= 0xffff; address += 1) {
594
+ bytes[address] = this.player.ramRead(address) & 0xff;
595
+ }
596
+ const filename = formatRamDumpFilename();
597
+ this.downloadBytes(filename, bytes);
598
+ this.setCheatStatus(`Dumped 64K RAM to ${filename}`);
599
+ }
600
+ catch (error) {
601
+ this.setCheatStatus(error instanceof Error ? error.message : 'Failed to dump C64 RAM.');
602
+ }
603
+ }
143
604
  injectCSS() {
144
605
  if (document.querySelector('style[data-c64-help]'))
145
606
  return;
@@ -262,6 +723,8 @@ export default class UIController {
262
723
  { id: 'input', label: 'Input' },
263
724
  { id: 'display', label: 'Display' },
264
725
  { id: 'audio', label: 'Audio' },
726
+ { id: 'cheevos', label: 'Cheevos' },
727
+ { id: 'cheats', label: 'Cheats' },
265
728
  { id: 'system', label: 'System' },
266
729
  ];
267
730
  const loadTypeOptions = LOAD_FORMAT_OPTIONS.map((format) => `<option value="${format.type}">${format.label}</option>`).join('');
@@ -350,6 +813,52 @@ export default class UIController {
350
813
  <div id="c64-audio-section-anchor"></div>
351
814
  </section>
352
815
 
816
+ <section class="c64-settings-section" data-settings-section="cheevos" hidden>
817
+ <label class="c64-section-label">Cheevos Dev</label>
818
+ <div class="c64-section-hint">Load a c64-cheevos detector and optional achievement set JSON for local development.</div>
819
+ <div class="c64-form-row">
820
+ <label for="c64-cheevos-detector">Detector ID</label>
821
+ <input id="c64-cheevos-detector" class="c64-text-input" type="text" placeholder="uridium" />
822
+ </div>
823
+ <div class="c64-form-row">
824
+ <button class="c64-btn" id="c64-cheevos-browse-json-btn" type="button">Load JSON File</button>
825
+ <span class="c64-inline-status" id="c64-cheevos-json-filename">No JSON file loaded</span>
826
+ <input id="c64-cheevos-json-file" class="c64-cheevos-json-file" type="file" accept="application/json,.json" />
827
+ </div>
828
+ <textarea id="c64-cheevos-json" class="c64-textarea" spellcheck="false" placeholder='{ "_id": "set1", "cheevos": [{ "_id": "zinc", "title": "Zinc", "description": "Clear level 1" }] }'></textarea>
829
+ <div class="c64-menu-actions">
830
+ <button class="c64-btn" id="c64-cheevos-enable-btn">Enable</button>
831
+ <button class="c64-btn" id="c64-cheevos-disable-btn">Disable</button>
832
+ <button class="c64-btn" id="c64-cheevos-choose-rom-btn" type="button" disabled>Choose ROM File</button>
833
+ <button class="c64-btn" id="c64-cheevos-clear-popped-btn">Clear Unlocks</button>
834
+ <button class="c64-btn" id="c64-cheevos-clear-scores-btn">Clear Scores</button>
835
+ </div>
836
+ <input id="c64-cheevos-rom-file" class="c64-cheevos-json-file" type="file" accept=".crt,.prg,.d64" />
837
+ <label class="c64-checkbox-row" for="c64-cheevos-tracker-visible">
838
+ <input type="checkbox" id="c64-cheevos-tracker-visible" />
839
+ Show tracker panel
840
+ </label>
841
+ <div class="c64-section-hint">Shows the cheevos tracker beside the emulator in Standard display mode.</div>
842
+ <div class="c64-section-hint" id="c64-cheevos-status">Cheevos dev tracking is disabled.</div>
843
+ </section>
844
+
845
+ <section class="c64-settings-section" data-settings-section="cheats" hidden>
846
+ <label class="c64-section-label">Cheat Mode</label>
847
+ <div class="c64-section-hint">Bind keys to change C64 memory bytes while the game is running. Values wrap between 0x00 and 0xff.</div>
848
+ <div class="c64-cheat-list" id="c64-cheat-list"></div>
849
+ <div class="c64-menu-actions">
850
+ <button class="c64-btn" id="c64-add-cheat-btn" type="button">Add Cheat</button>
851
+ </div>
852
+ <div class="c64-tools-section">
853
+ <label class="c64-section-label">Memory Tools</label>
854
+ <div class="c64-menu-actions">
855
+ <button class="c64-btn" id="c64-dump-ram-btn" type="button">Dump 64K RAM</button>
856
+ </div>
857
+ <div class="c64-section-hint">Downloads raw C64 RAM from $0000-$ffff as a .bin file for address inspection.</div>
858
+ <div class="c64-cheat-status" id="c64-cheat-status" hidden></div>
859
+ </div>
860
+ </section>
861
+
353
862
  <section class="c64-settings-section" data-settings-section="system" hidden>
354
863
  <label class="c64-section-label">System Actions</label>
355
864
  <div class="c64-system-actions">
@@ -534,6 +1043,161 @@ export default class UIController {
534
1043
  window.dispatchEvent(new CustomEvent('c64-load-tool', { detail: tool }));
535
1044
  });
536
1045
  loadToolsManifest().catch(() => { });
1046
+ const cheevosDetectorInput = panel.querySelector('#c64-cheevos-detector');
1047
+ const cheevosJsonInput = panel.querySelector('#c64-cheevos-json');
1048
+ const cheevosJsonFile = panel.querySelector('#c64-cheevos-json-file');
1049
+ const cheevosBrowseJsonBtn = panel.querySelector('#c64-cheevos-browse-json-btn');
1050
+ const cheevosJsonFilename = panel.querySelector('#c64-cheevos-json-filename');
1051
+ const cheevosStatus = panel.querySelector('#c64-cheevos-status');
1052
+ const cheevosTrackerVisibleInput = panel.querySelector('#c64-cheevos-tracker-visible');
1053
+ const cheevosChooseRomBtn = panel.querySelector('#c64-cheevos-choose-rom-btn');
1054
+ const cheevosRomFile = panel.querySelector('#c64-cheevos-rom-file');
1055
+ let pendingCheevosRomPath = '';
1056
+ let pendingCheevosRomType;
1057
+ const storedCheevosDetector = window.localStorage.getItem(CHEEVOS_DETECTOR_STORAGE_KEY) ?? '';
1058
+ if (cheevosDetectorInput)
1059
+ cheevosDetectorInput.value = storedCheevosDetector;
1060
+ const trackerVisible = window.localStorage.getItem(CHEEVOS_TRACKER_VISIBLE_STORAGE_KEY) !== '0';
1061
+ if (cheevosTrackerVisibleInput) {
1062
+ cheevosTrackerVisibleInput.checked = trackerVisible;
1063
+ window.dispatchEvent(new CustomEvent('c64-cheevos-tracker-toggle', { detail: { visible: trackerVisible } }));
1064
+ cheevosTrackerVisibleInput.addEventListener('change', () => {
1065
+ const visible = cheevosTrackerVisibleInput.checked;
1066
+ window.localStorage.setItem(CHEEVOS_TRACKER_VISIBLE_STORAGE_KEY, visible ? '1' : '0');
1067
+ window.dispatchEvent(new CustomEvent('c64-cheevos-tracker-toggle', { detail: { visible } }));
1068
+ });
1069
+ }
1070
+ cheevosBrowseJsonBtn?.addEventListener('click', () => {
1071
+ cheevosJsonFile?.click();
1072
+ });
1073
+ cheevosJsonFile?.addEventListener('change', async () => {
1074
+ const file = cheevosJsonFile.files?.[0];
1075
+ if (!file || !cheevosJsonInput || !cheevosStatus)
1076
+ return;
1077
+ try {
1078
+ cheevosJsonInput.value = await file.text();
1079
+ if (cheevosJsonFilename)
1080
+ cheevosJsonFilename.textContent = file.name;
1081
+ cheevosStatus.textContent = `Loaded JSON from ${file.name}`;
1082
+ this.promptForCheevosJsonUrl(file, cheevosDetectorInput, cheevosStatus);
1083
+ }
1084
+ catch (err) {
1085
+ cheevosStatus.textContent = `Unable to read JSON file: ${String(err?.message ?? err)}`;
1086
+ }
1087
+ });
1088
+ panel.querySelector('#c64-cheevos-enable-btn')?.addEventListener('click', () => {
1089
+ const detectorId = cheevosDetectorInput?.value.trim() ?? '';
1090
+ const jsonText = cheevosJsonInput?.value.trim() ?? '';
1091
+ if (!detectorId) {
1092
+ if (cheevosStatus)
1093
+ cheevosStatus.textContent = 'Enter a detector ID first.';
1094
+ return;
1095
+ }
1096
+ window.localStorage.setItem(CHEEVOS_DETECTOR_STORAGE_KEY, detectorId);
1097
+ window.dispatchEvent(new CustomEvent('c64-cheevos-enable', { detail: { detectorId, jsonText } }));
1098
+ if (cheevosStatus)
1099
+ cheevosStatus.textContent = `Enabling ${detectorId}...`;
1100
+ });
1101
+ panel.querySelector('#c64-cheevos-disable-btn')?.addEventListener('click', () => {
1102
+ window.dispatchEvent(new CustomEvent('c64-cheevos-disable'));
1103
+ if (cheevosStatus)
1104
+ cheevosStatus.textContent = 'Cheevos dev tracking is disabled.';
1105
+ });
1106
+ const dispatchCheevosRomFile = (file, romPath, type) => {
1107
+ const resolvedType = type ?? inferLoadTypeFromFilename(file.name) ?? 'crt';
1108
+ window.dispatchEvent(new CustomEvent('c64-cheevos-rom-file', {
1109
+ detail: { file, type: resolvedType, romPath },
1110
+ }));
1111
+ if (cheevosStatus)
1112
+ cheevosStatus.textContent = `Loading ROM ${file.name} for ${romPath}`;
1113
+ };
1114
+ cheevosChooseRomBtn?.addEventListener('click', async () => {
1115
+ if (!pendingCheevosRomPath)
1116
+ return;
1117
+ if ('showOpenFilePicker' in window) {
1118
+ try {
1119
+ const rom = await chooseAndStoreCheevosRom(pendingCheevosRomPath, pendingCheevosRomType);
1120
+ if (rom)
1121
+ dispatchCheevosRomFile(rom.file, rom.romPath, rom.type);
1122
+ return;
1123
+ }
1124
+ catch (err) {
1125
+ if (err?.name === 'AbortError')
1126
+ return;
1127
+ if (cheevosStatus) {
1128
+ cheevosStatus.textContent = `Unable to remember ROM file: ${String(err?.message ?? err)}`;
1129
+ }
1130
+ return;
1131
+ }
1132
+ }
1133
+ cheevosRomFile?.click();
1134
+ });
1135
+ cheevosRomFile?.addEventListener('change', async () => {
1136
+ const file = cheevosRomFile.files?.[0];
1137
+ if (!file || !pendingCheevosRomPath)
1138
+ return;
1139
+ try {
1140
+ await storeCheevosRomFile(pendingCheevosRomPath, file, pendingCheevosRomType);
1141
+ }
1142
+ catch (err) {
1143
+ if (cheevosStatus) {
1144
+ cheevosStatus.textContent = `Unable to remember ROM file: ${String(err?.message ?? err)}`;
1145
+ }
1146
+ }
1147
+ dispatchCheevosRomFile(file, pendingCheevosRomPath, pendingCheevosRomType);
1148
+ });
1149
+ panel.querySelector('#c64-cheevos-clear-popped-btn')?.addEventListener('click', () => {
1150
+ window.dispatchEvent(new CustomEvent('c64-cheevos-clear-popped', {
1151
+ detail: { detectorId: cheevosDetectorInput?.value.trim() ?? '' },
1152
+ }));
1153
+ if (cheevosStatus)
1154
+ cheevosStatus.textContent = 'Local unlocks cleared.';
1155
+ });
1156
+ panel.querySelector('#c64-cheevos-clear-scores-btn')?.addEventListener('click', () => {
1157
+ window.dispatchEvent(new CustomEvent('c64-cheevos-clear-scores', {
1158
+ detail: { detectorId: cheevosDetectorInput?.value.trim() ?? '' },
1159
+ }));
1160
+ if (cheevosStatus)
1161
+ cheevosStatus.textContent = 'Local scores cleared.';
1162
+ });
1163
+ window.addEventListener('c64-cheevos-status', (event) => {
1164
+ if (!cheevosStatus)
1165
+ return;
1166
+ const detail = event.detail;
1167
+ if (detail?.status === 'enabled') {
1168
+ cheevosStatus.textContent = `Tracking ${detail.detectorId ?? 'cheevos'} (${detail.cheevosCount ?? 0} achievements)`;
1169
+ }
1170
+ });
1171
+ window.addEventListener('c64-cheevos-json-loaded', (event) => {
1172
+ const detail = event.detail;
1173
+ if (!detail?.jsonText || !cheevosJsonInput)
1174
+ return;
1175
+ cheevosJsonInput.value = detail.jsonText;
1176
+ if (cheevosJsonFilename)
1177
+ cheevosJsonFilename.textContent = detail.source ?? 'URL-loaded JSON';
1178
+ if (cheevosStatus)
1179
+ cheevosStatus.textContent = `Loaded JSON from ${detail.source ?? 'URL'}`;
1180
+ });
1181
+ window.addEventListener('c64-cheevos-rom-needed', (event) => {
1182
+ const detail = event
1183
+ .detail;
1184
+ pendingCheevosRomPath = detail?.romPath?.trim() ?? '';
1185
+ pendingCheevosRomType = isSupportedLoadType(detail?.type) ? detail.type : undefined;
1186
+ if (cheevosChooseRomBtn)
1187
+ cheevosChooseRomBtn.disabled = !pendingCheevosRomPath;
1188
+ if (cheevosStatus && pendingCheevosRomPath) {
1189
+ cheevosStatus.textContent = `${detail?.reason ?? 'Choose local ROM file'}: ${pendingCheevosRomPath}`;
1190
+ }
1191
+ });
1192
+ window.addEventListener('c64-cheevos-error', (event) => {
1193
+ if (!cheevosStatus)
1194
+ return;
1195
+ const detail = event.detail;
1196
+ cheevosStatus.textContent = `Cheevos error: ${detail?.error ?? 'Unknown error'}`;
1197
+ });
1198
+ panel.querySelector('#c64-add-cheat-btn')?.addEventListener('click', () => this.addCheat());
1199
+ panel.querySelector('#c64-dump-ram-btn')?.addEventListener('click', () => this.dumpC64Ram());
1200
+ this.renderCheats();
537
1201
  const section = panel.querySelector('[data-settings-section="system"]');
538
1202
  // Detach cartridge / hard reset controls
539
1203
  const saveSnapshotBtn = section?.querySelector('#c64-save-snapshot-btn');