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 unsigned width, height;
285 core->desiredVideoDimensions(core, &width, &height);
286 stream->videoDimensionsChanged(stream, width, height);
287 }
288}
289
290static bool _GBCoreLoadROM(struct mCore* core, struct VFile* vf) {
291 return GBLoadROM(core->board, vf);
292}
293
294static bool _GBCoreLoadBIOS(struct mCore* core, struct VFile* vf, int type) {
295 UNUSED(type);
296 GBLoadBIOS(core->board, vf);
297 return true;
298}
299
300static bool _GBCoreLoadSave(struct mCore* core, struct VFile* vf) {
301 return GBLoadSave(core->board, vf);
302}
303
304static bool _GBCoreLoadTemporarySave(struct mCore* core, struct VFile* vf) {
305 struct GB* gb = core->board;
306 GBSavedataMask(gb, vf, false);
307 return true; // TODO: Return a real value
308}
309
310static bool _GBCoreLoadPatch(struct mCore* core, struct VFile* vf) {
311 if (!vf) {
312 return false;
313 }
314 struct Patch patch;
315 if (!loadPatch(vf, &patch)) {
316 return false;
317 }
318 GBApplyPatch(core->board, &patch);
319 return true;
320}
321
322static void _GBCoreUnloadROM(struct mCore* core) {
323 struct GBCore* gbcore = (struct GBCore*) core;
324 struct LR35902Core* cpu = core->cpu;
325 if (gbcore->cheatDevice) {
326 LR35902HotplugDetach(cpu, CPU_COMPONENT_CHEAT_DEVICE);
327 cpu->components[CPU_COMPONENT_CHEAT_DEVICE] = NULL;
328 mCheatDeviceDestroy(gbcore->cheatDevice);
329 gbcore->cheatDevice = NULL;
330 }
331 return GBUnloadROM(core->board);
332}
333
334static void _GBCoreChecksum(const struct mCore* core, void* data, enum mCoreChecksumType type) {
335 struct GB* gb = (struct GB*) core->board;
336 switch (type) {
337 case CHECKSUM_CRC32:
338 memcpy(data, &gb->romCrc32, sizeof(gb->romCrc32));
339 break;
340 }
341 return;
342}
343
344static void _GBCoreReset(struct mCore* core) {
345 struct GBCore* gbcore = (struct GBCore*) core;
346 struct GB* gb = (struct GB*) core->board;
347 if (gbcore->renderer.outputBuffer) {
348 GBVideoAssociateRenderer(&gb->video, &gbcore->renderer.d);
349 }
350
351 if (gb->memory.rom) {
352 struct GBCartridgeOverride override;
353 const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
354 override.headerCrc32 = doCrc32(cart, sizeof(*cart));
355 if (GBOverrideFind(gbcore->overrides, &override)) {
356 GBOverrideApply(gb, &override);
357 }
358 }
359
360 const char* modelGB = mCoreConfigGetValue(&core->config, "gb.model");
361 const char* modelCGB = mCoreConfigGetValue(&core->config, "cgb.model");
362 const char* modelSGB = mCoreConfigGetValue(&core->config, "sgb.model");
363 if (modelGB || modelCGB || modelSGB) {
364 GBDetectModel(gb);
365 if (gb->model == GB_MODEL_DMG && modelGB) {
366 gb->model = GBNameToModel(modelGB);
367 } else if (gb->model == GB_MODEL_CGB && modelCGB) {
368 gb->model = GBNameToModel(modelCGB);
369 } else if (gb->model == GB_MODEL_SGB && modelSGB) {
370 gb->model = GBNameToModel(modelSGB);
371 }
372 }
373
374 int fakeBool;
375 if (mCoreConfigGetIntValue(&core->config, "sgb.borders", &fakeBool)) {
376 gb->video.sgbBorders = fakeBool;
377 }
378
379#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
380 if (!gb->biosVf && core->opts.useBios) {
381 struct VFile* bios = NULL;
382 bool found = false;
383 if (core->opts.bios) {
384 bios = VFileOpen(core->opts.bios, O_RDONLY);
385 if (bios && GBIsBIOS(bios)) {
386 found = true;
387 } else if (bios) {
388 bios->close(bios);
389 bios = NULL;
390 }
391 }
392 if (!found) {
393 GBDetectModel(gb);
394 const char* configPath = NULL;
395
396 switch (gb->model) {
397 case GB_MODEL_DMG:
398 case GB_MODEL_MGB: // TODO
399 configPath = mCoreConfigGetValue(&core->config, "gb.bios");
400 break;
401 case GB_MODEL_SGB:
402 case GB_MODEL_SGB2: // TODO
403 configPath = mCoreConfigGetValue(&core->config, "sgb.bios");
404 break;
405 case GB_MODEL_CGB:
406 case GB_MODEL_AGB:
407 configPath = mCoreConfigGetValue(&core->config, "gbc.bios");
408 break;
409 default:
410 break;
411 };
412 if (configPath) {
413 bios = VFileOpen(configPath, O_RDONLY);
414 }
415 if (bios && GBIsBIOS(bios)) {
416 found = true;
417 } else if (bios) {
418 bios->close(bios);
419 bios = NULL;
420 }
421 }
422 if (!found) {
423 char path[PATH_MAX];
424 mCoreConfigDirectory(path, PATH_MAX);
425 switch (gb->model) {
426 case GB_MODEL_DMG:
427 case GB_MODEL_MGB: // TODO
428 strncat(path, PATH_SEP "gb_bios.bin", PATH_MAX - strlen(path));
429 break;
430 case GB_MODEL_SGB:
431 case GB_MODEL_SGB2: // TODO
432 strncat(path, PATH_SEP "sgb_bios.bin", PATH_MAX - strlen(path));
433 break;
434 case GB_MODEL_CGB:
435 case GB_MODEL_AGB:
436 strncat(path, PATH_SEP "gbc_bios.bin", PATH_MAX - strlen(path));
437 break;
438 default:
439 break;
440 };
441 bios = VFileOpen(path, O_RDONLY);
442 if (bios && GBIsBIOS(bios)) {
443 found = true;
444 } else if (bios) {
445 bios->close(bios);
446 bios = NULL;
447 }
448 }
449 if (bios) {
450 GBLoadBIOS(gb, bios);
451 }
452 }
453#endif
454
455 LR35902Reset(core->cpu);
456
457 if (core->opts.skipBios) {
458 GBSkipBIOS(core->board);
459 }
460}
461
462static void _GBCoreRunFrame(struct mCore* core) {
463 struct GB* gb = core->board;
464 int32_t frameCounter = gb->video.frameCounter;
465 while (gb->video.frameCounter == frameCounter) {
466 LR35902Run(core->cpu);
467 }
468}
469
470static void _GBCoreRunLoop(struct mCore* core) {
471 LR35902Run(core->cpu);
472}
473
474static void _GBCoreStep(struct mCore* core) {
475 struct LR35902Core* cpu = core->cpu;
476 do {
477 LR35902Tick(cpu);
478 } while (cpu->executionState != LR35902_CORE_FETCH);
479}
480
481static size_t _GBCoreStateSize(struct mCore* core) {
482 UNUSED(core);
483 return sizeof(struct GBSerializedState);
484}
485
486static bool _GBCoreLoadState(struct mCore* core, const void* state) {
487 return GBDeserialize(core->board, state);
488}
489
490static bool _GBCoreSaveState(struct mCore* core, void* state) {
491 struct LR35902Core* cpu = core->cpu;
492 while (cpu->executionState != LR35902_CORE_FETCH) {
493 LR35902Tick(cpu);
494 }
495 GBSerialize(core->board, state);
496 return true;
497}
498
499static void _GBCoreSetKeys(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 _GBCoreAddKeys(struct mCore* core, uint32_t keys) {
506 struct GBCore* gbcore = (struct GBCore*) core;
507 gbcore->keys |= keys;
508 GBTestKeypadIRQ(core->board);
509}
510
511static void _GBCoreClearKeys(struct mCore* core, uint32_t keys) {
512 struct GBCore* gbcore = (struct GBCore*) core;
513 gbcore->keys &= ~keys;
514}
515
516static int32_t _GBCoreFrameCounter(const struct mCore* core) {
517 const struct GB* gb = core->board;
518 return gb->video.frameCounter;
519}
520
521static int32_t _GBCoreFrameCycles(const struct mCore* core) {
522 UNUSED(core);
523 return GB_VIDEO_TOTAL_LENGTH;
524}
525
526static int32_t _GBCoreFrequency(const struct mCore* core) {
527 UNUSED(core);
528 // TODO: GB differences
529 return DMG_LR35902_FREQUENCY;
530}
531
532static void _GBCoreGetGameTitle(const struct mCore* core, char* title) {
533 GBGetGameTitle(core->board, title);
534}
535
536static void _GBCoreGetGameCode(const struct mCore* core, char* title) {
537 GBGetGameCode(core->board, title);
538}
539
540static void _GBCoreSetPeripheral(struct mCore* core, int type, void* periph) {
541 struct GB* gb = core->board;
542 switch (type) {
543 case mPERIPH_ROTATION:
544 gb->memory.rotation = periph;
545 break;
546 case mPERIPH_RUMBLE:
547 gb->memory.rumble = periph;
548 break;
549 case mPERIPH_IMAGE_SOURCE:
550 gb->memory.cam = periph;
551 break;
552 default:
553 return;
554 }
555}
556
557static uint32_t _GBCoreBusRead8(struct mCore* core, uint32_t address) {
558 struct LR35902Core* cpu = core->cpu;
559 return cpu->memory.load8(cpu, address);
560}
561
562static uint32_t _GBCoreBusRead16(struct mCore* core, uint32_t address) {
563 struct LR35902Core* cpu = core->cpu;
564 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8);
565}
566
567static uint32_t _GBCoreBusRead32(struct mCore* core, uint32_t address) {
568 struct LR35902Core* cpu = core->cpu;
569 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8) |
570 (cpu->memory.load8(cpu, address + 2) << 16) | (cpu->memory.load8(cpu, address + 3) << 24);
571}
572
573static void _GBCoreBusWrite8(struct mCore* core, uint32_t address, uint8_t value) {
574 struct LR35902Core* cpu = core->cpu;
575 cpu->memory.store8(cpu, address, value);
576}
577
578static void _GBCoreBusWrite16(struct mCore* core, uint32_t address, uint16_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}
583
584static void _GBCoreBusWrite32(struct mCore* core, uint32_t address, uint32_t value) {
585 struct LR35902Core* cpu = core->cpu;
586 cpu->memory.store8(cpu, address, value);
587 cpu->memory.store8(cpu, address + 1, value >> 8);
588 cpu->memory.store8(cpu, address + 2, value >> 16);
589 cpu->memory.store8(cpu, address + 3, value >> 24);
590}
591
592static uint32_t _GBCoreRawRead8(struct mCore* core, uint32_t address, int segment) {
593 struct LR35902Core* cpu = core->cpu;
594 return GBView8(cpu, address, segment);
595}
596
597static uint32_t _GBCoreRawRead16(struct mCore* core, uint32_t address, int segment) {
598 struct LR35902Core* cpu = core->cpu;
599 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8);
600}
601
602static uint32_t _GBCoreRawRead32(struct mCore* core, uint32_t address, int segment) {
603 struct LR35902Core* cpu = core->cpu;
604 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8) |
605 (GBView8(cpu, address + 2, segment) << 16) | (GBView8(cpu, address + 3, segment) << 24);
606}
607
608static void _GBCoreRawWrite8(struct mCore* core, uint32_t address, int segment, uint8_t value) {
609 struct LR35902Core* cpu = core->cpu;
610 GBPatch8(cpu, address, value, NULL, segment);
611}
612
613static void _GBCoreRawWrite16(struct mCore* core, uint32_t address, int segment, uint16_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}
618
619static void _GBCoreRawWrite32(struct mCore* core, uint32_t address, int segment, uint32_t value) {
620 struct LR35902Core* cpu = core->cpu;
621 GBPatch8(cpu, address, value, NULL, segment);
622 GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
623 GBPatch8(cpu, address + 2, value >> 16, NULL, segment);
624 GBPatch8(cpu, address + 3, value >> 24, NULL, segment);
625}
626
627size_t _GBListMemoryBlocks(const struct mCore* core, const struct mCoreMemoryBlock** blocks) {
628 const struct GB* gb = core->board;
629 switch (gb->model) {
630 case GB_MODEL_DMG:
631 case GB_MODEL_MGB:
632 case GB_MODEL_SGB:
633 case GB_MODEL_SGB2:
634 default:
635 *blocks = _GBMemoryBlocks;
636 return sizeof(_GBMemoryBlocks) / sizeof(*_GBMemoryBlocks);
637 case GB_MODEL_CGB:
638 case GB_MODEL_AGB:
639 *blocks = _GBCMemoryBlocks;
640 return sizeof(_GBCMemoryBlocks) / sizeof(*_GBCMemoryBlocks);
641 }
642}
643
644void* _GBGetMemoryBlock(struct mCore* core, size_t id, size_t* sizeOut) {
645 struct GB* gb = core->board;
646 bool isCgb = gb->model >= GB_MODEL_CGB;
647 switch (id) {
648 default:
649 return NULL;
650 case GB_REGION_CART_BANK0:
651 *sizeOut = gb->memory.romSize;
652 return gb->memory.rom;
653 case GB_REGION_VRAM:
654 *sizeOut = GB_SIZE_WORKING_RAM_BANK0 * (isCgb ? 1 : 2);
655 return gb->video.vram;
656 case GB_REGION_EXTERNAL_RAM:
657 *sizeOut = gb->sramSize;
658 return gb->memory.sram;
659 case GB_REGION_WORKING_RAM_BANK0:
660 *sizeOut = GB_SIZE_VRAM * (isCgb ? 8 : 2);
661 return gb->memory.wram;
662 case GB_BASE_OAM:
663 *sizeOut = GB_SIZE_OAM;
664 return gb->video.oam.raw;
665 case GB_BASE_HRAM:
666 *sizeOut = GB_SIZE_HRAM;
667 return gb->memory.hram;
668 }
669}
670
671#ifdef USE_DEBUGGERS
672static bool _GBCoreSupportsDebuggerType(struct mCore* core, enum mDebuggerType type) {
673 UNUSED(core);
674 switch (type) {
675 case DEBUGGER_CLI:
676 return true;
677 default:
678 return false;
679 }
680}
681
682static struct mDebuggerPlatform* _GBCoreDebuggerPlatform(struct mCore* core) {
683 struct GBCore* gbcore = (struct GBCore*) core;
684 struct GB* gb = core->board;
685 if (!gbcore->debuggerPlatform) {
686 struct LR35902Debugger* platform = (struct LR35902Debugger*) LR35902DebuggerPlatformCreate();
687 if (gb->model >= GB_MODEL_CGB) {
688 platform->segments = _GBCSegments;
689 } else {
690 platform->segments = _GBSegments;
691 }
692 gbcore->debuggerPlatform = &platform->d;
693 }
694 return gbcore->debuggerPlatform;
695}
696
697static struct CLIDebuggerSystem* _GBCoreCliDebuggerSystem(struct mCore* core) {
698 return GBCLIDebuggerCreate(core);
699}
700
701static void _GBCoreAttachDebugger(struct mCore* core, struct mDebugger* debugger) {
702 struct LR35902Core* cpu = core->cpu;
703 if (core->debugger) {
704 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
705 }
706 cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
707 LR35902HotplugAttach(cpu, CPU_COMPONENT_DEBUGGER);
708 core->debugger = debugger;
709}
710
711static void _GBCoreDetachDebugger(struct mCore* core) {
712 struct LR35902Core* cpu = core->cpu;
713 if (core->debugger) {
714 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
715 }
716 cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
717 core->debugger = NULL;
718}
719
720static void _GBCoreLoadSymbols(struct mCore* core, struct VFile* vf) {
721 core->symbolTable = mDebuggerSymbolTableCreate();
722#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
723 if (!vf) {
724 vf = mDirectorySetOpenSuffix(&core->dirs, core->dirs.base, ".sym", O_RDONLY);
725 }
726#endif
727 if (!vf) {
728 return;
729 }
730 GBLoadSymbols(core->symbolTable, vf);
731}
732
733static bool _GBCoreLookupIdentifier(struct mCore* core, const char* name, int32_t* value, int* segment) {
734 UNUSED(core);
735 *segment = -1;
736 int i;
737 for (i = 0; i < REG_MAX; ++i) {
738 const char* reg = GBIORegisterNames[i];
739 if (reg && strcasecmp(reg, name) == 0) {
740 *value = GB_BASE_IO | i;
741 return true;
742 }
743 }
744 return false;
745}
746#endif
747
748static struct mCheatDevice* _GBCoreCheatDevice(struct mCore* core) {
749 struct GBCore* gbcore = (struct GBCore*) core;
750 if (!gbcore->cheatDevice) {
751 gbcore->cheatDevice = GBCheatDeviceCreate();
752 ((struct LR35902Core*) core->cpu)->components[CPU_COMPONENT_CHEAT_DEVICE] = &gbcore->cheatDevice->d;
753 LR35902HotplugAttach(core->cpu, CPU_COMPONENT_CHEAT_DEVICE);
754 gbcore->cheatDevice->p = core;
755 }
756 return gbcore->cheatDevice;
757}
758
759static size_t _GBCoreSavedataClone(struct mCore* core, void** sram) {
760 struct GB* gb = core->board;
761 struct VFile* vf = gb->sramVf;
762 if (vf) {
763 *sram = malloc(vf->size(vf));
764 vf->seek(vf, 0, SEEK_SET);
765 return vf->read(vf, *sram, vf->size(vf));
766 }
767 *sram = malloc(gb->sramSize);
768 memcpy(*sram, gb->memory.sram, gb->sramSize);
769 return gb->sramSize;
770}
771
772static bool _GBCoreSavedataRestore(struct mCore* core, const void* sram, size_t size, bool writeback) {
773 struct GB* gb = core->board;
774 if (!writeback) {
775 struct VFile* vf = VFileMemChunk(sram, size);
776 GBSavedataMask(gb, vf, true);
777 return true;
778 }
779 struct VFile* vf = gb->sramVf;
780 if (vf) {
781 vf->seek(vf, 0, SEEK_SET);
782 return vf->write(vf, sram, size) > 0;
783 }
784 if (size > 0x20000) {
785 size = 0x20000;
786 }
787 GBResizeSram(gb, size);
788 memcpy(gb->memory.sram, sram, size);
789 return true;
790}
791
792static size_t _GBCoreListVideoLayers(const struct mCore* core, const struct mCoreChannelInfo** info) {
793 UNUSED(core);
794 *info = _GBVideoLayers;
795 return sizeof(_GBVideoLayers) / sizeof(*_GBVideoLayers);
796}
797
798static size_t _GBCoreListAudioChannels(const struct mCore* core, const struct mCoreChannelInfo** info) {
799 UNUSED(core);
800 *info = _GBAudioChannels;
801 return sizeof(_GBAudioChannels) / sizeof(*_GBAudioChannels);
802}
803
804static void _GBCoreEnableVideoLayer(struct mCore* core, size_t id, bool enable) {
805 struct GB* gb = core->board;
806 switch (id) {
807 case 0:
808 gb->video.renderer->disableBG = !enable;
809 break;
810 case 1:
811 gb->video.renderer->disableOBJ = !enable;
812 break;
813 case 2:
814 gb->video.renderer->disableWIN = !enable;
815 break;
816 default:
817 break;
818 }
819}
820
821static void _GBCoreEnableAudioChannel(struct mCore* core, size_t id, bool enable) {
822 struct GB* gb = core->board;
823 switch (id) {
824 case 0:
825 case 1:
826 case 2:
827 case 3:
828 gb->audio.forceDisableCh[id] = !enable;
829 break;
830 default:
831 break;
832 }
833}
834
835#ifndef MINIMAL_CORE
836static void _GBCoreStartVideoLog(struct mCore* core, struct mVideoLogContext* context) {
837 struct GBCore* gbcore = (struct GBCore*) core;
838 struct GB* gb = core->board;
839 gbcore->logContext = context;
840
841 int channelId = mVideoLoggerAddChannel(context);
842 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
843 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, false);
844 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, context, channelId);
845 gbcore->proxyRenderer.logger->block = false;
846
847 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, &gbcore->renderer.d);
848 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
849}
850
851static void _GBCoreEndVideoLog(struct mCore* core) {
852 struct GBCore* gbcore = (struct GBCore*) core;
853 struct GB* gb = core->board;
854 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
855 free(gbcore->proxyRenderer.logger);
856 gbcore->proxyRenderer.logger = NULL;
857}
858#endif
859
860struct mCore* GBCoreCreate(void) {
861 struct GBCore* gbcore = malloc(sizeof(*gbcore));
862 struct mCore* core = &gbcore->d;
863 memset(&core->opts, 0, sizeof(core->opts));
864 core->cpu = NULL;
865 core->board = NULL;
866 core->debugger = NULL;
867 core->symbolTable = NULL;
868 core->init = _GBCoreInit;
869 core->deinit = _GBCoreDeinit;
870 core->platform = _GBCorePlatform;
871 core->setSync = _GBCoreSetSync;
872 core->loadConfig = _GBCoreLoadConfig;
873 core->desiredVideoDimensions = _GBCoreDesiredVideoDimensions;
874 core->setVideoBuffer = _GBCoreSetVideoBuffer;
875 core->getPixels = _GBCoreGetPixels;
876 core->putPixels = _GBCorePutPixels;
877 core->getAudioChannel = _GBCoreGetAudioChannel;
878 core->setAudioBufferSize = _GBCoreSetAudioBufferSize;
879 core->getAudioBufferSize = _GBCoreGetAudioBufferSize;
880 core->setAVStream = _GBCoreSetAVStream;
881 core->addCoreCallbacks = _GBCoreAddCoreCallbacks;
882 core->clearCoreCallbacks = _GBCoreClearCoreCallbacks;
883 core->isROM = GBIsROM;
884 core->loadROM = _GBCoreLoadROM;
885 core->loadBIOS = _GBCoreLoadBIOS;
886 core->loadSave = _GBCoreLoadSave;
887 core->loadTemporarySave = _GBCoreLoadTemporarySave;
888 core->loadPatch = _GBCoreLoadPatch;
889 core->unloadROM = _GBCoreUnloadROM;
890 core->checksum = _GBCoreChecksum;
891 core->reset = _GBCoreReset;
892 core->runFrame = _GBCoreRunFrame;
893 core->runLoop = _GBCoreRunLoop;
894 core->step = _GBCoreStep;
895 core->stateSize = _GBCoreStateSize;
896 core->loadState = _GBCoreLoadState;
897 core->saveState = _GBCoreSaveState;
898 core->setKeys = _GBCoreSetKeys;
899 core->addKeys = _GBCoreAddKeys;
900 core->clearKeys = _GBCoreClearKeys;
901 core->frameCounter = _GBCoreFrameCounter;
902 core->frameCycles = _GBCoreFrameCycles;
903 core->frequency = _GBCoreFrequency;
904 core->getGameTitle = _GBCoreGetGameTitle;
905 core->getGameCode = _GBCoreGetGameCode;
906 core->setPeripheral = _GBCoreSetPeripheral;
907 core->busRead8 = _GBCoreBusRead8;
908 core->busRead16 = _GBCoreBusRead16;
909 core->busRead32 = _GBCoreBusRead32;
910 core->busWrite8 = _GBCoreBusWrite8;
911 core->busWrite16 = _GBCoreBusWrite16;
912 core->busWrite32 = _GBCoreBusWrite32;
913 core->rawRead8 = _GBCoreRawRead8;
914 core->rawRead16 = _GBCoreRawRead16;
915 core->rawRead32 = _GBCoreRawRead32;
916 core->rawWrite8 = _GBCoreRawWrite8;
917 core->rawWrite16 = _GBCoreRawWrite16;
918 core->rawWrite32 = _GBCoreRawWrite32;
919 core->listMemoryBlocks = _GBListMemoryBlocks;
920 core->getMemoryBlock = _GBGetMemoryBlock;
921#ifdef USE_DEBUGGERS
922 core->supportsDebuggerType = _GBCoreSupportsDebuggerType;
923 core->debuggerPlatform = _GBCoreDebuggerPlatform;
924 core->cliDebuggerSystem = _GBCoreCliDebuggerSystem;
925 core->attachDebugger = _GBCoreAttachDebugger;
926 core->detachDebugger = _GBCoreDetachDebugger;
927 core->loadSymbols = _GBCoreLoadSymbols;
928 core->lookupIdentifier = _GBCoreLookupIdentifier;
929#endif
930 core->cheatDevice = _GBCoreCheatDevice;
931 core->savedataClone = _GBCoreSavedataClone;
932 core->savedataRestore = _GBCoreSavedataRestore;
933 core->listVideoLayers = _GBCoreListVideoLayers;
934 core->listAudioChannels = _GBCoreListAudioChannels;
935 core->enableVideoLayer = _GBCoreEnableVideoLayer;
936 core->enableAudioChannel = _GBCoreEnableAudioChannel;
937#ifndef MINIMAL_CORE
938 core->startVideoLog = _GBCoreStartVideoLog;
939 core->endVideoLog = _GBCoreEndVideoLog;
940#endif
941 return core;
942}
943
944#ifndef MINIMAL_CORE
945static void _GBVLPStartFrameCallback(void *context) {
946 struct mCore* core = context;
947 struct GBCore* gbcore = (struct GBCore*) core;
948 struct GB* gb = core->board;
949
950 if (!mVideoLoggerRendererRun(gbcore->proxyRenderer.logger, true)) {
951 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
952 mVideoLogContextRewind(gbcore->logContext, core);
953 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
954 }
955}
956
957static bool _GBVLPInit(struct mCore* core) {
958 struct GBCore* gbcore = (struct GBCore*) core;
959 if (!_GBCoreInit(core)) {
960 return false;
961 }
962 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
963 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, true);
964 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, NULL);
965 memset(&gbcore->logCallbacks, 0, sizeof(gbcore->logCallbacks));
966 gbcore->logCallbacks.videoFrameStarted = _GBVLPStartFrameCallback;
967 gbcore->logCallbacks.context = core;
968 core->addCoreCallbacks(core, &gbcore->logCallbacks);
969 return true;
970}
971
972static void _GBVLPDeinit(struct mCore* core) {
973 struct GBCore* gbcore = (struct GBCore*) core;
974 if (gbcore->logContext) {
975 mVideoLogContextDestroy(core, gbcore->logContext);
976 }
977 _GBCoreDeinit(core);
978}
979
980static void _GBVLPReset(struct mCore* core) {
981 struct GBCore* gbcore = (struct GBCore*) core;
982 struct GB* gb = (struct GB*) core->board;
983 if (gb->video.renderer == &gbcore->proxyRenderer.d) {
984 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
985 } else if (gbcore->renderer.outputBuffer) {
986 struct GBVideoRenderer* renderer = &gbcore->renderer.d;
987 GBVideoAssociateRenderer(&gb->video, renderer);
988 }
989
990 LR35902Reset(core->cpu);
991 mVideoLogContextRewind(gbcore->logContext, core);
992 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
993
994 // Make sure CPU loop never spins
995 GBHalt(gb->cpu);
996 gb->memory.ie = 0;
997 gb->memory.ime = false;
998}
999
1000static bool _GBVLPLoadROM(struct mCore* core, struct VFile* vf) {
1001 struct GBCore* gbcore = (struct GBCore*) core;
1002 gbcore->logContext = mVideoLogContextCreate(NULL);
1003 if (!mVideoLogContextLoad(gbcore->logContext, vf)) {
1004 mVideoLogContextDestroy(core, gbcore->logContext);
1005 gbcore->logContext = NULL;
1006 return false;
1007 }
1008 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, gbcore->logContext, 0);
1009 return true;
1010}
1011
1012static bool _GBVLPLoadState(struct mCore* core, const void* buffer) {
1013 struct GB* gb = (struct GB*) core->board;
1014 const struct GBSerializedState* state = buffer;
1015
1016 gb->timing.root = NULL;
1017 gb->model = state->model;
1018
1019 gb->cpu->pc = GB_BASE_HRAM;
1020 gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
1021
1022 GBVideoDeserialize(&gb->video, state);
1023 GBIODeserialize(gb, state);
1024 GBAudioReset(&gb->audio);
1025
1026 // Make sure CPU loop never spins
1027 GBHalt(gb->cpu);
1028 gb->memory.ie = 0;
1029 gb->memory.ime = false;
1030
1031 return true;
1032}
1033
1034static bool _returnTrue(struct VFile* vf) {
1035 UNUSED(vf);
1036 return true;
1037}
1038
1039struct mCore* GBVideoLogPlayerCreate(void) {
1040 struct mCore* core = GBCoreCreate();
1041 core->init = _GBVLPInit;
1042 core->deinit = _GBVLPDeinit;
1043 core->reset = _GBVLPReset;
1044 core->loadROM = _GBVLPLoadROM;
1045 core->loadState = _GBVLPLoadState;
1046 core->isROM = _returnTrue;
1047 return core;
1048}
1049#else
1050struct mCore* GBVideoLogPlayerCreate(void) {
1051 return false;
1052}
1053#endif