Upgraded Sameboy-SDL to SDL2, fixed Windows build, fixed save states in SDL, added reset and mute to SDL. The SDL port now renders via OpenGL.

This commit is contained in:
Lior Halphon 2017-05-21 21:44:28 +03:00
parent 50a21da4d5
commit bef89c6604
6 changed files with 141 additions and 479 deletions

View File

@ -15,6 +15,14 @@ _a > _b ? _a : _b; })
__typeof__ (b) _b = (b); \ __typeof__ (b) _b = (b); \
_a < _b ? _a : _b; }) _a < _b ? _a : _b; })
#ifdef _WIN32
/* "Old" (Pre-2015) Windows headers/libc don't have round. */
static inline double round(double f)
{
return f >= 0? (int)(f + 0.5) : (int)(f - 0.5);
}
#endif
#define APU_FREQUENCY 0x80000 #define APU_FREQUENCY 0x80000
static int16_t generate_square(uint64_t phase, uint32_t wave_length, int16_t amplitude, uint8_t duty) static int16_t generate_square(uint64_t phase, uint32_t wave_length, int16_t amplitude, uint8_t duty)

View File

@ -651,12 +651,14 @@ void GB_switch_model_and_reset(GB_gameboy_t *gb, bool is_cgb)
void *GB_get_direct_access(GB_gameboy_t *gb, GB_direct_access_t access, size_t *size, uint16_t *bank) void *GB_get_direct_access(GB_gameboy_t *gb, GB_direct_access_t access, size_t *size, uint16_t *bank)
{ {
/* Set size and bank to dummy pointers if not set */ /* Set size and bank to dummy pointers if not set */
size_t dummy_size;
uint16_t dummy_bank;
if (!size) { if (!size) {
size = alloca(sizeof(size)); size = &dummy_size;
} }
if (!bank) { if (!bank) {
bank = alloca(sizeof(bank)); bank = &dummy_bank;
} }

View File

@ -43,10 +43,10 @@ endif
# Set compilation and linkage flags based on target, platform and configuration # Set compilation and linkage flags based on target, platform and configuration
CFLAGS += -Werror -Wall -std=gnu11 -ICore -D_GNU_SOURCE -DVERSION="$(VERSION)" -I. -D_USE_MATH_DEFINES CFLAGS += -Werror -Wall -std=gnu11 -ICore -D_GNU_SOURCE -DVERSION="$(VERSION)" -I. -D_USE_MATH_DEFINES
SDL_LDFLAGS := -lSDL SDL_LDFLAGS := -lSDL2
ifeq ($(PLATFORM),windows32) ifeq ($(PLATFORM),windows32)
CFLAGS += -IWindows CFLAGS += -IWindows
LDFLAGS += -lmsvcrt -lSDLmain -Wl,/MANIFESTFILE:NUL LDFLAGS += -lmsvcrt -lSDL2main -Wl,/MANIFESTFILE:NUL
else else
LDFLAGS += -lc -lm LDFLAGS += -lc -lm
endif endif
@ -56,19 +56,16 @@ SYSROOT := $(shell xcodebuild -sdk macosx -version Path 2> /dev/null)
CFLAGS += -F/Library/Frameworks CFLAGS += -F/Library/Frameworks
OCFLAGS += -x objective-c -fobjc-arc -Wno-deprecated-declarations -isysroot $(SYSROOT) -mmacosx-version-min=10.9 OCFLAGS += -x objective-c -fobjc-arc -Wno-deprecated-declarations -isysroot $(SYSROOT) -mmacosx-version-min=10.9
LDFLAGS += -framework AppKit -framework PreferencePanes -framework Carbon -framework QuartzCore LDFLAGS += -framework AppKit -framework PreferencePanes -framework Carbon -framework QuartzCore
SDL_LDFLAGS := -F/Library/Frameworks -framework SDL SDL_LDFLAGS := -F/Library/Frameworks -framework SDL2
endif endif
CFLAGS += -Wno-deprecated-declarations
ifeq ($(PLATFORM),windows32) ifeq ($(PLATFORM),windows32)
CFLAGS += -Wno-deprecated-declarations # Seems like Microsoft deprecated every single LIBC function CFLAGS += -Wno-deprecated-declarations -Dstrdup=_strdup # Seems like Microsoft deprecated every single LIBC function
LDFLAGS += -Wl,/NODEFAULTLIB:libcmt LDFLAGS += -Wl,/NODEFAULTLIB:libcmt.lib
endif endif
ifeq ($(CONF),debug) ifeq ($(CONF),debug)
CFLAGS += -g CFLAGS += -g
ifeq ($(PLATFORM),windows32)
LDFLAGS += -Wl,/debug
endif
else ifeq ($(CONF), release) else ifeq ($(CONF), release)
CFLAGS += -O3 -DNDEBUG CFLAGS += -O3 -DNDEBUG
ifneq ($(PLATFORM),windows32) ifneq ($(PLATFORM),windows32)
@ -82,7 +79,7 @@ endif
# Define our targets # Define our targets
ifeq ($(PLATFORM),windows32) ifeq ($(PLATFORM),windows32)
SDL_TARGET := $(BIN)/sdl/sameboy.exe $(BIN)/sdl/sameboy_debugger.exe $(BIN)/sdl/SDL.dll SDL_TARGET := $(BIN)/sdl/sameboy.exe $(BIN)/sdl/sameboy_debugger.exe $(BIN)/sdl/SDL2.dll
TESTER_TARGET := $(BIN)/tester/sameboy_tester.exe TESTER_TARGET := $(BIN)/tester/sameboy_tester.exe
else else
SDL_TARGET := $(BIN)/sdl/sameboy SDL_TARGET := $(BIN)/sdl/sameboy
@ -105,7 +102,6 @@ TESTER_SOURCES := $(shell ls Tester/*.c)
ifeq ($(PLATFORM),Darwin) ifeq ($(PLATFORM),Darwin)
COCOA_SOURCES := $(shell ls Cocoa/*.m) $(shell ls HexFiend/*.m) COCOA_SOURCES := $(shell ls Cocoa/*.m) $(shell ls HexFiend/*.m)
QUICKLOOK_SOURCES := $(shell ls QuickLook/*.m) $(shell ls QuickLook/*.c) QUICKLOOK_SOURCES := $(shell ls QuickLook/*.m) $(shell ls QuickLook/*.c)
SDL_SOURCES += $(shell ls SDL/*.m)
endif endif
CORE_OBJECTS := $(patsubst %,$(OBJ)/%.o,$(CORE_SOURCES)) CORE_OBJECTS := $(patsubst %,$(OBJ)/%.o,$(CORE_SOURCES))
@ -236,11 +232,11 @@ $(OBJ)/%.res: %.rc
%.o: %.res %.o: %.res
cvtres /OUT:"$@" $^ cvtres /OUT:"$@" $^
# We must provide SDL.dll with the Windows port. This is an AWFUL HACK to find it. # We must provide SDL2.dll with the Windows port. This is an AWFUL HACK to find it.
SPACE := SPACE :=
SPACE += SPACE +=
$(BIN)/sdl/SDL.dll: $(BIN)/sdl/SDL2.dll:
@$(eval POTENTIAL_MATCHES := $(subst @@@," ",$(patsubst %,%/SDL.dll,$(subst ;,$(SPACE),$(subst $(SPACE),@@@,$(lib)))))) @$(eval POTENTIAL_MATCHES := $(subst @@@," ",$(patsubst %,%/SDL2.dll,$(subst ;,$(SPACE),$(subst $(SPACE),@@@,$(lib))))))
@$(eval MATCH := $(shell ls $(POTENTIAL_MATCHES) 2> NUL | head -n 1)) @$(eval MATCH := $(shell ls $(POTENTIAL_MATCHES) 2> NUL | head -n 1))
cp "$(MATCH)" $@ cp "$(MATCH)" $@

View File

@ -1,16 +0,0 @@
/* SDLMain.m - main entry point for our Cocoa-ized SDL app
Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
Non-NIB-Code & other changes: Max Horn <max@quendi.de>
Feel free to customize this file to suit your needs
*/
#ifndef _SDLMain_h_
#define _SDLMain_h_
#import <Cocoa/Cocoa.h>
@interface SDLMain : NSObject<NSApplicationDelegate>
@end
#endif /* _SDLMain_h_ */

View File

@ -1,382 +0,0 @@
/* SDLMain.m - main entry point for our Cocoa-ized SDL app
Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
Non-NIB-Code & other changes: Max Horn <max@quendi.de>
Feel free to customize this file to suit your needs
*/
#include <SDL/SDL.h>
#include "SDLMain.h"
#include <sys/param.h> /* for MAXPATHLEN */
#include <unistd.h>
#import <objc/runtime.h>
/* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
but the method still is there and works. To avoid warnings, we declare
it ourselves here. */
@interface NSApplication(SDL_Missing_Methods)
- (void)setAppleMenu:(NSMenu *)menu;
@end
/* Use this flag to determine whether we use SDLMain.nib or not */
#define SDL_USE_NIB_FILE 0
/* Use this flag to determine whether we use CPS (docking) or not */
#define SDL_USE_CPS 1
#ifdef SDL_USE_CPS
/* Portions of CPS.h */
typedef struct CPSProcessSerNum
{
UInt32 lo;
UInt32 hi;
} CPSProcessSerNum;
extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn);
extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn);
#endif /* SDL_USE_CPS */
static int gArgc;
static char **gArgv;
static BOOL gFinderLaunch;
static BOOL gCalledAppMainline = FALSE;
static NSString *getApplicationName(void)
{
const NSDictionary *dict;
NSString *appName = 0;
/* Determine the application name */
dict = (__bridge const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
if (dict)
appName = [dict objectForKey: @"CFBundleName"];
if (![appName length])
appName = [[NSProcessInfo processInfo] processName];
return appName;
}
#if SDL_USE_NIB_FILE
/* A helper category for NSString */
@interface NSString (ReplaceSubString)
- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
@end
#endif
@interface NSApplication (SDLApplication)
@end
@implementation NSApplication (SDLApplication)
/* Invoked from the Quit menu item */
- (void)_terminate:(id)sender
{
/* Post a SDL_QUIT event */
SDL_Event event;
event.type = SDL_QUIT;
SDL_PushEvent(&event);
/* Call "super" */
[self _terminate:sender];
}
/* Use swizzling to avoid warning and undocumented Obj C runtime behavior. Didn't feel like rewriting SDLMain for this. */
+ (void) load
{
method_exchangeImplementations(class_getInstanceMethod(self, @selector(terminate:)), class_getInstanceMethod(self, @selector(_terminate:)));
}
@end
/* The main class of the application, the application's delegate */
@implementation SDLMain
/* Set the working directory to the .app's parent directory */
- (void) setupWorkingDirectory:(BOOL)shouldChdir
{
if (shouldChdir)
{
char parentdir[MAXPATHLEN];
CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) {
chdir(parentdir); /* chdir to the binary app's parent */
}
CFRelease(url);
CFRelease(url2);
}
}
#if SDL_USE_NIB_FILE
/* Fix menu to contain the real app name instead of "SDL App" */
- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
{
NSRange aRange;
NSEnumerator *enumerator;
NSMenuItem *menuItem;
aRange = [[aMenu title] rangeOfString:@"SDL App"];
if (aRange.length != 0)
[aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
enumerator = [[aMenu itemArray] objectEnumerator];
while ((menuItem = [enumerator nextObject]))
{
aRange = [[menuItem title] rangeOfString:@"SDL App"];
if (aRange.length != 0)
[menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
if ([menuItem hasSubmenu])
[self fixMenu:[menuItem submenu] withAppName:appName];
}
}
#else
static void setApplicationMenu(void)
{
/* warning: this code is very odd */
NSMenu *appleMenu;
NSMenuItem *menuItem;
NSString *title;
NSString *appName;
appName = getApplicationName();
appleMenu = [[NSMenu alloc] initWithTitle:@""];
/* Add menu items */
title = [@"About " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Hide " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
[appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Quit " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
/* Put menu into the menubar */
menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[menuItem setSubmenu:appleMenu];
[[NSApp mainMenu] addItem:menuItem];
/* Tell the application object that this is now the application menu */
[NSApp setAppleMenu:appleMenu];
}
/* Create a window menu */
static void setupWindowMenu(void)
{
NSMenu *windowMenu;
NSMenuItem *windowMenuItem;
NSMenuItem *menuItem;
windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
/* "Minimize" item */
menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
[windowMenu addItem:menuItem];
/* Put menu into the menubar */
windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
[windowMenuItem setSubmenu:windowMenu];
[[NSApp mainMenu] addItem:windowMenuItem];
/* Tell the application object that this is now the window menu */
[NSApp setWindowsMenu:windowMenu];
/* Finally give up our references to the objects */
}
/* Replacement for NSApplicationMain */
static void CustomApplicationMain (int argc, char **argv)
{
SDLMain *sdlMain;
/* Ensure the application object is initialised */
[NSApplication sharedApplication];
#ifdef SDL_USE_CPS
{
CPSProcessSerNum PSN;
/* Tell the dock about us */
if (!CPSGetCurrentProcess(&PSN))
if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
if (!CPSSetFrontProcess(&PSN))
[NSApplication sharedApplication];
}
#endif /* SDL_USE_CPS */
/* Set up the menubar */
[NSApp setMainMenu:[[NSMenu alloc] init]];
setApplicationMenu();
setupWindowMenu();
/* Create SDLMain and make it the app delegate */
sdlMain = [[SDLMain alloc] init];
[NSApp setDelegate:sdlMain];
/* Start the main event loop */
[NSApp run];
}
#endif
/*
* Catch document open requests...this lets us notice files when the app
* was launched by double-clicking a document, or when a document was
* dragged/dropped on the app's icon. You need to have a
* CFBundleDocumentsType section in your Info.plist to get this message,
* apparently.
*
* Files are added to gArgv, so to the app, they'll look like command line
* arguments. Previously, apps launched from the finder had nothing but
* an argv[0].
*
* This message may be received multiple times to open several docs on launch.
*
* This message is ignored once the app's mainline has been called.
*/
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
const char *temparg;
size_t arglen;
char *arg;
char **newargv;
if (!gFinderLaunch) /* MacOS is passing command line args. */
return FALSE;
if (gCalledAppMainline) /* app has started, ignore this document. */
return FALSE;
temparg = [filename UTF8String];
arglen = SDL_strlen(temparg) + 1;
arg = (char *) SDL_malloc(arglen);
if (arg == NULL)
return FALSE;
newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2));
if (newargv == NULL)
{
SDL_free(arg);
return FALSE;
}
gArgv = newargv;
SDL_strlcpy(arg, temparg, arglen);
gArgv[gArgc++] = arg;
gArgv[gArgc] = NULL;
return TRUE;
}
/* Called when the internal event loop has just started running */
- (void) applicationDidFinishLaunching: (NSNotification *) note
{
int status;
/* Set the working directory to the .app's parent directory */
[self setupWorkingDirectory:gFinderLaunch];
#if SDL_USE_NIB_FILE
/* Set the main menu to contain the real app name instead of "SDL App" */
[self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
#endif
/* Hand off to main application code */
gCalledAppMainline = TRUE;
status = SDL_main (gArgc, gArgv);
/* We're done, thank you for playing */
exit(status);
}
@end
@implementation NSString (ReplaceSubString)
- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
{
unsigned int bufferSize;
unsigned int selfLen = [self length];
unsigned int aStringLen = [aString length];
unichar *buffer;
NSRange localRange;
NSString *result;
bufferSize = selfLen + aStringLen - aRange.length;
buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar));
/* Get first part into buffer */
localRange.location = 0;
localRange.length = aRange.location;
[self getCharacters:buffer range:localRange];
/* Get middle part into buffer */
localRange.location = 0;
localRange.length = aStringLen;
[aString getCharacters:(buffer+aRange.location) range:localRange];
/* Get last part into buffer */
localRange.location = aRange.location + aRange.length;
localRange.length = selfLen - localRange.location;
[self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
/* Build output string */
result = [NSString stringWithCharacters:buffer length:bufferSize];
NSDeallocateMemoryPages(buffer, bufferSize);
return result;
}
@end
void cocoa_disable_filtering(void) {
CGContextSetInterpolationQuality([[NSGraphicsContext currentContext] CGContext], kCGInterpolationNone);
}
#ifdef main
# undef main
#endif
/* Main entry point to executable - should *not* be SDL_main! */
int main (int argc, char **argv)
{
/* Copy the arguments into a global variable */
/* This is passed if we are launched by double-clicking */
if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
gArgv[0] = argv[0];
gArgv[1] = NULL;
gArgc = 1;
gFinderLaunch = YES;
} else {
int i;
gArgc = argc;
gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));
for (i = 0; i <= argc; i++)
gArgv[i] = argv[i];
gFinderLaunch = NO;
}
#if SDL_USE_NIB_FILE
NSApplicationMain (argc, argv);
#else
CustomApplicationMain (argc, argv);
#endif
return 0;
}

