src/gb/core.c (view raw)
1/* Copyright (c) 2013-2016 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include <mgba/gb/core.h>
7
8#include <mgba/core/core.h>
9#include <mgba/internal/debugger/symbols.h>
10#include <mgba/internal/gb/cheats.h>
11#include <mgba/internal/gb/debugger/symbols.h>
12#include <mgba/internal/gb/extra/cli.h>
13#include <mgba/internal/gb/io.h>
14#include <mgba/internal/gb/gb.h>
15#include <mgba/internal/gb/mbc.h>
16#include <mgba/internal/gb/overrides.h>
17#include <mgba/internal/gb/renderers/software.h>
18#include <mgba/internal/gb/renderers/proxy.h>
19#include <mgba/internal/gb/serialize.h>
20#include <mgba/internal/lr35902/lr35902.h>
21#include <mgba/internal/lr35902/debugger/debugger.h>
22#include <mgba-util/crc32.h>
23#include <mgba-util/memory.h>
24#include <mgba-util/patch.h>
25#include <mgba-util/vfs.h>
26
27static const struct mCoreChannelInfo _GBVideoLayers[] = {
28 { 0, "bg", "Background", NULL },
29 { 1, "bgwin", "Window", NULL },
30 { 2, "obj", "Objects", NULL },
31};
32
33static const struct mCoreChannelInfo _GBAudioChannels[] = {
34 { 0, "ch1", "Channel 1", "Square/Sweep" },
35 { 1, "ch2", "Channel 2", "Square" },
36 { 2, "ch3", "Channel 3", "PCM" },
37 { 3, "ch4", "Channel 4", "Noise" },
38};
39
40static const struct LR35902Segment _GBSegments[] = {
41 { .name = "ROM", .start = GB_BASE_CART_BANK1, .end = GB_BASE_VRAM },
42 { .name = "RAM", .start = GB_BASE_EXTERNAL_RAM, .end = GB_BASE_WORKING_RAM_BANK0 },
43 { 0 }
44};
45
46static const struct LR35902Segment _GBCSegments[] = {
47 { .name = "ROM", .start = GB_BASE_CART_BANK1, .end = GB_BASE_VRAM },
48 { .name = "RAM", .start = GB_BASE_EXTERNAL_RAM, .end = GB_BASE_WORKING_RAM_BANK0 },
49 { .name = "WRAM", .start = GB_BASE_WORKING_RAM_BANK1, .end = 0xE000 },
50 { .name = "VRAM", .start = GB_BASE_VRAM, .end = GB_BASE_EXTERNAL_RAM },
51 { 0 }
52};
53
54static const struct mCoreMemoryBlock _GBMemoryBlocks[] = {
55 { -1, "mem", "All", "All", 0, 0x10000, 0x10000, mCORE_MEMORY_VIRTUAL },
56 { GB_REGION_CART_BANK0, "cart0", "ROM Bank", "Game Pak (32kiB)", GB_BASE_CART_BANK0, GB_SIZE_CART_BANK0 * 2, 0x800000, mCORE_MEMORY_READ | mCORE_MEMORY_MAPPED, 511 },
57 { GB_REGION_VRAM, "vram", "VRAM", "Video RAM (8kiB)", GB_BASE_VRAM, GB_BASE_VRAM + GB_SIZE_VRAM, GB_SIZE_VRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
58 { GB_REGION_EXTERNAL_RAM, "sram", "SRAM", "External RAM (8kiB)", GB_BASE_EXTERNAL_RAM, GB_BASE_EXTERNAL_RAM + GB_SIZE_EXTERNAL_RAM, GB_SIZE_EXTERNAL_RAM * 4, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 3 },
59 { GB_REGION_WORKING_RAM_BANK0, "wram", "WRAM", "Working RAM (8kiB)", GB_BASE_WORKING_RAM_BANK0, GB_BASE_WORKING_RAM_BANK0 + GB_SIZE_WORKING_RAM_BANK0 * 2 , GB_SIZE_WORKING_RAM_BANK0 * 2, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
60 { GB_BASE_OAM, "oam", "OAM", "OBJ Attribute Memory", GB_BASE_OAM, GB_BASE_OAM + GB_SIZE_OAM, GB_SIZE_OAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
61 { GB_BASE_IO, "io", "MMIO", "Memory-Mapped I/O", GB_BASE_IO, GB_BASE_IO + GB_SIZE_IO, GB_SIZE_IO, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
62 { GB_BASE_HRAM, "hram", "HRAM", "High RAM", GB_BASE_HRAM, GB_BASE_HRAM + GB_SIZE_HRAM, GB_SIZE_HRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
63};
64
65static const struct mCoreMemoryBlock _GBCMemoryBlocks[] = {
66 { -1, "mem", "All", "All", 0, 0x10000, 0x10000, mCORE_MEMORY_VIRTUAL },
67 { GB_REGION_CART_BANK0, "cart0", "ROM Bank", "Game Pak (32kiB)", GB_BASE_CART_BANK0, GB_SIZE_CART_BANK0 * 2, 0x800000, mCORE_MEMORY_READ | mCORE_MEMORY_MAPPED, 511 },
68 { GB_REGION_VRAM, "vram", "VRAM", "Video RAM (8kiB)", GB_BASE_VRAM, GB_BASE_VRAM + GB_SIZE_VRAM, GB_SIZE_VRAM * 2, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 1 },
69 { GB_REGION_EXTERNAL_RAM, "sram", "SRAM", "External RAM (8kiB)", GB_BASE_EXTERNAL_RAM, GB_BASE_EXTERNAL_RAM + GB_SIZE_EXTERNAL_RAM, GB_SIZE_EXTERNAL_RAM * 4, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 3 },
70 { GB_REGION_WORKING_RAM_BANK0, "wram", "WRAM", "Working RAM (8kiB)", GB_BASE_WORKING_RAM_BANK0, GB_BASE_WORKING_RAM_BANK0 + GB_SIZE_WORKING_RAM_BANK0 * 2, GB_SIZE_WORKING_RAM_BANK0 * 8, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 7 },
71 { GB_BASE_OAM, "oam", "OAM", "OBJ Attribute Memory", GB_BASE_OAM, GB_BASE_OAM + GB_SIZE_OAM, GB_SIZE_OAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
72 { GB_BASE_IO, "io", "MMIO", "Memory-Mapped I/O", GB_BASE_IO, GB_BASE_IO + GB_SIZE_IO, GB_SIZE_IO, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
73 { GB_BASE_HRAM, "hram", "HRAM", "High RAM", GB_BASE_HRAM, GB_BASE_HRAM + GB_SIZE_HRAM, GB_SIZE_HRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
74};
75
76struct mVideoLogContext;
77struct GBCore {
78 struct mCore d;
79 struct GBVideoSoftwareRenderer renderer;
80 struct GBVideoProxyRenderer proxyRenderer;
81 struct mVideoLogContext* logContext;
82 struct mCoreCallbacks logCallbacks;
83 uint8_t keys;
84 struct mCPUComponent* components[CPU_COMPONENT_MAX];
85 const struct Configuration* overrides;
86 struct mDebuggerPlatform* debuggerPlatform;
87 struct mCheatDevice* cheatDevice;
88};
89
90static bool _GBCoreInit(struct mCore* core) {
91 struct GBCore* gbcore = (struct GBCore*) core;
92
93 struct LR35902Core* cpu = anonymousMemoryMap(sizeof(struct LR35902Core));
94 struct GB* gb = anonymousMemoryMap(sizeof(struct GB));
95 if (!cpu || !gb) {
96 free(cpu);
97 free(gb);
98 return false;
99 }
100 core->cpu = cpu;
101 core->board = gb;
102 gbcore->overrides = NULL;
103 gbcore->debuggerPlatform = NULL;
104 gbcore->cheatDevice = NULL;
105
106 GBCreate(gb);
107 memset(gbcore->components, 0, sizeof(gbcore->components));
108 LR35902SetComponents(cpu, &gb->d, CPU_COMPONENT_MAX, gbcore->components);
109 LR35902Init(cpu);
110 mRTCGenericSourceInit(&core->rtc, core);
111 gb->memory.rtc = &core->rtc.d;
112
113 GBVideoSoftwareRendererCreate(&gbcore->renderer);
114 gbcore->renderer.outputBuffer = NULL;
115
116 gbcore->keys = 0;
117 gb->keySource = &gbcore->keys;
118
119#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
120 mDirectorySetInit(&core->dirs);
121#endif
122
123 return true;
124}
125
126static void _GBCoreDeinit(struct mCore* core) {
127 LR35902Deinit(core->cpu);
128 GBDestroy(core->board);
129 mappedMemoryFree(core->cpu, sizeof(struct LR35902Core));
130 mappedMemoryFree(core->board, sizeof(struct GB));
131#if defined USE_DEBUGGERS && (!defined(MINIMAL_CORE) || MINIMAL_CORE < 2)
132 mDirectorySetDeinit(&core->dirs);
133 if (core->symbolTable) {
134 mDebuggerSymbolTableDestroy(core->symbolTable);
135 }
136#endif
137
138 struct GBCore* gbcore = (struct GBCore*) core;
139 free(gbcore->debuggerPlatform);
140 if (gbcore->cheatDevice) {
141 mCheatDeviceDestroy(gbcore->cheatDevice);
142 }
143 free(gbcore->cheatDevice);
144 mCoreConfigFreeOpts(&core->opts);
145 free(core);
146}
147
148static enum mPlatform _GBCorePlatform(const struct mCore* core) {
149 UNUSED(core);
150 return PLATFORM_GB;
151}
152
153static void _GBCoreSetSync(struct mCore* core, struct mCoreSync* sync) {
154 struct GB* gb = core->board;
155 gb->sync = sync;
156}
157
158static void _GBCoreLoadConfig(struct mCore* core, const struct mCoreConfig* config) {
159 UNUSED(config);
160
161 struct GB* gb = core->board;
162 if (core->opts.mute) {
163 gb->audio.masterVolume = 0;
164 } else {
165 gb->audio.masterVolume = core->opts.volume;
166 }
167 gb->video.frameskip = core->opts.frameskip;
168
169 int color;
170 if (mCoreConfigGetIntValue(config, "gb.pal[0]", &color)) {
171 GBVideoSetPalette(&gb->video, 0, color);
172 }
173 if (mCoreConfigGetIntValue(config, "gb.pal[1]", &color)) {
174 GBVideoSetPalette(&gb->video, 1, color);
175 }
176 if (mCoreConfigGetIntValue(config, "gb.pal[2]", &color)) {
177 GBVideoSetPalette(&gb->video, 2, color);
178 }
179 if (mCoreConfigGetIntValue(config, "gb.pal[3]", &color)) {
180 GBVideoSetPalette(&gb->video, 3, color);
181 }
182 if (mCoreConfigGetIntValue(config, "gb.pal[4]", &color)) {
183 GBVideoSetPalette(&gb->video, 4, color);
184 }
185 if (mCoreConfigGetIntValue(config, "gb.pal[5]", &color)) {
186 GBVideoSetPalette(&gb->video, 5, color);
187 }
188 if (mCoreConfigGetIntValue(config, "gb.pal[6]", &color)) {
189 GBVideoSetPalette(&gb->video, 6, color);
190 }
191 if (mCoreConfigGetIntValue(config, "gb.pal[7]", &color)) {
192 GBVideoSetPalette(&gb->video, 7, color);
193 }
194 if (mCoreConfigGetIntValue(config, "gb.pal[8]", &color)) {
195 GBVideoSetPalette(&gb->video, 8, color);
196 }
197 if (mCoreConfigGetIntValue(config, "gb.pal[9]", &color)) {
198 GBVideoSetPalette(&gb->video, 9, color);
199 }
200 if (mCoreConfigGetIntValue(config, "gb.pal[10]", &color)) {
201 GBVideoSetPalette(&gb->video, 10, color);
202 }
203 if (mCoreConfigGetIntValue(config, "gb.pal[11]", &color)) {
204 GBVideoSetPalette(&gb->video, 11, color);
205 }
206
207 mCoreConfigCopyValue(&core->config, config, "gb.bios");
208 mCoreConfigCopyValue(&core->config, config, "sgb.bios");
209 mCoreConfigCopyValue(&core->config, config, "gbc.bios");
210 mCoreConfigCopyValue(&core->config, config, "gb.model");
211 mCoreConfigCopyValue(&core->config, config, "sgb.model");
212 mCoreConfigCopyValue(&core->config, config, "cgb.model");
213 mCoreConfigCopyValue(&core->config, config, "sgb.borders");
214
215#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
216 struct GBCore* gbcore = (struct GBCore*) core;
217 gbcore->overrides = mCoreConfigGetOverridesConst(config);
218#endif
219}
220
221static void _GBCoreDesiredVideoDimensions(struct mCore* core, unsigned* width, unsigned* height) {
222 struct GB* gb = core->board;
223 if (gb && (gb->model != GB_MODEL_SGB || !gb->video.sgbBorders)) {
224 *width = GB_VIDEO_HORIZONTAL_PIXELS;
225 *height = GB_VIDEO_VERTICAL_PIXELS;
226 } else {
227 *width = 256;
228 *height = 224;
229 }
230}
231
232static void _GBCoreSetVideoBuffer(struct mCore* core, color_t* buffer, size_t stride) {
233 struct GBCore* gbcore = (struct GBCore*) core;
234 gbcore->renderer.outputBuffer = buffer;
235 gbcore->renderer.outputBufferStride = stride;
236}
237
238static void _GBCoreGetPixels(struct mCore* core, const void** buffer, size_t* stride) {
239 struct GBCore* gbcore = (struct GBCore*) core;
240 gbcore->renderer.d.getPixels(&gbcore->renderer.d, stride, buffer);
241}
242
243static void _GBCorePutPixels(struct mCore* core, const void* buffer, size_t stride) {
244 struct GBCore* gbcore = (struct GBCore*) core;
245 gbcore->renderer.d.putPixels(&gbcore->renderer.d, stride, buffer);
246}
247
248static struct blip_t* _GBCoreGetAudioChannel(struct mCore* core, int ch) {
249 struct GB* gb = core->board;
250 switch (ch) {
251 case 0:
252 return gb->audio.left;
253 case 1:
254 return gb->audio.right;
255 default:
256 return NULL;
257 }
258}
259
260static void _GBCoreSetAudioBufferSize(struct mCore* core, size_t samples) {
261 struct GB* gb = core->board;
262 GBAudioResizeBuffer(&gb->audio, samples);
263}
264
265static size_t _GBCoreGetAudioBufferSize(struct mCore* core) {
266 struct GB* gb = core->board;
267 return gb->audio.samples;
268}
269
270static void _GBCoreAddCoreCallbacks(struct mCore* core, struct mCoreCallbacks* coreCallbacks) {
271 struct GB* gb = core->board;
272 *mCoreCallbacksListAppend(&gb->coreCallbacks) = *coreCallbacks;
273}
274
275static void _GBCoreClearCoreCallbacks(struct mCore* core) {
276 struct GB* gb = core->board;
277 mCoreCallbacksListClear(&gb->coreCallbacks);
278}
279
280static void _GBCoreSetAVStream(struct mCore* core, struct mAVStream* stream) {
281 struct GB* gb = core->board;
282 gb->stream = stream;
283 if (stream && stream->videoDimensionsChanged) {
284 stream->videoDimensionsChanged(stream, GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
285 }
286}
287
288static bool _GBCoreLoadROM(struct mCore* core, struct VFile* vf) {
289 return GBLoadROM(core->board, vf);
290}
291
292static bool _GBCoreLoadBIOS(struct mCore* core, struct VFile* vf, int type) {
293 UNUSED(type);
294 GBLoadBIOS(core->board, vf);
295 return true;
296}
297
298static bool _GBCoreLoadSave(struct mCore* core, struct VFile* vf) {
299 return GBLoadSave(core->board, vf);
300}
301
302static bool _GBCoreLoadTemporarySave(struct mCore* core, struct VFile* vf) {
303 struct GB* gb = core->board;
304 GBSavedataMask(gb, vf, false);
305 return true; // TODO: Return a real value
306}
307
308static bool _GBCoreLoadPatch(struct mCore* core, struct VFile* vf) {
309 if (!vf) {
310 return false;
311 }
312 struct Patch patch;
313 if (!loadPatch(vf, &patch)) {
314 return false;
315 }
316 GBApplyPatch(core->board, &patch);
317 return true;
318}
319
320static void _GBCoreUnloadROM(struct mCore* core) {
321 struct GBCore* gbcore = (struct GBCore*) core;
322 struct LR35902Core* cpu = core->cpu;
323 if (gbcore->cheatDevice) {
324 LR35902HotplugDetach(cpu, CPU_COMPONENT_CHEAT_DEVICE);
325 cpu->components[CPU_COMPONENT_CHEAT_DEVICE] = NULL;
326 mCheatDeviceDestroy(gbcore->cheatDevice);
327 gbcore->cheatDevice = NULL;
328 }
329 return GBUnloadROM(core->board);
330}
331
332static void _GBCoreChecksum(const struct mCore* core, void* data, enum mCoreChecksumType type) {
333 struct GB* gb = (struct GB*) core->board;
334 switch (type) {
335 case CHECKSUM_CRC32:
336 memcpy(data, &gb->romCrc32, sizeof(gb->romCrc32));
337 break;
338 }
339 return;
340}
341
342static void _GBCoreReset(struct mCore* core) {
343 struct GBCore* gbcore = (struct GBCore*) core;
344 struct GB* gb = (struct GB*) core->board;
345 if (gbcore->renderer.outputBuffer) {
346 GBVideoAssociateRenderer(&gb->video, &gbcore->renderer.d);
347 }
348
349 if (gb->memory.rom) {
350 struct GBCartridgeOverride override;
351 const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
352 override.headerCrc32 = doCrc32(cart, sizeof(*cart));
353 if (GBOverrideFind(gbcore->overrides, &override)) {
354 GBOverrideApply(gb, &override);
355 }
356 }
357
358 const char* modelGB = mCoreConfigGetValue(&core->config, "gb.model");
359 const char* modelCGB = mCoreConfigGetValue(&core->config, "cgb.model");
360 const char* modelSGB = mCoreConfigGetValue(&core->config, "sgb.model");
361 if (modelGB || modelCGB || modelSGB) {
362 GBDetectModel(gb);
363 if (gb->model == GB_MODEL_DMG && modelGB) {
364 gb->model = GBNameToModel(modelGB);
365 } else if (gb->model == GB_MODEL_CGB && modelCGB) {
366 gb->model = GBNameToModel(modelCGB);
367 } else if (gb->model == GB_MODEL_SGB && modelSGB) {
368 gb->model = GBNameToModel(modelSGB);
369 }
370 }
371
372 int fakeBool;
373 if (mCoreConfigGetIntValue(&core->config, "sgb.borders", &fakeBool)) {
374 gb->video.sgbBorders = fakeBool;
375 }
376
377#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
378 if (!gb->biosVf && core->opts.useBios) {
379 struct VFile* bios = NULL;
380 bool found = false;
381 if (core->opts.bios) {
382 bios = VFileOpen(core->opts.bios, O_RDONLY);
383 if (bios && GBIsBIOS(bios)) {
384 found = true;
385 } else if (bios) {
386 bios->close(bios);
387 bios = NULL;
388 }
389 }
390 if (!found) {
391 GBDetectModel(gb);
392 const char* configPath = NULL;
393
394 switch (gb->model) {
395 case GB_MODEL_DMG:
396 case GB_MODEL_MGB: // TODO
397 configPath = mCoreConfigGetValue(&core->config, "gb.bios");
398 break;
399 case GB_MODEL_SGB:
400 case GB_MODEL_SGB2: // TODO
401 configPath = mCoreConfigGetValue(&core->config, "sgb.bios");
402 break;
403 case GB_MODEL_CGB:
404 case GB_MODEL_AGB:
405 configPath = mCoreConfigGetValue(&core->config, "gbc.bios");
406 break;
407 default:
408 break;
409 };
410 if (configPath) {
411 bios = VFileOpen(configPath, O_RDONLY);
412 }
413 if (bios && GBIsBIOS(bios)) {
414 found = true;
415 } else if (bios) {
416 bios->close(bios);
417 bios = NULL;
418 }
419 }
420 if (!found) {
421 char path[PATH_MAX];
422 mCoreConfigDirectory(path, PATH_MAX);
423 switch (gb->model) {
424 case GB_MODEL_DMG:
425 case GB_MODEL_MGB: // TODO
426 strncat(path, PATH_SEP "gb_bios.bin", PATH_MAX - strlen(path));
427 break;
428 case GB_MODEL_SGB:
429 case GB_MODEL_SGB2: // TODO
430 strncat(path, PATH_SEP "sgb_bios.bin", PATH_MAX - strlen(path));
431 break;
432 case GB_MODEL_CGB:
433 case GB_MODEL_AGB:
434 strncat(path, PATH_SEP "gbc_bios.bin", PATH_MAX - strlen(path));
435 break;
436 default:
437 break;
438 };
439 bios = VFileOpen(path, O_RDONLY);
440 if (bios && GBIsBIOS(bios)) {
441 found = true;
442 } else if (bios) {
443 bios->close(bios);
444 bios = NULL;
445 }
446 }
447 if (bios) {
448 GBLoadBIOS(gb, bios);
449 }
450 }
451#endif
452
453 LR35902Reset(core->cpu);
454}
455
456static void _GBCoreRunFrame(struct mCore* core) {
457 struct GB* gb = core->board;
458 int32_t frameCounter = gb->video.frameCounter;
459 while (gb->video.frameCounter == frameCounter) {
460 LR35902Run(core->cpu);
461 }
462}
463
464static void _GBCoreRunLoop(struct mCore* core) {
465 LR35902Run(core->cpu);
466}
467
468static void _GBCoreStep(struct mCore* core) {
469 struct LR35902Core* cpu = core->cpu;
470 do {
471 LR35902Tick(cpu);
472 } while (cpu->executionState != LR35902_CORE_FETCH);
473}
474
475static size_t _GBCoreStateSize(struct mCore* core) {
476 UNUSED(core);
477 return sizeof(struct GBSerializedState);
478}
479
480static bool _GBCoreLoadState(struct mCore* core, const void* state) {
481 return GBDeserialize(core->board, state);
482}
483
484static bool _GBCoreSaveState(struct mCore* core, void* state) {
485 struct LR35902Core* cpu = core->cpu;
486 while (cpu->executionState != LR35902_CORE_FETCH) {
487 LR35902Tick(cpu);
488 }
489 GBSerialize(core->board, state);
490 return true;
491}
492
493static void _GBCoreSetKeys(struct mCore* core, uint32_t keys) {
494 struct GBCore* gbcore = (struct GBCore*) core;
495 gbcore->keys = keys;
496 GBTestKeypadIRQ(core->board);
497}
498
499static void _GBCoreAddKeys(struct mCore* core, uint32_t keys) {
500 struct GBCore* gbcore = (struct GBCore*) core;
501 gbcore->keys |= keys;
502 GBTestKeypadIRQ(core->board);
503}
504
505static void _GBCoreClearKeys(struct mCore* core, uint32_t keys) {
506 struct GBCore* gbcore = (struct GBCore*) core;
507 gbcore->keys &= ~keys;
508}
509
510static int32_t _GBCoreFrameCounter(const struct mCore* core) {
511 const struct GB* gb = core->board;
512 return gb->video.frameCounter;
513}
514
515static int32_t _GBCoreFrameCycles(const struct mCore* core) {
516 UNUSED(core);
517 return GB_VIDEO_TOTAL_LENGTH;
518}
519
520static int32_t _GBCoreFrequency(const struct mCore* core) {
521 UNUSED(core);
522 // TODO: GB differences
523 return DMG_LR35902_FREQUENCY;
524}
525
526static void _GBCoreGetGameTitle(const struct mCore* core, char* title) {
527 GBGetGameTitle(core->board, title);
528}
529
530static void _GBCoreGetGameCode(const struct mCore* core, char* title) {
531 GBGetGameCode(core->board, title);
532}
533
534static void _GBCoreSetPeripheral(struct mCore* core, int type, void* periph) {
535 struct GB* gb = core->board;
536 switch (type) {
537 case mPERIPH_ROTATION:
538 gb->memory.rotation = periph;
539 break;
540 case mPERIPH_RUMBLE:
541 gb->memory.rumble = periph;
542 break;
543 case mPERIPH_IMAGE_SOURCE:
544 gb->memory.cam = periph;
545 break;
546 default:
547 return;
548 }
549}
550
551static uint32_t _GBCoreBusRead8(struct mCore* core, uint32_t address) {
552 struct LR35902Core* cpu = core->cpu;
553 return cpu->memory.load8(cpu, address);
554}
555
556static uint32_t _GBCoreBusRead16(struct mCore* core, uint32_t address) {
557 struct LR35902Core* cpu = core->cpu;
558 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8);
559}
560
561static uint32_t _GBCoreBusRead32(struct mCore* core, uint32_t address) {
562 struct LR35902Core* cpu = core->cpu;
563 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8) |
564 (cpu->memory.load8(cpu, address + 2) << 16) | (cpu->memory.load8(cpu, address + 3) << 24);
565}
566
567static void _GBCoreBusWrite8(struct mCore* core, uint32_t address, uint8_t value) {
568 struct LR35902Core* cpu = core->cpu;
569 cpu->memory.store8(cpu, address, value);
570}
571
572static void _GBCoreBusWrite16(struct mCore* core, uint32_t address, uint16_t value) {
573 struct LR35902Core* cpu = core->cpu;
574 cpu->memory.store8(cpu, address, value);
575 cpu->memory.store8(cpu, address + 1, value >> 8);
576}
577
578static void _GBCoreBusWrite32(struct mCore* core, uint32_t address, uint32_t value) {
579 struct LR35902Core* cpu = core->cpu;
580 cpu->memory.store8(cpu, address, value);
581 cpu->memory.store8(cpu, address + 1, value >> 8);
582 cpu->memory.store8(cpu, address + 2, value >> 16);
583 cpu->memory.store8(cpu, address + 3, value >> 24);
584}
585
586static uint32_t _GBCoreRawRead8(struct mCore* core, uint32_t address, int segment) {
587 struct LR35902Core* cpu = core->cpu;
588 return GBView8(cpu, address, segment);
589}
590
591static uint32_t _GBCoreRawRead16(struct mCore* core, uint32_t address, int segment) {
592 struct LR35902Core* cpu = core->cpu;
593 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8);
594}
595
596static uint32_t _GBCoreRawRead32(struct mCore* core, uint32_t address, int segment) {
597 struct LR35902Core* cpu = core->cpu;
598 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8) |
599 (GBView8(cpu, address + 2, segment) << 16) | (GBView8(cpu, address + 3, segment) << 24);
600}
601
602static void _GBCoreRawWrite8(struct mCore* core, uint32_t address, int segment, uint8_t value) {
603 struct LR35902Core* cpu = core->cpu;
604 GBPatch8(cpu, address, value, NULL, segment);
605}
606
607static void _GBCoreRawWrite16(struct mCore* core, uint32_t address, int segment, uint16_t value) {
608 struct LR35902Core* cpu = core->cpu;
609 GBPatch8(cpu, address, value, NULL, segment);
610 GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
611}
612
613static void _GBCoreRawWrite32(struct mCore* core, uint32_t address, int segment, uint32_t value) {
614 struct LR35902Core* cpu = core->cpu;
615 GBPatch8(cpu, address, value, NULL, segment);
616 GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
617 GBPatch8(cpu, address + 2, value >> 16, NULL, segment);
618 GBPatch8(cpu, address + 3, value >> 24, NULL, segment);
619}
620
621size_t _GBListMemoryBlocks(const struct mCore* core, const struct mCoreMemoryBlock** blocks) {
622 const struct GB* gb = core->board;
623 switch (gb->model) {
624 case GB_MODEL_DMG:
625 case GB_MODEL_MGB:
626 case GB_MODEL_SGB:
627 case GB_MODEL_SGB2:
628 default:
629 *blocks = _GBMemoryBlocks;
630 return sizeof(_GBMemoryBlocks) / sizeof(*_GBMemoryBlocks);
631 case GB_MODEL_CGB:
632 case GB_MODEL_AGB:
633 *blocks = _GBCMemoryBlocks;
634 return sizeof(_GBCMemoryBlocks) / sizeof(*_GBCMemoryBlocks);
635 }
636}
637
638void* _GBGetMemoryBlock(struct mCore* core, size_t id, size_t* sizeOut) {
639 struct GB* gb = core->board;
640 bool isCgb = gb->model >= GB_MODEL_CGB;
641 switch (id) {
642 default:
643 return NULL;
644 case GB_REGION_CART_BANK0:
645 *sizeOut = gb->memory.romSize;
646 return gb->memory.rom;
647 case GB_REGION_VRAM:
648 *sizeOut = GB_SIZE_WORKING_RAM_BANK0 * (isCgb ? 1 : 2);
649 return gb->video.vram;
650 case GB_REGION_EXTERNAL_RAM:
651 *sizeOut = gb->sramSize;
652 return gb->memory.sram;
653 case GB_REGION_WORKING_RAM_BANK0:
654 *sizeOut = GB_SIZE_VRAM * (isCgb ? 8 : 2);
655 return gb->memory.wram;
656 case GB_BASE_OAM:
657 *sizeOut = GB_SIZE_OAM;
658 return gb->video.oam.raw;
659 case GB_BASE_HRAM:
660 *sizeOut = GB_SIZE_HRAM;
661 return gb->memory.hram;
662 }
663}
664
665#ifdef USE_DEBUGGERS
666static bool _GBCoreSupportsDebuggerType(struct mCore* core, enum mDebuggerType type) {
667 UNUSED(core);
668 switch (type) {
669 case DEBUGGER_CLI:
670 return true;
671 default:
672 return false;
673 }
674}
675
676static struct mDebuggerPlatform* _GBCoreDebuggerPlatform(struct mCore* core) {
677 struct GBCore* gbcore = (struct GBCore*) core;
678 struct GB* gb = core->board;
679 if (!gbcore->debuggerPlatform) {
680 struct LR35902Debugger* platform = (struct LR35902Debugger*) LR35902DebuggerPlatformCreate();
681 if (gb->model >= GB_MODEL_CGB) {
682 platform->segments = _GBCSegments;
683 } else {
684 platform->segments = _GBSegments;
685 }
686 gbcore->debuggerPlatform = &platform->d;
687 }
688 return gbcore->debuggerPlatform;
689}
690
691static struct CLIDebuggerSystem* _GBCoreCliDebuggerSystem(struct mCore* core) {
692 return GBCLIDebuggerCreate(core);
693}
694
695static void _GBCoreAttachDebugger(struct mCore* core, struct mDebugger* debugger) {
696 struct LR35902Core* cpu = core->cpu;
697 if (core->debugger) {
698 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
699 }
700 cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
701 LR35902HotplugAttach(cpu, CPU_COMPONENT_DEBUGGER);
702 core->debugger = debugger;
703}
704
705static void _GBCoreDetachDebugger(struct mCore* core) {
706 struct LR35902Core* cpu = core->cpu;
707 if (core->debugger) {
708 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
709 }
710 cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
711 core->debugger = NULL;
712}
713
714static void _GBCoreLoadSymbols(struct mCore* core, struct VFile* vf) {
715 core->symbolTable = mDebuggerSymbolTableCreate();
716#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
717 if (!vf) {
718 vf = mDirectorySetOpenSuffix(&core->dirs, core->dirs.base, ".sym", O_RDONLY);
719 }
720#endif
721 if (!vf) {
722 return;
723 }
724 GBLoadSymbols(core->symbolTable, vf);
725}
726
727static bool _GBCoreLookupIdentifier(struct mCore* core, const char* name, int32_t* value, int* segment) {
728 UNUSED(core);
729 *segment = -1;
730 int i;
731 for (i = 0; i < REG_MAX; ++i) {
732 const char* reg = GBIORegisterNames[i];
733 if (reg && strcasecmp(reg, name) == 0) {
734 *value = GB_BASE_IO | i;
735 return true;
736 }
737 }
738 return false;
739}
740#endif
741
742static struct mCheatDevice* _GBCoreCheatDevice(struct mCore* core) {
743 struct GBCore* gbcore = (struct GBCore*) core;
744 if (!gbcore->cheatDevice) {
745 gbcore->cheatDevice = GBCheatDeviceCreate();
746 ((struct LR35902Core*) core->cpu)->components[CPU_COMPONENT_CHEAT_DEVICE] = &gbcore->cheatDevice->d;
747 LR35902HotplugAttach(core->cpu, CPU_COMPONENT_CHEAT_DEVICE);
748 gbcore->cheatDevice->p = core;
749 }
750 return gbcore->cheatDevice;
751}
752
753static size_t _GBCoreSavedataClone(struct mCore* core, void** sram) {
754 struct GB* gb = core->board;
755 struct VFile* vf = gb->sramVf;
756 if (vf) {
757 *sram = malloc(vf->size(vf));
758 vf->seek(vf, 0, SEEK_SET);
759 return vf->read(vf, *sram, vf->size(vf));
760 }
761 *sram = malloc(gb->sramSize);
762 memcpy(*sram, gb->memory.sram, gb->sramSize);
763 return gb->sramSize;
764}
765
766static bool _GBCoreSavedataRestore(struct mCore* core, const void* sram, size_t size, bool writeback) {
767 struct GB* gb = core->board;
768 if (!writeback) {
769 struct VFile* vf = VFileMemChunk(sram, size);
770 GBSavedataMask(gb, vf, true);
771 return true;
772 }
773 struct VFile* vf = gb->sramVf;
774 if (vf) {
775 vf->seek(vf, 0, SEEK_SET);
776 return vf->write(vf, sram, size) > 0;
777 }
778 if (size > 0x20000) {
779 size = 0x20000;
780 }
781 GBResizeSram(gb, size);
782 memcpy(gb->memory.sram, sram, size);
783 return true;
784}
785
786static size_t _GBCoreListVideoLayers(const struct mCore* core, const struct mCoreChannelInfo** info) {
787 UNUSED(core);
788 *info = _GBVideoLayers;
789 return sizeof(_GBVideoLayers) / sizeof(*_GBVideoLayers);
790}
791
792static size_t _GBCoreListAudioChannels(const struct mCore* core, const struct mCoreChannelInfo** info) {
793 UNUSED(core);
794 *info = _GBAudioChannels;
795 return sizeof(_GBAudioChannels) / sizeof(*_GBAudioChannels);
796}
797
798static void _GBCoreEnableVideoLayer(struct mCore* core, size_t id, bool enable) {
799 struct GB* gb = core->board;
800 switch (id) {
801 case 0:
802 gb->video.renderer->disableBG = !enable;
803 break;
804 case 1:
805 gb->video.renderer->disableOBJ = !enable;
806 break;
807 case 2:
808 gb->video.renderer->disableWIN = !enable;
809 break;
810 default:
811 break;
812 }
813}
814
815static void _GBCoreEnableAudioChannel(struct mCore* core, size_t id, bool enable) {
816 struct GB* gb = core->board;
817 switch (id) {
818 case 0:
819 case 1:
820 case 2:
821 case 3:
822 gb->audio.forceDisableCh[id] = !enable;
823 break;
824 default:
825 break;
826 }
827}
828
829#ifndef MINIMAL_CORE
830static void _GBCoreStartVideoLog(struct mCore* core, struct mVideoLogContext* context) {
831 struct GBCore* gbcore = (struct GBCore*) core;
832 struct GB* gb = core->board;
833 gbcore->logContext = context;
834
835 int channelId = mVideoLoggerAddChannel(context);
836 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
837 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, false);
838 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, context, channelId);
839 gbcore->proxyRenderer.logger->block = false;
840
841 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, &gbcore->renderer.d);
842 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
843}
844
845static void _GBCoreEndVideoLog(struct mCore* core) {
846 struct GBCore* gbcore = (struct GBCore*) core;
847 struct GB* gb = core->board;
848 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
849 free(gbcore->proxyRenderer.logger);
850 gbcore->proxyRenderer.logger = NULL;
851}
852#endif
853
854struct mCore* GBCoreCreate(void) {
855 struct GBCore* gbcore = malloc(sizeof(*gbcore));
856 struct mCore* core = &gbcore->d;
857 memset(&core->opts, 0, sizeof(core->opts));
858 core->cpu = NULL;
859 core->board = NULL;
860 core->debugger = NULL;
861 core->symbolTable = NULL;
862 core->init = _GBCoreInit;
863 core->deinit = _GBCoreDeinit;
864 core->platform = _GBCorePlatform;
865 core->setSync = _GBCoreSetSync;
866 core->loadConfig = _GBCoreLoadConfig;
867 core->desiredVideoDimensions = _GBCoreDesiredVideoDimensions;
868 core->setVideoBuffer = _GBCoreSetVideoBuffer;
869 core->getPixels = _GBCoreGetPixels;
870 core->putPixels = _GBCorePutPixels;
871 core->getAudioChannel = _GBCoreGetAudioChannel;
872 core->setAudioBufferSize = _GBCoreSetAudioBufferSize;
873 core->getAudioBufferSize = _GBCoreGetAudioBufferSize;
874 core->setAVStream = _GBCoreSetAVStream;
875 core->addCoreCallbacks = _GBCoreAddCoreCallbacks;
876 core->clearCoreCallbacks = _GBCoreClearCoreCallbacks;
877 core->isROM = GBIsROM;
878 core->loadROM = _GBCoreLoadROM;
879 core->loadBIOS = _GBCoreLoadBIOS;
880 core->loadSave = _GBCoreLoadSave;
881 core->loadTemporarySave = _GBCoreLoadTemporarySave;
882 core->loadPatch = _GBCoreLoadPatch;
883 core->unloadROM = _GBCoreUnloadROM;
884 core->checksum = _GBCoreChecksum;
885 core->reset = _GBCoreReset;
886 core->runFrame = _GBCoreRunFrame;
887 core->runLoop = _GBCoreRunLoop;
888 core->step = _GBCoreStep;
889 core->stateSize = _GBCoreStateSize;
890 core->loadState = _GBCoreLoadState;
891 core->saveState = _GBCoreSaveState;
892 core->setKeys = _GBCoreSetKeys;
893 core->addKeys = _GBCoreAddKeys;
894 core->clearKeys = _GBCoreClearKeys;
895 core->frameCounter = _GBCoreFrameCounter;
896 core->frameCycles = _GBCoreFrameCycles;
897 core->frequency = _GBCoreFrequency;
898 core->getGameTitle = _GBCoreGetGameTitle;
899 core->getGameCode = _GBCoreGetGameCode;
900 core->setPeripheral = _GBCoreSetPeripheral;
901 core->busRead8 = _GBCoreBusRead8;
902 core->busRead16 = _GBCoreBusRead16;
903 core->busRead32 = _GBCoreBusRead32;
904 core->busWrite8 = _GBCoreBusWrite8;
905 core->busWrite16 = _GBCoreBusWrite16;
906 core->busWrite32 = _GBCoreBusWrite32;
907 core->rawRead8 = _GBCoreRawRead8;
908 core->rawRead16 = _GBCoreRawRead16;
909 core->rawRead32 = _GBCoreRawRead32;
910 core->rawWrite8 = _GBCoreRawWrite8;
911 core->rawWrite16 = _GBCoreRawWrite16;
912 core->rawWrite32 = _GBCoreRawWrite32;
913 core->listMemoryBlocks = _GBListMemoryBlocks;
914 core->getMemoryBlock = _GBGetMemoryBlock;
915#ifdef USE_DEBUGGERS
916 core->supportsDebuggerType = _GBCoreSupportsDebuggerType;
917 core->debuggerPlatform = _GBCoreDebuggerPlatform;
918 core->cliDebuggerSystem = _GBCoreCliDebuggerSystem;
919 core->attachDebugger = _GBCoreAttachDebugger;
920 core->detachDebugger = _GBCoreDetachDebugger;
921 core->loadSymbols = _GBCoreLoadSymbols;
922 core->lookupIdentifier = _GBCoreLookupIdentifier;
923#endif
924 core->cheatDevice = _GBCoreCheatDevice;
925 core->savedataClone = _GBCoreSavedataClone;
926 core->savedataRestore = _GBCoreSavedataRestore;
927 core->listVideoLayers = _GBCoreListVideoLayers;
928 core->listAudioChannels = _GBCoreListAudioChannels;
929 core->enableVideoLayer = _GBCoreEnableVideoLayer;
930 core->enableAudioChannel = _GBCoreEnableAudioChannel;
931#ifndef MINIMAL_CORE
932 core->startVideoLog = _GBCoreStartVideoLog;
933 core->endVideoLog = _GBCoreEndVideoLog;
934#endif
935 return core;
936}
937
938#ifndef MINIMAL_CORE
939static void _GBVLPStartFrameCallback(void *context) {
940 struct mCore* core = context;
941 struct GBCore* gbcore = (struct GBCore*) core;
942 struct GB* gb = core->board;
943
944 if (!mVideoLoggerRendererRun(gbcore->proxyRenderer.logger, true)) {
945 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
946 mVideoLogContextRewind(gbcore->logContext, core);
947 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
948 }
949}
950
951static bool _GBVLPInit(struct mCore* core) {
952 struct GBCore* gbcore = (struct GBCore*) core;
953 if (!_GBCoreInit(core)) {
954 return false;
955 }
956 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
957 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, true);
958 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, NULL);
959 memset(&gbcore->logCallbacks, 0, sizeof(gbcore->logCallbacks));
960 gbcore->logCallbacks.videoFrameStarted = _GBVLPStartFrameCallback;
961 gbcore->logCallbacks.context = core;
962 core->addCoreCallbacks(core, &gbcore->logCallbacks);
963 return true;
964}
965
966static void _GBVLPDeinit(struct mCore* core) {
967 struct GBCore* gbcore = (struct GBCore*) core;
968 if (gbcore->logContext) {
969 mVideoLogContextDestroy(core, gbcore->logContext);
970 }
971 _GBCoreDeinit(core);
972}
973
974static void _GBVLPReset(struct mCore* core) {
975 struct GBCore* gbcore = (struct GBCore*) core;
976 struct GB* gb = (struct GB*) core->board;
977 if (gb->video.renderer == &gbcore->proxyRenderer.d) {
978 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
979 } else if (gbcore->renderer.outputBuffer) {
980 struct GBVideoRenderer* renderer = &gbcore->renderer.d;
981 GBVideoAssociateRenderer(&gb->video, renderer);
982 }
983
984 LR35902Reset(core->cpu);
985 mVideoLogContextRewind(gbcore->logContext, core);
986 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
987
988 // Make sure CPU loop never spins
989 GBHalt(gb->cpu);
990 gb->memory.ie = 0;
991 gb->memory.ime = false;
992}
993
994static bool _GBVLPLoadROM(struct mCore* core, struct VFile* vf) {
995 struct GBCore* gbcore = (struct GBCore*) core;
996 gbcore->logContext = mVideoLogContextCreate(NULL);
997 if (!mVideoLogContextLoad(gbcore->logContext, vf)) {
998 mVideoLogContextDestroy(core, gbcore->logContext);
999 gbcore->logContext = NULL;
1000 return false;
1001 }
1002 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, gbcore->logContext, 0);
1003 return true;
1004}
1005
1006static bool _GBVLPLoadState(struct mCore* core, const void* buffer) {
1007 struct GB* gb = (struct GB*) core->board;
1008 const struct GBSerializedState* state = buffer;
1009
1010 gb->timing.root = NULL;
1011 gb->model = state->model;
1012
1013 gb->cpu->pc = GB_BASE_HRAM;
1014 gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
1015
1016 GBVideoDeserialize(&gb->video, state);
1017 GBIODeserialize(gb, state);
1018 GBAudioReset(&gb->audio);
1019
1020 // Make sure CPU loop never spins
1021 GBHalt(gb->cpu);
1022 gb->memory.ie = 0;
1023 gb->memory.ime = false;
1024
1025 return true;
1026}
1027
1028static bool _returnTrue(struct VFile* vf) {
1029 UNUSED(vf);
1030 return true;
1031}
1032
1033struct mCore* GBVideoLogPlayerCreate(void) {
1034 struct mCore* core = GBCoreCreate();
1035 core->init = _GBVLPInit;
1036 core->deinit = _GBVLPDeinit;
1037 core->reset = _GBVLPReset;
1038 core->loadROM = _GBVLPLoadROM;
1039 core->loadState = _GBVLPLoadState;
1040 core->isROM = _returnTrue;
1041 return core;
1042}
1043#else
1044struct mCore* GBVideoLogPlayerCreate(void) {
1045 return false;
1046}
1047#endif