all repos — mgba @ 2279521482689b79d3baa5be7560431b11825ca1

mGBA Game Boy Advance Emulator

src/platform/sdl/sdl-events.c (view raw)

  1/* Copyright (c) 2013-2014 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 "sdl-events.h"
  7
  8#include <mgba/core/core.h>
  9#include <mgba/core/input.h>
 10#include <mgba/core/serialize.h>
 11#include <mgba/core/thread.h>
 12#include <mgba/debugger/debugger.h>
 13#include <mgba/internal/gba/input.h>
 14#include <mgba-util/configuration.h>
 15#include <mgba-util/formatting.h>
 16#include <mgba-util/vfs.h>
 17
 18#if SDL_VERSION_ATLEAST(2, 0, 0) && defined(__APPLE__)
 19#define GUI_MOD KMOD_GUI
 20#else
 21#define GUI_MOD KMOD_CTRL
 22#endif
 23
 24#define GYRO_STEPS 100
 25#define RUMBLE_PWM 16
 26#define RUMBLE_STEPS 2
 27
 28mLOG_DEFINE_CATEGORY(SDL_EVENTS, "SDL Events", "platform.sdl.events");
 29
 30DEFINE_VECTOR(SDL_JoystickList, struct SDL_JoystickCombo);
 31
 32#if SDL_VERSION_ATLEAST(2, 0, 0)
 33static void _mSDLSetRumble(struct mRumble* rumble, int enable);
 34#endif
 35static int32_t _mSDLReadTiltX(struct mRotationSource* rumble);
 36static int32_t _mSDLReadTiltY(struct mRotationSource* rumble);
 37static int32_t _mSDLReadGyroZ(struct mRotationSource* rumble);
 38static void _mSDLRotationSample(struct mRotationSource* source);
 39
 40bool mSDLInitEvents(struct mSDLEvents* context) {
 41#if SDL_VERSION_ATLEAST(2, 0, 4)
 42	SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1");
 43#endif
 44	if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) {
 45		mLOG(SDL_EVENTS, ERROR, "SDL joystick initialization failed: %s", SDL_GetError());
 46	}
 47
 48#if SDL_VERSION_ATLEAST(2, 0, 0)
 49	SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
 50	if (SDL_InitSubSystem(SDL_INIT_HAPTIC) < 0) {
 51		mLOG(SDL_EVENTS, ERROR, "SDL haptic initialization failed: %s", SDL_GetError());
 52	}
 53	if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
 54		mLOG(SDL_EVENTS, ERROR, "SDL video initialization failed: %s", SDL_GetError());
 55	}
 56#endif
 57
 58	SDL_JoystickEventState(SDL_ENABLE);
 59	int nJoysticks = SDL_NumJoysticks();
 60	SDL_JoystickListInit(&context->joysticks, nJoysticks);
 61	if (nJoysticks > 0) {
 62		mSDLUpdateJoysticks(context, NULL);
 63		// Some OSes don't do hotplug detection
 64		if (!SDL_JoystickListSize(&context->joysticks)) {
 65			int i;
 66			for (i = 0; i < nJoysticks; ++i) {
 67				SDL_Joystick* sdlJoystick = SDL_JoystickOpen(i);
 68				if (!sdlJoystick) {
 69					continue;
 70				}
 71				struct SDL_JoystickCombo* joystick = SDL_JoystickListAppend(&context->joysticks);
 72				joystick->joystick = sdlJoystick;
 73				joystick->index = SDL_JoystickListSize(&context->joysticks) - 1;
 74#if SDL_VERSION_ATLEAST(2, 0, 0)
 75				joystick->id = SDL_JoystickInstanceID(joystick->joystick);
 76				joystick->haptic = SDL_HapticOpenFromJoystick(joystick->joystick);
 77#else
 78				joystick->id = SDL_JoystickIndex(joystick->joystick);
 79#endif
 80			}
 81		}
 82	}
 83
 84	context->playersAttached = 0;
 85
 86	size_t i;
 87	for (i = 0; i < MAX_PLAYERS; ++i) {
 88		context->preferredJoysticks[i] = 0;
 89	}
 90
 91#if !SDL_VERSION_ATLEAST(2, 0, 0)
 92	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
 93#else
 94	context->screensaverSuspendDepth = 0;
 95#endif
 96	return true;
 97}
 98
 99void mSDLDeinitEvents(struct mSDLEvents* context) {
100	size_t i;
101	for (i = 0; i < SDL_JoystickListSize(&context->joysticks); ++i) {
102		struct SDL_JoystickCombo* joystick = SDL_JoystickListGetPointer(&context->joysticks, i);
103#if SDL_VERSION_ATLEAST(2, 0, 0)
104		SDL_HapticClose(joystick->haptic);
105#endif
106		SDL_JoystickClose(joystick->joystick);
107	}
108	SDL_JoystickListDeinit(&context->joysticks);
109	SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
110}
111
112void mSDLEventsLoadConfig(struct mSDLEvents* context, const struct Configuration* config) {
113	context->preferredJoysticks[0] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 0);
114	context->preferredJoysticks[1] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 1);
115	context->preferredJoysticks[2] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 2);
116	context->preferredJoysticks[3] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 3);
117}
118
119void mSDLInitBindingsGBA(struct mInputMap* inputMap) {
120#ifdef BUILD_PANDORA
121	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_PAGEDOWN, GBA_KEY_A);
122	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_END, GBA_KEY_B);
123	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RSHIFT, GBA_KEY_L);
124	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RCTRL, GBA_KEY_R);
125	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LALT, GBA_KEY_START);
126	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LCTRL, GBA_KEY_SELECT);
127	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_UP, GBA_KEY_UP);
128	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_DOWN, GBA_KEY_DOWN);
129	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LEFT, GBA_KEY_LEFT);
130	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RIGHT, GBA_KEY_RIGHT);
131#else
132	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_x, GBA_KEY_A);
133	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_z, GBA_KEY_B);
134	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_a, GBA_KEY_L);
135	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_s, GBA_KEY_R);
136	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RETURN, GBA_KEY_START);
137	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_BACKSPACE, GBA_KEY_SELECT);
138	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_UP, GBA_KEY_UP);
139	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_DOWN, GBA_KEY_DOWN);
140	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LEFT, GBA_KEY_LEFT);
141	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RIGHT, GBA_KEY_RIGHT);
142#endif
143
144	struct mInputAxis description = { GBA_KEY_RIGHT, GBA_KEY_LEFT, 0x4000, -0x4000 };
145	mInputBindAxis(inputMap, SDL_BINDING_BUTTON, 0, &description);
146	description = (struct mInputAxis) { GBA_KEY_DOWN, GBA_KEY_UP, 0x4000, -0x4000 };
147	mInputBindAxis(inputMap, SDL_BINDING_BUTTON, 1, &description);
148
149	mInputBindHat(inputMap, SDL_BINDING_BUTTON, 0, &GBAInputInfo.hat);
150}
151
152bool mSDLAttachPlayer(struct mSDLEvents* events, struct mSDLPlayer* player) {
153	player->joystick = 0;
154
155	if (events->playersAttached >= MAX_PLAYERS) {
156		return false;
157	}
158
159#if SDL_VERSION_ATLEAST(2, 0, 0)
160	player->rumble.d.setRumble = _mSDLSetRumble;
161	CircleBufferInit(&player->rumble.history, RUMBLE_PWM);
162	player->rumble.level = 0;
163	player->rumble.activeLevel = 0;
164	player->rumble.p = player;
165#endif
166
167	player->rotation.d.readTiltX = _mSDLReadTiltX;
168	player->rotation.d.readTiltY = _mSDLReadTiltY;
169	player->rotation.d.readGyroZ = _mSDLReadGyroZ;
170	player->rotation.d.sample = _mSDLRotationSample;
171	player->rotation.axisX = 2;
172	player->rotation.axisY = 3;
173	player->rotation.gyroSensitivity = 2.2e9f;
174	player->rotation.gyroX = 0;
175	player->rotation.gyroY = 1;
176	player->rotation.zDelta = 0;
177	CircleBufferInit(&player->rotation.zHistory, sizeof(float) * GYRO_STEPS);
178	player->rotation.p = player;
179
180	player->playerId = events->playersAttached;
181	events->players[player->playerId] = player;
182	size_t firstUnclaimed = SIZE_MAX;
183	size_t index = SIZE_MAX;
184
185	size_t i;
186	for (i = 0; i < SDL_JoystickListSize(&events->joysticks); ++i) {
187		bool claimed = false;
188
189		int p;
190		for (p = 0; p < events->playersAttached; ++p) {
191			if (events->players[p]->joystick == SDL_JoystickListGetPointer(&events->joysticks, i)) {
192				claimed = true;
193				break;
194			}
195		}
196
197		if (!claimed && firstUnclaimed == SIZE_MAX) {
198			firstUnclaimed = i;
199		}
200
201#if SDL_VERSION_ATLEAST(2, 0, 0)
202		char joystickName[34] = {0};
203		SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(SDL_JoystickListGetPointer(&events->joysticks, i)->joystick), joystickName, sizeof(joystickName));
204#else
205		const char* joystickName = SDL_JoystickName(SDL_JoystickIndex(SDL_JoystickListGetPointer(&events->joysticks, i)->joystick));
206		if (!joystickName) {
207			continue;
208		}
209#endif
210		if (events->preferredJoysticks[player->playerId] && strcmp(events->preferredJoysticks[player->playerId], joystickName) == 0) {
211			index = i;
212			break;
213		}
214	}
215
216	if (index == SIZE_MAX && firstUnclaimed != SIZE_MAX) {
217		index = firstUnclaimed;
218	}
219
220	if (index != SIZE_MAX) {
221		player->joystick = SDL_JoystickListGetPointer(&events->joysticks, index);
222
223#if SDL_VERSION_ATLEAST(2, 0, 0)
224		if (player->joystick->haptic) {
225			SDL_HapticRumbleInit(player->joystick->haptic);
226		}
227#endif
228	}
229
230	++events->playersAttached;
231	return true;
232}
233
234void mSDLDetachPlayer(struct mSDLEvents* events, struct mSDLPlayer* player) {
235	if (player != events->players[player->playerId]) {
236		return;
237	}
238	int i;
239	for (i = player->playerId; i < events->playersAttached; ++i) {
240		if (i + 1 < MAX_PLAYERS) {
241			events->players[i] = events->players[i + 1];
242		}
243		if (i < events->playersAttached - 1) {
244			events->players[i]->playerId = i;
245		}
246	}
247	--events->playersAttached;
248	CircleBufferDeinit(&player->rotation.zHistory);
249}
250
251void mSDLPlayerLoadConfig(struct mSDLPlayer* context, const struct Configuration* config) {
252	mInputMapLoad(context->bindings, SDL_BINDING_KEY, config);
253	if (context->joystick) {
254		mInputMapLoad(context->bindings, SDL_BINDING_BUTTON, config);
255#if SDL_VERSION_ATLEAST(2, 0, 0)
256		char name[34] = {0};
257		SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(context->joystick->joystick), name, sizeof(name));
258#else
259		const char* name = SDL_JoystickName(SDL_JoystickIndex(context->joystick->joystick));
260		if (!name) {
261			return;
262		}
263#endif
264		mInputProfileLoad(context->bindings, SDL_BINDING_BUTTON, config, name);
265
266		const char* value;
267		char* end;
268		int numAxes = SDL_JoystickNumAxes(context->joystick->joystick);
269		int axis;
270		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisX", name);
271		if (value) {
272			axis = strtol(value, &end, 0);
273			if (axis >= 0 && axis < numAxes && end && !*end) {
274				context->rotation.axisX = axis;
275			}
276		}
277		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisY", name);
278		if (value) {
279			axis = strtol(value, &end, 0);
280			if (axis >= 0 && axis < numAxes && end && !*end) {
281				context->rotation.axisY = axis;
282			}
283		}
284		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisX", name);
285		if (value) {
286			axis = strtol(value, &end, 0);
287			if (axis >= 0 && axis < numAxes && end && !*end) {
288				context->rotation.gyroX = axis;
289			}
290		}
291		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisY", name);
292		if (value) {
293			axis = strtol(value, &end, 0);
294			if (axis >= 0 && axis < numAxes && end && !*end) {
295				context->rotation.gyroY = axis;
296			}
297		}
298		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroSensitivity", name);
299		if (value) {
300			float sensitivity = strtof_u(value, &end);
301			if (end && !*end) {
302				context->rotation.gyroSensitivity = sensitivity;
303			}
304		}
305	}
306}
307
308void mSDLPlayerSaveConfig(const struct mSDLPlayer* context, struct Configuration* config) {
309	if (context->joystick) {
310#if SDL_VERSION_ATLEAST(2, 0, 0)
311		char name[34] = {0};
312		SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(context->joystick->joystick), name, sizeof(name));
313#else
314		const char* name = SDL_JoystickName(SDL_JoystickIndex(context->joystick->joystick));
315		if (!name) {
316			return;
317		}
318#endif
319		char value[16];
320		snprintf(value, sizeof(value), "%i", context->rotation.axisX);
321		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisX", value, name);
322		snprintf(value, sizeof(value), "%i", context->rotation.axisY);
323		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisY", value, name);
324		snprintf(value, sizeof(value), "%i", context->rotation.gyroX);
325		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisX", value, name);
326		snprintf(value, sizeof(value), "%i", context->rotation.gyroY);
327		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisY", value, name);
328		snprintf(value, sizeof(value), "%g", context->rotation.gyroSensitivity);
329		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroSensitivity", value, name);
330	}
331}
332
333void mSDLPlayerChangeJoystick(struct mSDLEvents* events, struct mSDLPlayer* player, size_t index) {
334	if (player->playerId >= MAX_PLAYERS || index >= SDL_JoystickListSize(&events->joysticks)) {
335		return;
336	}
337	player->joystick = SDL_JoystickListGetPointer(&events->joysticks, index);
338}
339
340void mSDLUpdateJoysticks(struct mSDLEvents* events, const struct Configuration* config) {
341	// Pump SDL joystick events without eating the rest of the events
342	SDL_JoystickUpdate();
343#if SDL_VERSION_ATLEAST(2, 0, 0)
344	SDL_Event event;
345	while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED) > 0) {
346		if (event.type == SDL_JOYDEVICEADDED) {
347			SDL_Joystick* sdlJoystick = SDL_JoystickOpen(event.jdevice.which);
348			if (!sdlJoystick) {
349				continue;
350			}
351			ssize_t joysticks[MAX_PLAYERS];
352			size_t i;
353			// Pointers can get invalidated, so we'll need to refresh them
354			for (i = 0; i < events->playersAttached && i < MAX_PLAYERS; ++i) {
355				joysticks[i] = events->players[i]->joystick ? SDL_JoystickListIndex(&events->joysticks, events->players[i]->joystick) : SIZE_MAX;
356				events->players[i]->joystick = NULL;
357			}
358			struct SDL_JoystickCombo* joystick = SDL_JoystickListAppend(&events->joysticks);
359			joystick->joystick = sdlJoystick;
360			joystick->id = SDL_JoystickInstanceID(joystick->joystick);
361			joystick->index = SDL_JoystickListSize(&events->joysticks) - 1;
362#if SDL_VERSION_ATLEAST(2, 0, 0)
363			joystick->haptic = SDL_HapticOpenFromJoystick(joystick->joystick);
364#endif
365			for (i = 0; i < events->playersAttached && i < MAX_PLAYERS; ++i) {
366				if (joysticks[i] != SIZE_MAX) {
367					events->players[i]->joystick = SDL_JoystickListGetPointer(&events->joysticks, joysticks[i]);
368				}
369			}
370
371#if SDL_VERSION_ATLEAST(2, 0, 0)
372			char joystickName[34] = {0};
373			SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick->joystick), joystickName, sizeof(joystickName));
374#else
375			const char* joystickName = SDL_JoystickName(SDL_JoystickIndex(joystick->joystick));
376			if (joystickName)
377#endif
378			{
379				for (i = 0; (int) i < events->playersAttached; ++i) {
380					if (events->players[i]->joystick) {
381						continue;
382					}
383					if (events->preferredJoysticks[i] && strcmp(events->preferredJoysticks[i], joystickName) == 0) {
384						events->players[i]->joystick = joystick;
385						if (config && events->players[i]->bindings) {
386							mInputProfileLoad(events->players[i]->bindings, SDL_BINDING_BUTTON, config, joystickName);
387						}
388						return;
389					}
390				}
391			}
392			for (i = 0; (int) i < events->playersAttached; ++i) {
393				if (events->players[i]->joystick) {
394					continue;
395				}
396				events->players[i]->joystick = joystick;
397				if (config && events->players[i]->bindings && joystickName) {
398					mInputProfileLoad(events->players[i]->bindings, SDL_BINDING_BUTTON, config, joystickName);
399				}
400				break;
401			}
402		} else if (event.type == SDL_JOYDEVICEREMOVED) {
403			SDL_JoystickID ids[MAX_PLAYERS] = { 0 };
404			size_t i;
405			for (i = 0; (int) i < events->playersAttached; ++i) {
406				if (events->players[i]->joystick) {
407					ids[i] = events->players[i]->joystick->id;
408					events->players[i]->joystick = 0;
409				} else {
410					ids[i] = -1;
411				}
412			}
413			for (i = 0; i < SDL_JoystickListSize(&events->joysticks);) {
414				struct SDL_JoystickCombo* joystick = SDL_JoystickListGetPointer(&events->joysticks, i);
415				if (joystick->id == event.jdevice.which) {
416					SDL_JoystickListShift(&events->joysticks, i, 1);
417					continue;
418				}
419				SDL_JoystickListGetPointer(&events->joysticks, i)->index = i;
420				int p;
421				for (p = 0; p < events->playersAttached; ++p) {
422					if (joystick->id == ids[p]) {
423						events->players[p]->joystick = SDL_JoystickListGetPointer(&events->joysticks, i);
424					}
425				}
426				++i;
427			}
428		}
429	}
430#endif
431}
432
433static void _pauseAfterFrame(struct mCoreThread* context) {
434	context->frameCallback = 0;
435	mCoreThreadPauseFromThread(context);
436}
437
438static void _mSDLHandleKeypress(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_KeyboardEvent* event) {
439	int key = -1;
440	if (!(event->keysym.mod & ~(KMOD_NUM | KMOD_CAPS))) {
441		key = mInputMapKey(sdlContext->bindings, SDL_BINDING_KEY, event->keysym.sym);
442	}
443	if (key != -1) {
444		mCoreThreadInterrupt(context);
445		if (event->type == SDL_KEYDOWN) {
446			context->core->addKeys(context->core, 1 << key);
447		} else {
448			context->core->clearKeys(context->core, 1 << key);
449		}
450		mCoreThreadContinue(context);
451		return;
452	}
453	if (event->keysym.sym == SDLK_TAB) {
454		context->impl->sync.audioWait = event->type != SDL_KEYDOWN;
455		return;
456	}
457	if (event->keysym.sym == SDLK_BACKQUOTE) {
458		mCoreThreadSetRewinding(context, event->type == SDL_KEYDOWN);
459	}
460	if (event->type == SDL_KEYDOWN) {
461		switch (event->keysym.sym) {
462#ifdef USE_DEBUGGERS
463		case SDLK_F11:
464			if (context->core->debugger) {
465				mDebuggerEnter(context->core->debugger, DEBUGGER_ENTER_MANUAL, NULL);
466			}
467			return;
468#endif
469#ifdef USE_PNG
470		case SDLK_F12:
471			mCoreTakeScreenshot(context->core);
472			return;
473#endif
474		case SDLK_BACKSLASH:
475			mCoreThreadPause(context);
476			context->frameCallback = _pauseAfterFrame;
477			mCoreThreadUnpause(context);
478			return;
479#ifdef BUILD_PANDORA
480		case SDLK_ESCAPE:
481			mCoreThreadEnd(context);
482			return;
483#endif
484		default:
485			if ((event->keysym.mod & GUI_MOD) && (event->keysym.mod & GUI_MOD) == event->keysym.mod) {
486				switch (event->keysym.sym) {
487#if SDL_VERSION_ATLEAST(2, 0, 0)
488				case SDLK_f:
489					SDL_SetWindowFullscreen(sdlContext->window, sdlContext->fullscreen ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);
490					sdlContext->fullscreen = !sdlContext->fullscreen;
491					sdlContext->windowUpdated = 1;
492					break;
493#endif
494				case SDLK_p:
495					mCoreThreadTogglePause(context);
496					break;
497				case SDLK_n:
498					mCoreThreadPause(context);
499					context->frameCallback = _pauseAfterFrame;
500					mCoreThreadUnpause(context);
501					break;
502				case SDLK_r:
503					mCoreThreadReset(context);
504					break;
505				default:
506					break;
507				}
508			}
509			if (event->keysym.mod & KMOD_SHIFT) {
510				switch (event->keysym.sym) {
511				case SDLK_F1:
512				case SDLK_F2:
513				case SDLK_F3:
514				case SDLK_F4:
515				case SDLK_F5:
516				case SDLK_F6:
517				case SDLK_F7:
518				case SDLK_F8:
519				case SDLK_F9:
520					mCoreThreadInterrupt(context);
521					mCoreSaveState(context->core, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SAVEDATA | SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
522					mCoreThreadContinue(context);
523					break;
524				default:
525					break;
526				}
527			} else {
528				switch (event->keysym.sym) {
529				case SDLK_F1:
530				case SDLK_F2:
531				case SDLK_F3:
532				case SDLK_F4:
533				case SDLK_F5:
534				case SDLK_F6:
535				case SDLK_F7:
536				case SDLK_F8:
537				case SDLK_F9:
538					mCoreThreadInterrupt(context);
539					mCoreLoadState(context->core, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
540					mCoreThreadContinue(context);
541					break;
542				default:
543					break;
544				}
545			}
546			return;
547		}
548	}
549}
550
551static void _mSDLHandleMouseButton(struct mCore* core, struct mSDLPlayer* sdlContext, const struct SDL_MouseButtonEvent* event) {
552	if (event->button != SDL_BUTTON_LEFT) {
553		return;
554	}
555	int x = event->x;
556	int y = event->y;
557#if SDL_VERSION_ATLEAST(2, 0, 0)
558	int windowW;
559	int windowH;
560	SDL_GetWindowSize(sdlContext->window, &windowW, &windowH);
561	unsigned coreW;
562	unsigned coreH;
563	core->desiredVideoDimensions(core, &coreW, &coreH);
564	x = x * coreW / windowW;
565	y = y * coreH / windowH;
566#endif
567	core->setCursorLocation(core, x, y);
568	core->setCursorDown(core, event->state == SDL_PRESSED);
569}
570
571static void _mSDLHandleMouseMotion(struct mCore* core, struct mSDLPlayer* sdlContext, const struct SDL_MouseMotionEvent* event) {
572	int x = event->x;
573	int y = event->y;
574#if SDL_VERSION_ATLEAST(2, 0, 0)
575	int windowW;
576	int windowH;
577	SDL_GetWindowSize(sdlContext->window, &windowW, &windowH);
578	unsigned coreW;
579	unsigned coreH;
580	core->desiredVideoDimensions(core, &coreW, &coreH);
581	x = x * coreW / windowW;
582	y = y * coreH / windowH;
583#endif
584	core->setCursorLocation(core, x, y);
585}
586
587static void _mSDLHandleJoyButton(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyButtonEvent* event) {
588	int key = 0;
589	key = mInputMapKey(sdlContext->bindings, SDL_BINDING_BUTTON, event->button);
590	if (key == -1) {
591		return;
592	}
593
594	mCoreThreadInterrupt(context);
595	if (event->type == SDL_JOYBUTTONDOWN) {
596		context->core->addKeys(context->core, 1 << key);
597	} else {
598		context->core->clearKeys(context->core, 1 << key);
599	}
600	mCoreThreadContinue(context);
601}
602
603static void _mSDLHandleJoyHat(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyHatEvent* event) {
604	int allKeys = mInputMapHat(sdlContext->bindings, SDL_BINDING_BUTTON, event->hat, -1);
605	if (allKeys == 0) {
606		return;
607	}
608
609	int keys = mInputMapHat(sdlContext->bindings, SDL_BINDING_BUTTON, event->hat, event->value);
610
611	mCoreThreadInterrupt(context);
612	context->core->clearKeys(context->core, allKeys ^ keys);
613	context->core->addKeys(context->core, keys);
614	mCoreThreadContinue(context);
615}
616
617static void _mSDLHandleJoyAxis(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyAxisEvent* event) {
618	int clearKeys = ~mInputClearAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, -1);
619	int newKeys = 0;
620	int key = mInputMapAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, event->value);
621	if (key != -1) {
622		newKeys |= 1 << key;
623	}
624	clearKeys &= ~newKeys;
625	mCoreThreadInterrupt(context);
626	context->core->clearKeys(context->core, clearKeys);
627	context->core->addKeys(context->core, newKeys);
628	mCoreThreadContinue(context);
629
630}
631
632#if SDL_VERSION_ATLEAST(2, 0, 0)
633static void _mSDLHandleWindowEvent(struct mSDLPlayer* sdlContext, const struct SDL_WindowEvent* event) {
634	switch (event->event) {
635	case SDL_WINDOWEVENT_SIZE_CHANGED:
636		sdlContext->windowUpdated = 1;
637		break;
638	}
639}
640#endif
641
642void mSDLHandleEvent(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const union SDL_Event* event) {
643	switch (event->type) {
644	case SDL_QUIT:
645		mCoreThreadEnd(context);
646		break;
647#if SDL_VERSION_ATLEAST(2, 0, 0)
648	case SDL_WINDOWEVENT:
649		_mSDLHandleWindowEvent(sdlContext, &event->window);
650		break;
651#else
652	case SDL_VIDEORESIZE:
653		sdlContext->newWidth = event->resize.w;
654		sdlContext->newHeight = event->resize.h;
655		sdlContext->windowUpdated = 1;
656		break;
657#endif
658	case SDL_KEYDOWN:
659	case SDL_KEYUP:
660		_mSDLHandleKeypress(context, sdlContext, &event->key);
661		break;
662	case SDL_MOUSEBUTTONDOWN:
663	case SDL_MOUSEBUTTONUP:
664		_mSDLHandleMouseButton(context->core, sdlContext, &event->button);
665		break;
666	case SDL_MOUSEMOTION:
667		_mSDLHandleMouseMotion(context->core, sdlContext, &event->motion);
668		break;
669	case SDL_JOYBUTTONDOWN:
670	case SDL_JOYBUTTONUP:
671		_mSDLHandleJoyButton(context, sdlContext, &event->jbutton);
672		break;
673	case SDL_JOYHATMOTION:
674		_mSDLHandleJoyHat(context, sdlContext, &event->jhat);
675		break;
676	case SDL_JOYAXISMOTION:
677		_mSDLHandleJoyAxis(context, sdlContext, &event->jaxis);
678		break;
679	}
680}
681
682#if SDL_VERSION_ATLEAST(2, 0, 0)
683static void _mSDLSetRumble(struct mRumble* rumble, int enable) {
684	struct mSDLRumble* sdlRumble = (struct mSDLRumble*) rumble;
685	if (!sdlRumble->p->joystick || !sdlRumble->p->joystick->haptic || !SDL_HapticRumbleSupported(sdlRumble->p->joystick->haptic)) {
686		return;
687	}
688	int8_t originalLevel = sdlRumble->level;
689	sdlRumble->level += enable;
690	if (CircleBufferSize(&sdlRumble->history) == RUMBLE_PWM) {
691		int8_t oldLevel;
692		CircleBufferRead8(&sdlRumble->history, &oldLevel);
693		sdlRumble->level -= oldLevel;
694	}
695	CircleBufferWrite8(&sdlRumble->history, enable);
696	if (sdlRumble->level == originalLevel) {
697		return;
698	}
699	float activeLevel = ceil(RUMBLE_STEPS * sdlRumble->level / (float) RUMBLE_PWM) / RUMBLE_STEPS;
700	if (fabsf(sdlRumble->activeLevel - activeLevel) < 0.75 / RUMBLE_STEPS) {
701		return;
702	}
703	sdlRumble->activeLevel = activeLevel;
704	if (sdlRumble->activeLevel > 0.5 / RUMBLE_STEPS) {
705		SDL_HapticRumbleStop(sdlRumble->p->joystick->haptic);
706		SDL_HapticRumblePlay(sdlRumble->p->joystick->haptic, activeLevel, 500);
707	} else {
708		SDL_HapticRumbleStop(sdlRumble->p->joystick->haptic);
709	}
710}
711#endif
712
713static int32_t _readTilt(struct mSDLPlayer* player, int axis) {
714	if (!player->joystick) {
715		return 0;
716	}
717	return SDL_JoystickGetAxis(player->joystick->joystick, axis) * 0x3800;
718}
719
720static int32_t _mSDLReadTiltX(struct mRotationSource* source) {
721	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
722	return _readTilt(rotation->p, rotation->axisX);
723}
724
725static int32_t _mSDLReadTiltY(struct mRotationSource* source) {
726	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
727	return _readTilt(rotation->p, rotation->axisY);
728}
729
730static int32_t _mSDLReadGyroZ(struct mRotationSource* source) {
731	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
732	float z = rotation->zDelta;
733	return z * rotation->gyroSensitivity;
734}
735
736static void _mSDLRotationSample(struct mRotationSource* source) {
737	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
738	SDL_JoystickUpdate();
739	if (!rotation->p->joystick) {
740		return;
741	}
742
743	int x = SDL_JoystickGetAxis(rotation->p->joystick->joystick, rotation->gyroX);
744	int y = SDL_JoystickGetAxis(rotation->p->joystick->joystick, rotation->gyroY);
745	union {
746		float f;
747		int32_t i;
748	} theta = { .f = atan2f(y, x) - atan2f(rotation->oldY, rotation->oldX) };
749	if (isnan(theta.f)) {
750		theta.f = 0.0f;
751	} else if (theta.f > M_PI) {
752		theta.f -= 2.0f * M_PI;
753	} else if (theta.f < -M_PI) {
754		theta.f += 2.0f * M_PI;
755	}
756	rotation->oldX = x;
757	rotation->oldY = y;
758
759	float oldZ = 0;
760	if (CircleBufferSize(&rotation->zHistory) == GYRO_STEPS * sizeof(float)) {
761		CircleBufferRead32(&rotation->zHistory, (int32_t*) &oldZ);
762	}
763	CircleBufferWrite32(&rotation->zHistory, theta.i);
764	rotation->zDelta += theta.f - oldZ;
765}
766
767#if SDL_VERSION_ATLEAST(2, 0, 0)
768void mSDLSuspendScreensaver(struct mSDLEvents* events) {
769	if (events->screensaverSuspendDepth == 0 && events->screensaverSuspendable) {
770		SDL_DisableScreenSaver();
771	}
772	++events->screensaverSuspendDepth;
773}
774
775void mSDLResumeScreensaver(struct mSDLEvents* events) {
776	--events->screensaverSuspendDepth;
777	if (events->screensaverSuspendDepth == 0 && events->screensaverSuspendable) {
778		SDL_EnableScreenSaver();
779	}
780}
781
782void mSDLSetScreensaverSuspendable(struct mSDLEvents* events, bool suspendable) {
783	bool wasSuspendable = events->screensaverSuspendable;
784	events->screensaverSuspendable = suspendable;
785	if (events->screensaverSuspendDepth > 0) {
786		if (suspendable && !wasSuspendable) {
787			SDL_DisableScreenSaver();
788		} else if (!suspendable && wasSuspendable) {
789			SDL_EnableScreenSaver();
790		}
791	} else {
792		SDL_EnableScreenSaver();
793	}
794}
795#endif