View File

@ -4,7 +4,7 @@
#include <time.h> #include <time.h>
#include <assert.h> #include <assert.h>
#include <signal.h> #include <signal.h>
#include <SDL/SDL.h> #include <SDL2/SDL.h>
#ifndef _WIN32 #ifndef _WIN32
#define AUDIO_FREQUENCY 96000 #define AUDIO_FREQUENCY 96000
#else #else
@ -15,28 +15,94 @@
#define snprintf _snprintf #define snprintf _snprintf
#endif #endif
#if defined(__APPLE__) && SDL_MAJOR_VERSION == 2 && SDL_MINOR_VERSION == 0 && SDL_PATCHLEVEL == 5
#error You are using SDL2-2.0.5, which contains a bug that prevents 96KHz audio playback on macOS. Use SDL2-2.0.4 or alternatively modify this file to reduce the frequency to 44100 and disable this error.
#endif
#include "gb.h" #include "gb.h"
static bool running = false;
static char *filename; static char *filename;
static char *battery_save_path_ptr;
static void replace_extension(const char *src, size_t length, char *dest, const char *ext); static void replace_extension(const char *src, size_t length, char *dest, const char *ext);
static SDL_Window *window = NULL;
static SDL_Renderer *renderer = NULL;
static SDL_Texture *texture = NULL;
static SDL_PixelFormat *pixel_format = NULL;
static uint32_t pixels[160*144];
GB_gameboy_t gb; GB_gameboy_t gb;
static void GB_update_keys_status(GB_gameboy_t *gb) static enum {
GB_SDL_NO_COMMAND,
GB_SDL_SAVE_STATE_COMMAND,
GB_SDL_LOAD_STATE_COMMAND,
GB_SDL_RESET_COMMAND,
} pending_command;
static unsigned command_parameter;
static void handle_events(GB_gameboy_t *gb)
{ {
static bool ctrl = false; static bool ctrl = false;
static bool shift = false; static bool shift = false;
#ifdef __APPLE__ #ifdef __APPLE__
static bool cmd = false; static bool cmd = false;
#define MODIFIER cmd
#else
#define MODIFIER ctrl
#endif #endif
SDL_Event event; SDL_Event event;
while (SDL_PollEvent(&event)) while (SDL_PollEvent(&event))
{ {
switch( event.type ){ switch( event.type ){
case SDL_QUIT: case SDL_QUIT:
running = false; GB_save_battery(gb, battery_save_path_ptr);
exit(0);
case SDL_KEYDOWN: case SDL_KEYDOWN:
case SDL_KEYUP: switch (event.key.keysym.sym) {
case SDLK_c:
if (ctrl && event.type == SDL_KEYDOWN) {
ctrl = false;
GB_debugger_break(gb);
}
break;
case SDLK_r:
if (MODIFIER) {
pending_command = GB_SDL_RESET_COMMAND;
}
break;
case SDLK_m:
if (MODIFIER) {
#ifdef __APPLE__
// Can't over CMD+M (Minimize) in SDL
if (!shift) {
break;
}
#endif
SDL_PauseAudio(SDL_GetAudioStatus() == SDL_AUDIO_PLAYING? true : false);
}
break;
default:
/* Save states */
if (event.key.keysym.sym >= SDLK_0 && event.key.keysym.sym <= SDLK_9) {
if (MODIFIER) {
command_parameter = event.key.keysym.sym - SDLK_0;
if (shift) {
pending_command = GB_SDL_LOAD_STATE_COMMAND;
}
else {
pending_command = GB_SDL_SAVE_STATE_COMMAND;
}
}
}
break;
}
case SDL_KEYUP: // Fallthrough
switch (event.key.keysym.sym) { switch (event.key.keysym.sym) {
case SDLK_RIGHT: case SDLK_RIGHT:
GB_set_key_state(gb, GB_KEY_RIGHT, event.type == SDL_KEYDOWN); GB_set_key_state(gb, GB_KEY_RIGHT, event.type == SDL_KEYDOWN);
@ -74,42 +140,11 @@ static void GB_update_keys_status(GB_gameboy_t *gb)
shift = event.type == SDL_KEYDOWN; shift = event.type == SDL_KEYDOWN;
break; break;
#ifdef __APPLE__ #ifdef __APPLE__
case SDLK_LMETA: case SDLK_LGUI:
case SDLK_RMETA: case SDLK_RGUI:
cmd = event.type == SDL_KEYDOWN; cmd = event.type == SDL_KEYDOWN;
break; break;
#endif #endif
case SDLK_c:
if (ctrl && event.type == SDL_KEYDOWN) {
ctrl = false;
GB_debugger_break(gb);
}
break;
default:
/* Save states */
if (event.key.keysym.sym >= SDLK_0 && event.key.keysym.sym <= SDLK_9) {
#ifdef __APPLE__
if (cmd) {
#else
if (ctrl) {
#endif
char save_path[strlen(filename) + 4];
char save_extension[] =".s0";
save_extension[2] += event.key.keysym.sym - SDLK_0;
replace_extension(filename, strlen(filename), save_path, save_extension);
if (shift) {
GB_load_state(gb, save_path);
}
else {
GB_save_state(gb, save_path);
}
}
}
break;
} }
break; break;
default: default:
@ -120,11 +155,11 @@ static void GB_update_keys_status(GB_gameboy_t *gb)
static void vblank(GB_gameboy_t *gb) static void vblank(GB_gameboy_t *gb)
{ {
SDL_Surface *screen = GB_get_user_data(gb); SDL_UpdateTexture(texture, NULL, pixels, 160 * sizeof (uint32_t));
SDL_Flip(screen); SDL_RenderClear(renderer);
GB_update_keys_status(gb); SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
GB_set_pixels_output(gb, screen->pixels); handle_events(gb);
} }
#ifdef __APPLE__ #ifdef __APPLE__
@ -178,10 +213,9 @@ static char *executable_relative_path(const char *filename)
return path; return path;
} }
static SDL_Surface *screen = NULL;
static uint32_t rgb_encode(GB_gameboy_t *gb, uint8_t r, uint8_t g, uint8_t b) static uint32_t rgb_encode(GB_gameboy_t *gb, uint8_t r, uint8_t g, uint8_t b)
{ {
return SDL_MapRGB(screen->format, r, g, b); return SDL_MapRGB(pixel_format, r, g, b);
} }
static void debugger_interrupt(int ignore) static void debugger_interrupt(int ignore)
@ -217,9 +251,6 @@ static void replace_extension(const char *src, size_t length, char *dest, const
strcat(dest, ext); strcat(dest, ext);
} }
#ifdef __APPLE__
extern void cocoa_disable_filtering(void);
#endif
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
bool dmg = false; bool dmg = false;
@ -270,16 +301,18 @@ usage:
signal(SIGINT, debugger_interrupt); signal(SIGINT, debugger_interrupt);
SDL_Init( SDL_INIT_EVERYTHING ); SDL_Init( SDL_INIT_EVERYTHING );
screen = SDL_SetVideoMode(160, 144, 32, SDL_SWSURFACE );
SDL_WM_SetCaption("SameBoy v" xstr(VERSION), "SameBoy v" xstr(VERSION)); window = SDL_CreateWindow("SameBoy v" xstr(VERSION), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
#ifdef __APPLE__ 160, 144, SDL_WINDOW_OPENGL);
cocoa_disable_filtering(); renderer = SDL_CreateRenderer(window, -1, 0);
#endif
texture = SDL_CreateTexture(renderer, SDL_GetWindowPixelFormat(window), SDL_TEXTUREACCESS_STREAMING, 160, 144);
pixel_format = SDL_AllocFormat(SDL_GetWindowPixelFormat(window));
/* Configure Screen */ /* Configure Screen */
SDL_LockSurface(screen);
GB_set_vblank_callback(&gb, (GB_vblank_callback_t) vblank); GB_set_vblank_callback(&gb, (GB_vblank_callback_t) vblank);
GB_set_user_data(&gb, screen); GB_set_pixels_output(&gb, pixels);
GB_set_pixels_output(&gb, screen->pixels);
GB_set_rgb_encode_callback(&gb, rgb_encode); GB_set_rgb_encode_callback(&gb, rgb_encode);
size_t path_length = strlen(filename); size_t path_length = strlen(filename);
@ -287,6 +320,7 @@ usage:
/* Configure battery */ /* Configure battery */
char battery_save_path[path_length + 5]; /* At the worst case, size is strlen(path) + 4 bytes for .sav + NULL */ char battery_save_path[path_length + 5]; /* At the worst case, size is strlen(path) + 4 bytes for .sav + NULL */
replace_extension(filename, path_length, battery_save_path, ".sav"); replace_extension(filename, path_length, battery_save_path, ".sav");
battery_save_path_ptr = battery_save_path;
GB_load_battery(&gb, battery_save_path); GB_load_battery(&gb, battery_save_path);
/* Configure symbols */ /* Configure symbols */
@ -306,19 +340,39 @@ usage:
want.callback = audio_callback; want.callback = audio_callback;
want.userdata = &gb; want.userdata = &gb;
SDL_OpenAudio(&want, &have); SDL_OpenAudio(&want, &have);
GB_set_sample_rate(&gb, AUDIO_FREQUENCY); GB_set_sample_rate(&gb, have.freq);
/* Start Audio */ /* Start Audio */
SDL_PauseAudio(0); SDL_PauseAudio(false);
/* Run emulation */ /* Run emulation */
running = true; while (true) {
while (running) {
GB_run(&gb); GB_run(&gb);
} switch (pending_command) {
SDL_CloseAudio(); case GB_SDL_LOAD_STATE_COMMAND:
case GB_SDL_SAVE_STATE_COMMAND: {
char save_path[strlen(filename) + 4];
char save_extension[] = ".s0";
save_extension[2] += command_parameter;
replace_extension(filename, strlen(filename), save_path, save_extension);
GB_save_battery(&gb, battery_save_path); if (pending_command == GB_SDL_LOAD_STATE_COMMAND) {
return 0; GB_load_state(&gb, save_path);
}
else {
GB_save_state(&gb, save_path);
}
break;
}
case GB_SDL_RESET_COMMAND:
GB_reset(&gb);
break;
case GB_SDL_NO_COMMAND:
break;
}
pending_command = GB_SDL_NO_COMMAND;
}
} }