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 if (core->opts.skipBios) {
456 GBSkipBIOS(core->board);
457 }
458}
459
460static void _GBCoreRunFrame(struct mCore* core) {
461 struct GB* gb = core->board;
462 int32_t frameCounter = gb->video.frameCounter;
463 while (gb->video.frameCounter == frameCounter) {
464 LR35902Run(core->cpu);
465 }
466}
467
468static void _GBCoreRunLoop(struct mCore* core) {
469 LR35902Run(core->cpu);
470}
471
472static void _GBCoreStep(struct mCore* core) {
473 struct LR35902Core* cpu = core->cpu;
474 do {
475 LR35902Tick(cpu);
476 } while (cpu->executionState != LR35902_CORE_FETCH);
477}
478
479static size_t _GBCoreStateSize(struct mCore* core) {
480 UNUSED(core);
481 return sizeof(struct GBSerializedState);
482}
483
484static bool _GBCoreLoadState(struct mCore* core, const void* state) {
485 return GBDeserialize(core->board, state);
486}
487
488static bool _GBCoreSaveState(struct mCore* core, void* state) {
489 struct LR35902Core* cpu = core->cpu;
490 while (cpu->executionState != LR35902_CORE_FETCH) {
491 LR35902Tick(cpu);
492 }
493 GBSerialize(core->board, state);
494 return true;
495}
496
497static void _GBCoreSetKeys(struct mCore* core, uint32_t keys) {
498 struct GBCore* gbcore = (struct GBCore*) core;
499 gbcore->keys = keys;
500 GBTestKeypadIRQ(core->board);
501}
502
503static void _GBCoreAddKeys(struct mCore* core, uint32_t keys) {
504 struct GBCore* gbcore = (struct GBCore*) core;
505 gbcore->keys |= keys;
506 GBTestKeypadIRQ(core->board);
507}
508
509static void _GBCoreClearKeys(struct mCore* core, uint32_t keys) {
510 struct GBCore* gbcore = (struct GBCore*) core;
511 gbcore->keys &= ~keys;
512}
513
514static int32_t _GBCoreFrameCounter(const struct mCore* core) {
515 const struct GB* gb = core->board;
516 return gb->video.frameCounter;
517}
518
519static int32_t _GBCoreFrameCycles(const struct mCore* core) {
520 UNUSED(core);
521 return GB_VIDEO_TOTAL_LENGTH;
522}
523
524static int32_t _GBCoreFrequency(const struct mCore* core) {
525 UNUSED(core);
526 // TODO: GB differences
527 return DMG_LR35902_FREQUENCY;
528}
529
530static void _GBCoreGetGameTitle(const struct mCore* core, char* title) {
531 GBGetGameTitle(core->board, title);
532}
533
534static void _GBCoreGetGameCode(const struct mCore* core, char* title) {
535 GBGetGameCode(core->board, title);
536}
537
538static void _GBCoreSetPeripheral(struct mCore* core, int type, void* periph) {
539 struct GB* gb = core->board;
540 switch (type) {
541 case mPERIPH_ROTATION:
542 gb->memory.rotation = periph;
543 break;
544 case mPERIPH_RUMBLE:
545 gb->memory.rumble = periph;
546 break;
547 case mPERIPH_IMAGE_SOURCE:
548 gb->memory.cam = periph;
549 break;
550 default:
551 return;
552 }
553}
554
555static uint32_t _GBCoreBusRead8(struct mCore* core, uint32_t address) {
556 struct LR35902Core* cpu = core->cpu;
557 return cpu->memory.load8(cpu, address);
558}
559
560static uint32_t _GBCoreBusRead16(struct mCore* core, uint32_t address) {
561 struct LR35902Core* cpu = core->cpu;
562 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8);
563}
564
565static uint32_t _GBCoreBusRead32(struct mCore* core, uint32_t address) {
566 struct LR35902Core* cpu = core->cpu;
567 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8) |
568 (cpu->memory.load8(cpu, address + 2) << 16) | (cpu->memory.load8(cpu, address + 3) << 24);
569}
570
571static void _GBCoreBusWrite8(struct mCore* core, uint32_t address, uint8_t value) {
572 struct LR35902Core* cpu = core->cpu;
573 cpu->memory.store8(cpu, address, value);
574}
575
576static void _GBCoreBusWrite16(struct mCore* core, uint32_t address, uint16_t value) {
577 struct LR35902Core* cpu = core->cpu;
578 cpu->memory.store8(cpu, address, value);
579 cpu->memory.store8(cpu, address + 1, value >> 8);
580}
581
582static void _GBCoreBusWrite32(struct mCore* core, uint32_t address, uint32_t value) {
583 struct LR35902Core* cpu = core->cpu;
584 cpu->memory.store8(cpu, address, value);
585 cpu->memory.store8(cpu, address + 1, value >> 8);
586 cpu->memory.store8(cpu, address + 2, value >> 16);
587 cpu->memory.store8(cpu, address + 3, value >> 24);
588}
589
590static uint32_t _GBCoreRawRead8(struct mCore* core, uint32_t address, int segment) {
591 struct LR35902Core* cpu = core->cpu;
592 return GBView8(cpu, address, segment);
593}
594
595static uint32_t _GBCoreRawRead16(struct mCore* core, uint32_t address, int segment) {
596 struct LR35902Core* cpu = core->cpu;
597 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8);
598}
599
600static uint32_t _GBCoreRawRead32(struct mCore* core, uint32_t address, int segment) {
601 struct LR35902Core* cpu = core->cpu;
602 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8) |
603 (GBView8(cpu, address + 2, segment) << 16) | (GBView8(cpu, address + 3, segment) << 24);
604}
605
606static void _GBCoreRawWrite8(struct mCore* core, uint32_t address, int segment, uint8_t value) {
607 struct LR35902Core* cpu = core->cpu;
608 GBPatch8(cpu, address, value, NULL, segment);
609}
610
611static void _GBCoreRawWrite16(struct mCore* core, uint32_t address, int segment, uint16_t value) {
612 struct LR35902Core* cpu = core->cpu;
613 GBPatch8(cpu, address, value, NULL, segment);
614 GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
615}
616
617static void _GBCoreRawWrite32(struct mCore* core, uint32_t address, int segment, uint32_t value) {
618 struct LR35902Core* cpu = core->cpu;
619 GBPatch8(cpu, address, value, NULL, segment);
620 GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
621 GBPatch8(cpu, address + 2, value >> 16, NULL, segment);
622 GBPatch8(cpu, address + 3, value >> 24, NULL, segment);
623}
624
625size_t _GBListMemoryBlocks(const struct mCore* core, const struct mCoreMemoryBlock** blocks) {
626 const struct GB* gb = core->board;
627 switch (gb->model) {
628 case GB_MODEL_DMG:
629 case GB_MODEL_MGB:
630 case GB_MODEL_SGB:
631 case GB_MODEL_SGB2:
632 default:
633 *blocks = _GBMemoryBlocks;
634 return sizeof(_GBMemoryBlocks) / sizeof(*_GBMemoryBlocks);
635 case GB_MODEL_CGB:
636 case GB_MODEL_AGB:
637 *blocks = _GBCMemoryBlocks;
638 return sizeof(_GBCMemoryBlocks) / sizeof(*_GBCMemoryBlocks);
639 }
640}
641
642void* _GBGetMemoryBlock(struct mCore* core, size_t id, size_t* sizeOut) {
643 struct GB* gb = core->board;
644 bool isCgb = gb->model >= GB_MODEL_CGB;
645 switch (id) {
646 default:
647 return NULL;
648 case GB_REGION_CART_BANK0:
649 *sizeOut = gb->memory.romSize;
650 return gb->memory.rom;
651 case GB_REGION_VRAM:
652 *sizeOut = GB_SIZE_WORKING_RAM_BANK0 * (isCgb ? 1 : 2);
653 return gb->video.vram;
654 case GB_REGION_EXTERNAL_RAM:
655 *sizeOut = gb->sramSize;
656 return gb->memory.sram;
657 case GB_REGION_WORKING_RAM_BANK0:
658 *sizeOut = GB_SIZE_VRAM * (isCgb ? 8 : 2);
659 return gb->memory.wram;
660 case GB_BASE_OAM:
661 *sizeOut = GB_SIZE_OAM;
662 return gb->video.oam.raw;
663 case GB_BASE_HRAM:
664 *sizeOut = GB_SIZE_HRAM;
665 return gb->memory.hram;
666 }
667}
668
669#ifdef USE_DEBUGGERS
670static bool _GBCoreSupportsDebuggerType(struct mCore* core, enum mDebuggerType type) {
671 UNUSED(core);
672 switch (type) {
673 case DEBUGGER_CLI:
674 return true;
675 default:
676 return false;
677 }
678}
679
680static struct mDebuggerPlatform* _GBCoreDebuggerPlatform(struct mCore* core) {
681 struct GBCore* gbcore = (struct GBCore*) core;
682 struct GB* gb = core->board;
683 if (!gbcore->debuggerPlatform) {
684 struct LR35902Debugger* platform = (struct LR35902Debugger*) LR35902DebuggerPlatformCreate();
685 if (gb->model >= GB_MODEL_CGB) {
686 platform->segments = _GBCSegments;
687 } else {
688 platform->segments = _GBSegments;
689 }
690 gbcore->debuggerPlatform = &platform->d;
691 }
692 return gbcore->debuggerPlatform;
693}
694
695static struct CLIDebuggerSystem* _GBCoreCliDebuggerSystem(struct mCore* core) {
696 return GBCLIDebuggerCreate(core);
697}
698
699static void _GBCoreAttachDebugger(struct mCore* core, struct mDebugger* debugger) {
700 struct LR35902Core* cpu = core->cpu;
701 if (core->debugger) {
702 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
703 }
704 cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
705 LR35902HotplugAttach(cpu, CPU_COMPONENT_DEBUGGER);
706 core->debugger = debugger;
707}
708
709static void _GBCoreDetachDebugger(struct mCore* core) {
710 struct LR35902Core* cpu = core->cpu;
711 if (core->debugger) {
712 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
713 }
714 cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
715 core->debugger = NULL;
716}
717
718static void _GBCoreLoadSymbols(struct mCore* core, struct VFile* vf) {
719 core->symbolTable = mDebuggerSymbolTableCreate();
720#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
721 if (!vf) {
722 vf = mDirectorySetOpenSuffix(&core->dirs, core->dirs.base, ".sym", O_RDONLY);
723 }
724#endif
725 if (!vf) {
726 return;
727 }
728 GBLoadSymbols(core->symbolTable, vf);
729}
730
731static bool _GBCoreLookupIdentifier(struct mCore* core, const char* name, int32_t* value, int* segment) {
732 UNUSED(core);
733 *segment = -1;
734 int i;
735 for (i = 0; i < REG_MAX; ++i) {
736 const char* reg = GBIORegisterNames[i];
737 if (reg && strcasecmp(reg, name) == 0) {
738 *value = GB_BASE_IO | i;
739 return true;
740 }
741 }
742 return false;
743}
744#endif
745
746static struct mCheatDevice* _GBCoreCheatDevice(struct mCore* core) {
747 struct GBCore* gbcore = (struct GBCore*) core;
748 if (!gbcore->cheatDevice) {
749 gbcore->cheatDevice = GBCheatDeviceCreate();
750 ((struct LR35902Core*) core->cpu)->components[CPU_COMPONENT_CHEAT_DEVICE] = &gbcore->cheatDevice->d;
751 LR35902HotplugAttach(core->cpu, CPU_COMPONENT_CHEAT_DEVICE);
752 gbcore->cheatDevice->p = core;
753 }
754 return gbcore->cheatDevice;
755}
756
757static size_t _GBCoreSavedataClone(struct mCore* core, void** sram) {
758 struct GB* gb = core->board;
759 struct VFile* vf = gb->sramVf;
760 if (vf) {
761 *sram = malloc(vf->size(vf));
762 vf->seek(vf, 0, SEEK_SET);
763 return vf->read(vf, *sram, vf->size(vf));
764 }
765 *sram = malloc(gb->sramSize);
766 memcpy(*sram, gb->memory.sram, gb->sramSize);
767 return gb->sramSize;
768}
769
770static bool _GBCoreSavedataRestore(struct mCore* core, const void* sram, size_t size, bool writeback) {
771 struct GB* gb = core->board;
772 if (!writeback) {
773 struct VFile* vf = VFileMemChunk(sram, size);
774 GBSavedataMask(gb, vf, true);
775 return true;
776 }
777 struct VFile* vf = gb->sramVf;
778 if (vf) {
779 vf->seek(vf, 0, SEEK_SET);
780 return vf->write(vf, sram, size) > 0;
781 }
782 if (size > 0x20000) {
783 size = 0x20000;
784 }
785 GBResizeSram(gb, size);
786 memcpy(gb->memory.sram, sram, size);
787 return true;
788}
789
790static size_t _GBCoreListVideoLayers(const struct mCore* core, const struct mCoreChannelInfo** info) {
791 UNUSED(core);
792 *info = _GBVideoLayers;
793 return sizeof(_GBVideoLayers) / sizeof(*_GBVideoLayers);
794}
795
796static size_t _GBCoreListAudioChannels(const struct mCore* core, const struct mCoreChannelInfo** info) {
797 UNUSED(core);
798 *info = _GBAudioChannels;
799 return sizeof(_GBAudioChannels) / sizeof(*_GBAudioChannels);
800}
801
802static void _GBCoreEnableVideoLayer(struct mCore* core, size_t id, bool enable) {
803 struct GB* gb = core->board;
804 switch (id) {
805 case 0:
806 gb->video.renderer->disableBG = !enable;
807 break;
808 case 1:
809 gb->video.renderer->disableOBJ = !enable;
810 break;
811 case 2:
812 gb->video.renderer->disableWIN = !enable;
813 break;
814 default:
815 break;
816 }
817}
818
819static void _GBCoreEnableAudioChannel(struct mCore* core, size_t id, bool enable) {
820 struct GB* gb = core->board;
821 switch (id) {
822 case 0:
823 case 1:
824 case 2:
825 case 3:
826 gb->audio.forceDisableCh[id] = !enable;
827 break;
828 default:
829 break;
830 }
831}
832
833#ifndef MINIMAL_CORE
834static void _GBCoreStartVideoLog(struct mCore* core, struct mVideoLogContext* context) {
835 struct GBCore* gbcore = (struct GBCore*) core;
836 struct GB* gb = core->board;
837 gbcore->logContext = context;
838
839 int channelId = mVideoLoggerAddChannel(context);
840 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
841 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, false);
842 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, context, channelId);
843 gbcore->proxyRenderer.logger->block = false;
844
845 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, &gbcore->renderer.d);
846 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
847}
848
849static void _GBCoreEndVideoLog(struct mCore* core) {
850 struct GBCore* gbcore = (struct GBCore*) core;
851 struct GB* gb = core->board;
852 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
853 free(gbcore->proxyRenderer.logger);
854 gbcore->proxyRenderer.logger = NULL;
855}
856#endif
857
858struct mCore* GBCoreCreate(void) {
859 struct GBCore* gbcore = malloc(sizeof(*gbcore));
860 struct mCore* core = &gbcore->d;
861 memset(&core->opts, 0, sizeof(core->opts));
862 core->cpu = NULL;
863 core->board = NULL;
864 core->debugger = NULL;
865 core->symbolTable = NULL;
866 core->init = _GBCoreInit;
867 core->deinit = _GBCoreDeinit;
868 core->platform = _GBCorePlatform;
869 core->setSync = _GBCoreSetSync;
870 core->loadConfig = _GBCoreLoadConfig;
871 core->desiredVideoDimensions = _GBCoreDesiredVideoDimensions;
872 core->setVideoBuffer = _GBCoreSetVideoBuffer;
873 core->getPixels = _GBCoreGetPixels;
874 core->putPixels = _GBCorePutPixels;
875 core->getAudioChannel = _GBCoreGetAudioChannel;
876 core->setAudioBufferSize = _GBCoreSetAudioBufferSize;
877 core->getAudioBufferSize = _GBCoreGetAudioBufferSize;
878 core->setAVStream = _GBCoreSetAVStream;
879 core->addCoreCallbacks = _GBCoreAddCoreCallbacks;
880 core->clearCoreCallbacks = _GBCoreClearCoreCallbacks;
881 core->isROM = GBIsROM;
882 core->loadROM = _GBCoreLoadROM;
883 core->loadBIOS = _GBCoreLoadBIOS;
884 core->loadSave = _GBCoreLoadSave;
885 core->loadTemporarySave = _GBCoreLoadTemporarySave;
886 core->loadPatch = _GBCoreLoadPatch;
887 core->unloadROM = _GBCoreUnloadROM;
888 core->checksum = _GBCoreChecksum;
889 core->reset = _GBCoreReset;
890 core->runFrame = _GBCoreRunFrame;
891 core->runLoop = _GBCoreRunLoop;
892 core->step = _GBCoreStep;
893 core->stateSize = _GBCoreStateSize;
894 core->loadState = _GBCoreLoadState;
895 core->saveState = _GBCoreSaveState;
896 core->setKeys = _GBCoreSetKeys;
897 core->addKeys = _GBCoreAddKeys;
898 core->clearKeys = _GBCoreClearKeys;
899 core->frameCounter = _GBCoreFrameCounter;
900 core->frameCycles = _GBCoreFrameCycles;
901 core->frequency = _GBCoreFrequency;
902 core->getGameTitle = _GBCoreGetGameTitle;
903 core->getGameCode = _GBCoreGetGameCode;
904 core->setPeripheral = _GBCoreSetPeripheral;
905 core->busRead8 = _GBCoreBusRead8;
906 core->busRead16 = _GBCoreBusRead16;
907 core->busRead32 = _GBCoreBusRead32;
908 core->busWrite8 = _GBCoreBusWrite8;
909 core->busWrite16 = _GBCoreBusWrite16;
910 core->busWrite32 = _GBCoreBusWrite32;
911 core->rawRead8 = _GBCoreRawRead8;
912 core->rawRead16 = _GBCoreRawRead16;
913 core->rawRead32 = _GBCoreRawRead32;
914 core->rawWrite8 = _GBCoreRawWrite8;
915 core->rawWrite16 = _GBCoreRawWrite16;
916 core->rawWrite32 = _GBCoreRawWrite32;
917 core->listMemoryBlocks = _GBListMemoryBlocks;
918 core->getMemoryBlock = _GBGetMemoryBlock;
919#ifdef USE_DEBUGGERS
920 core->supportsDebuggerType = _GBCoreSupportsDebuggerType;
921 core->debuggerPlatform = _GBCoreDebuggerPlatform;
922 core->cliDebuggerSystem = _GBCoreCliDebuggerSystem;
923 core->attachDebugger = _GBCoreAttachDebugger;
924 core->detachDebugger = _GBCoreDetachDebugger;
925 core->loadSymbols = _GBCoreLoadSymbols;
926 core->lookupIdentifier = _GBCoreLookupIdentifier;
927#endif
928 core->cheatDevice = _GBCoreCheatDevice;
929 core->savedataClone = _GBCoreSavedataClone;
930 core->savedataRestore = _GBCoreSavedataRestore;
931 core->listVideoLayers = _GBCoreListVideoLayers;
932 core->listAudioChannels = _GBCoreListAudioChannels;
933 core->enableVideoLayer = _GBCoreEnableVideoLayer;
934 core->enableAudioChannel = _GBCoreEnableAudioChannel;
935#ifndef MINIMAL_CORE
936 core->startVideoLog = _GBCoreStartVideoLog;
937 core->endVideoLog = _GBCoreEndVideoLog;
938#endif
939 return core;
940}
941
942#ifndef MINIMAL_CORE
943static void _GBVLPStartFrameCallback(void *context) {
944 struct mCore* core = context;
945 struct GBCore* gbcore = (struct GBCore*) core;
946 struct GB* gb = core->board;
947
948 if (!mVideoLoggerRendererRun(gbcore->proxyRenderer.logger, true)) {
949 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
950 mVideoLogContextRewind(gbcore->logContext, core);
951 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
952 }
953}
954
955static bool _GBVLPInit(struct mCore* core) {
956 struct GBCore* gbcore = (struct GBCore*) core;
957 if (!_GBCoreInit(core)) {
958 return false;
959 }
960 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
961 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, true);
962 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, NULL);
963 memset(&gbcore->logCallbacks, 0, sizeof(gbcore->logCallbacks));
964 gbcore->logCallbacks.videoFrameStarted = _GBVLPStartFrameCallback;
965 gbcore->logCallbacks.context = core;
966 core->addCoreCallbacks(core, &gbcore->logCallbacks);
967 return true;
968}
969
970static void _GBVLPDeinit(struct mCore* core) {
971 struct GBCore* gbcore = (struct GBCore*) core;
972 if (gbcore->logContext) {
973 mVideoLogContextDestroy(core, gbcore->logContext);
974 }
975 _GBCoreDeinit(core);
976}
977
978static void _GBVLPReset(struct mCore* core) {
979 struct GBCore* gbcore = (struct GBCore*) core;
980 struct GB* gb = (struct GB*) core->board;
981 if (gb->video.renderer == &gbcore->proxyRenderer.d) {
982 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
983 } else if (gbcore->renderer.outputBuffer) {
984 struct GBVideoRenderer* renderer = &gbcore->renderer.d;
985 GBVideoAssociateRenderer(&gb->video, renderer);
986 }
987
988 LR35902Reset(core->cpu);
989 mVideoLogContextRewind(gbcore->logContext, core);
990 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
991
992 // Make sure CPU loop never spins
993 GBHalt(gb->cpu);
994 gb->memory.ie = 0;
995 gb->memory.ime = false;
996}
997
998static bool _GBVLPLoadROM(struct mCore* core, struct VFile* vf) {
999 struct GBCore* gbcore = (struct GBCore*) core;
1000 gbcore->logContext = mVideoLogContextCreate(NULL);
1001 if (!mVideoLogContextLoad(gbcore->logContext, vf)) {
1002 mVideoLogContextDestroy(core, gbcore->logContext);
1003 gbcore->logContext = NULL;
1004 return false;
1005 }
1006 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, gbcore->logContext, 0);
1007 return true;
1008}
1009
1010static bool _GBVLPLoadState(struct mCore* core, const void* buffer) {
1011 struct GB* gb = (struct GB*) core->board;
1012 const struct GBSerializedState* state = buffer;
1013
1014 gb->timing.root = NULL;
1015 gb->model = state->model;
1016
1017 gb->cpu->pc = GB_BASE_HRAM;
1018 gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
1019
1020 GBVideoDeserialize(&gb->video, state);
1021 GBIODeserialize(gb, state);
1022 GBAudioReset(&gb->audio);
1023
1024 // Make sure CPU loop never spins
1025 GBHalt(gb->cpu);
1026 gb->memory.ie = 0;
1027 gb->memory.ime = false;
1028
1029 return true;
1030}
1031
1032static bool _returnTrue(struct VFile* vf) {
1033 UNUSED(vf);
1034 return true;
1035}
1036
1037struct mCore* GBVideoLogPlayerCreate(void) {
1038 struct mCore* core = GBCoreCreate();
1039 core->init = _GBVLPInit;
1040 core->deinit = _GBVLPDeinit;
1041 core->reset = _GBVLPReset;
1042 core->loadROM = _GBVLPLoadROM;
1043 core->loadState = _GBVLPLoadState;
1044 core->isROM = _returnTrue;
1045 return core;
1046}
1047#else
1048struct mCore* GBVideoLogPlayerCreate(void) {
1049 return false;
1050}
1051#endif