all repos — mgba @ 9ddf82bebc1915ce8bee833e44b0a8eaa6451bbc

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		if (claimed) {
197			continue;
198		}
199
200		if (firstUnclaimed == SIZE_MAX) {
201			firstUnclaimed = i;
202		}
203
204#if SDL_VERSION_ATLEAST(2, 0, 0)
205		char joystickName[34] = {0};
206		SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(SDL_JoystickListGetPointer(&events->joysticks, i)->joystick), joystickName, sizeof(joystickName));
207#else
208		const char* joystickName = SDL_JoystickName(SDL_JoystickIndex(SDL_JoystickListGetPointer(&events->joysticks, i)->joystick));
209		if (!joystickName) {
210			continue;
211		}
212#endif
213		if (events->preferredJoysticks[player->playerId] && strcmp(events->preferredJoysticks[player->playerId], joystickName) == 0) {
214			index = i;
215			break;
216		}
217	}
218
219	if (index == SIZE_MAX && firstUnclaimed != SIZE_MAX) {
220		index = firstUnclaimed;
221	}
222
223	if (index != SIZE_MAX) {
224		player->joystick = SDL_JoystickListGetPointer(&events->joysticks, index);
225
226#if SDL_VERSION_ATLEAST(2, 0, 0)
227		if (player->joystick->haptic) {
228			SDL_HapticRumbleInit(player->joystick->haptic);
229		}
230#endif
231	}
232
233	++events->playersAttached;
234	return true;
235}
236
237void mSDLDetachPlayer(struct mSDLEvents* events, struct mSDLPlayer* player) {
238	if (player != events->players[player->playerId]) {
239		return;
240	}
241	int i;
242	for (i = player->playerId; i < events->playersAttached; ++i) {
243		if (i + 1 < MAX_PLAYERS) {
244			events->players[i] = events->players[i + 1];
245		}
246		if (i < events->playersAttached - 1) {
247			events->players[i]->playerId = i;
248		}
249	}
250	--events->playersAttached;
251	CircleBufferDeinit(&player->rotation.zHistory);
252#if SDL_VERSION_ATLEAST(2, 0, 0)
253	CircleBufferDeinit(&player->rumble.history);
254#endif
255}
256
257void mSDLPlayerLoadConfig(struct mSDLPlayer* context, const struct Configuration* config) {
258	mInputMapLoad(context->bindings, SDL_BINDING_KEY, config);
259	if (context->joystick) {
260		mInputMapLoad(context->bindings, SDL_BINDING_BUTTON, config);
261#if SDL_VERSION_ATLEAST(2, 0, 0)
262		char name[34] = {0};
263		SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(context->joystick->joystick), name, sizeof(name));
264#else
265		const char* name = SDL_JoystickName(SDL_JoystickIndex(context->joystick->joystick));
266		if (!name) {
267			return;
268		}
269#endif
270		mInputProfileLoad(context->bindings, SDL_BINDING_BUTTON, config, name);
271
272		const char* value;
273		char* end;
274		int numAxes = SDL_JoystickNumAxes(context->joystick->joystick);
275		int axis;
276		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisX", name);
277		if (value) {
278			axis = strtol(value, &end, 0);
279			if (axis >= 0 && axis < numAxes && end && !*end) {
280				context->rotation.axisX = axis;
281			}
282		}
283		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisY", name);
284		if (value) {
285			axis = strtol(value, &end, 0);
286			if (axis >= 0 && axis < numAxes && end && !*end) {
287				context->rotation.axisY = axis;
288			}
289		}
290		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisX", name);
291		if (value) {
292			axis = strtol(value, &end, 0);
293			if (axis >= 0 && axis < numAxes && end && !*end) {
294				context->rotation.gyroX = axis;
295			}
296		}
297		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisY", name);
298		if (value) {
299			axis = strtol(value, &end, 0);
300			if (axis >= 0 && axis < numAxes && end && !*end) {
301				context->rotation.gyroY = axis;
302			}
303		}
304		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroSensitivity", name);
305		if (value) {
306			float sensitivity = strtof_u(value, &end);
307			if (end && !*end) {
308				context->rotation.gyroSensitivity = sensitivity;
309			}
310		}
311	}
312}
313
314void mSDLPlayerSaveConfig(const struct mSDLPlayer* context, struct Configuration* config) {
315	if (context->joystick) {
316#if SDL_VERSION_ATLEAST(2, 0, 0)
317		char name[34] = {0};
318		SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(context->joystick->joystick), name, sizeof(name));
319#else
320		const char* name = SDL_JoystickName(SDL_JoystickIndex(context->joystick->joystick));
321		if (!name) {
322			return;
323		}
324#endif
325		char value[16];
326		snprintf(value, sizeof(value), "%i", context->rotation.axisX);
327		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisX", value, name);
328		snprintf(value, sizeof(value), "%i", context->rotation.axisY);
329		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisY", value, name);
330		snprintf(value, sizeof(value), "%i", context->rotation.gyroX);
331		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisX", value, name);
332		snprintf(value, sizeof(value), "%i", context->rotation.gyroY);
333		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisY", value, name);
334		snprintf(value, sizeof(value), "%g", context->rotation.gyroSensitivity);
335		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroSensitivity", value, name);
336	}
337}
338
339void mSDLPlayerChangeJoystick(struct mSDLEvents* events, struct mSDLPlayer* player, size_t index) {
340	if (player->playerId >= MAX_PLAYERS || index >= SDL_JoystickListSize(&events->joysticks)) {
341		return;
342	}
343	player->joystick = SDL_JoystickListGetPointer(&events->joysticks, index);
344}
345
346void mSDLUpdateJoysticks(struct mSDLEvents* events, const struct Configuration* config) {
347	// Pump SDL joystick events without eating the rest of the events
348	SDL_JoystickUpdate();
349#if SDL_VERSION_ATLEAST(2, 0, 0)
350	SDL_Event event;
351	while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED) > 0) {
352		if (event.type == SDL_JOYDEVICEADDED) {
353			SDL_Joystick* sdlJoystick = SDL_JoystickOpen(event.jdevice.which);
354			if (!sdlJoystick) {
355				continue;
356			}
357			ssize_t joysticks[MAX_PLAYERS];
358			ssize_t i;
359			// Pointers can get invalidated, so we'll need to refresh them
360			for (i = 0; i < events->playersAttached && i < MAX_PLAYERS; ++i) {
361				joysticks[i] = events->players[i]->joystick ? (ssize_t) SDL_JoystickListIndex(&events->joysticks, events->players[i]->joystick) : -1;
362				events->players[i]->joystick = NULL;
363			}
364			struct SDL_JoystickCombo* joystick = SDL_JoystickListAppend(&events->joysticks);
365			joystick->joystick = sdlJoystick;
366			joystick->id = SDL_JoystickInstanceID(joystick->joystick);
367			joystick->index = SDL_JoystickListSize(&events->joysticks) - 1;
368#if SDL_VERSION_ATLEAST(2, 0, 0)
369			joystick->haptic = SDL_HapticOpenFromJoystick(joystick->joystick);
370#endif
371			for (i = 0; i < events->playersAttached && i < MAX_PLAYERS; ++i) {
372				if (joysticks[i] != -1) {
373					events->players[i]->joystick = SDL_JoystickListGetPointer(&events->joysticks, joysticks[i]);
374				}
375			}
376
377#if SDL_VERSION_ATLEAST(2, 0, 0)
378			char joystickName[34] = {0};
379			SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick->joystick), joystickName, sizeof(joystickName));
380#else
381			const char* joystickName = SDL_JoystickName(SDL_JoystickIndex(joystick->joystick));
382			if (joystickName)
383#endif
384			{
385				for (i = 0; (int) i < events->playersAttached; ++i) {
386					if (events->players[i]->joystick) {
387						continue;
388					}
389					if (events->preferredJoysticks[i] && strcmp(events->preferredJoysticks[i], joystickName) == 0) {
390						events->players[i]->joystick = joystick;
391						if (config) {
392							mInputProfileLoad(events->players[i]->bindings, SDL_BINDING_BUTTON, config, joystickName);
393						}
394						return;
395					}
396				}
397			}
398			for (i = 0; (int) i < events->playersAttached; ++i) {
399				if (events->players[i]->joystick) {
400					continue;
401				}
402				events->players[i]->joystick = joystick;
403				if (config
404#if !SDL_VERSION_ATLEAST(2, 0, 0)
405					&& joystickName
406#endif
407					) {
408					mInputProfileLoad(events->players[i]->bindings, SDL_BINDING_BUTTON, config, joystickName);
409				}
410				break;
411			}
412		} else if (event.type == SDL_JOYDEVICEREMOVED) {
413			SDL_JoystickID ids[MAX_PLAYERS] = { 0 };
414			size_t i;
415			for (i = 0; (int) i < events->playersAttached; ++i) {
416				if (events->players[i]->joystick) {
417					ids[i] = events->players[i]->joystick->id;
418					events->players[i]->joystick = 0;
419				} else {
420					ids[i] = -1;
421				}
422			}
423			for (i = 0; i < SDL_JoystickListSize(&events->joysticks);) {
424				struct SDL_JoystickCombo* joystick = SDL_JoystickListGetPointer(&events->joysticks, i);
425				if (joystick->id == event.jdevice.which) {
426					SDL_JoystickListShift(&events->joysticks, i, 1);
427					continue;
428				}
429				SDL_JoystickListGetPointer(&events->joysticks, i)->index = i;
430				int p;
431				for (p = 0; p < events->playersAttached; ++p) {
432					if (joystick->id == ids[p]) {
433						events->players[p]->joystick = SDL_JoystickListGetPointer(&events->joysticks, i);
434					}
435				}
436				++i;
437			}
438		}
439	}
440#endif
441}
442
443static void _pauseAfterFrame(struct mCoreThread* context) {
444	context->frameCallback = 0;
445	mCoreThreadPauseFromThread(context);
446}
447
448static void _mSDLHandleKeypress(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_KeyboardEvent* event) {
449	int key = -1;
450	if (!(event->keysym.mod & ~(KMOD_NUM | KMOD_CAPS))) {
451		key = mInputMapKey(sdlContext->bindings, SDL_BINDING_KEY, event->keysym.sym);
452	}
453	if (key != -1) {
454		mCoreThreadInterrupt(context);
455		if (event->type == SDL_KEYDOWN) {
456			context->core->addKeys(context->core, 1 << key);
457		} else {
458			context->core->clearKeys(context->core, 1 << key);
459		}
460		mCoreThreadContinue(context);
461		return;
462	}
463	if (event->keysym.sym == SDLK_TAB) {
464		context->impl->sync.audioWait = event->type != SDL_KEYDOWN;
465		return;
466	}
467	if (event->keysym.sym == SDLK_BACKQUOTE) {
468		mCoreThreadSetRewinding(context, event->type == SDL_KEYDOWN);
469	}
470	if (event->type == SDL_KEYDOWN) {
471		switch (event->keysym.sym) {
472#ifdef USE_DEBUGGERS
473		case SDLK_F11:
474			if (context->core->debugger) {
475				mDebuggerEnter(context->core->debugger, DEBUGGER_ENTER_MANUAL, NULL);
476			}
477			return;
478#endif
479#ifdef USE_PNG
480		case SDLK_F12:
481			mCoreTakeScreenshot(context->core);
482			return;
483#endif
484		case SDLK_BACKSLASH:
485			mCoreThreadPause(context);
486			context->frameCallback = _pauseAfterFrame;
487			mCoreThreadUnpause(context);
488			return;
489#ifdef BUILD_PANDORA
490		case SDLK_ESCAPE:
491			mCoreThreadEnd(context);
492			return;
493#endif
494		default:
495			if ((event->keysym.mod & GUI_MOD) && (event->keysym.mod & GUI_MOD) == event->keysym.mod) {
496				switch (event->keysym.sym) {
497#if SDL_VERSION_ATLEAST(2, 0, 0)
498				case SDLK_f:
499					SDL_SetWindowFullscreen(sdlContext->window, sdlContext->fullscreen ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);
500					sdlContext->fullscreen = !sdlContext->fullscreen;
501					sdlContext->windowUpdated = 1;
502					break;
503#endif
504				case SDLK_p:
505					mCoreThreadTogglePause(context);
506					break;
507				case SDLK_n:
508					mCoreThreadPause(context);
509					context->frameCallback = _pauseAfterFrame;
510					mCoreThreadUnpause(context);
511					break;
512				case SDLK_r:
513					mCoreThreadReset(context);
514					break;
515				default:
516					break;
517				}
518			}
519			if (event->keysym.mod & KMOD_SHIFT) {
520				switch (event->keysym.sym) {
521				case SDLK_F1:
522				case SDLK_F2:
523				case SDLK_F3:
524				case SDLK_F4:
525				case SDLK_F5:
526				case SDLK_F6:
527				case SDLK_F7:
528				case SDLK_F8:
529				case SDLK_F9:
530					mCoreThreadInterrupt(context);
531					mCoreSaveState(context->core, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SAVEDATA | SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
532					mCoreThreadContinue(context);
533					break;
534				default:
535					break;
536				}
537			} else {
538				switch (event->keysym.sym) {
539				case SDLK_F1:
540				case SDLK_F2:
541				case SDLK_F3:
542				case SDLK_F4:
543				case SDLK_F5:
544				case SDLK_F6:
545				case SDLK_F7:
546				case SDLK_F8:
547				case SDLK_F9:
548					mCoreThreadInterrupt(context);
549					mCoreLoadState(context->core, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
550					mCoreThreadContinue(context);
551					break;
552				default:
553					break;
554				}
555			}
556			return;
557		}
558	}
559}
560
561static void _mSDLHandleJoyButton(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyButtonEvent* event) {
562	int key = 0;
563	key = mInputMapKey(sdlContext->bindings, SDL_BINDING_BUTTON, event->button);
564	if (key == -1) {
565		return;
566	}
567
568	mCoreThreadInterrupt(context);
569	if (event->type == SDL_JOYBUTTONDOWN) {
570		context->core->addKeys(context->core, 1 << key);
571	} else {
572		context->core->clearKeys(context->core, 1 << key);
573	}
574	mCoreThreadContinue(context);
575}
576
577static void _mSDLHandleJoyHat(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyHatEvent* event) {
578	int allKeys = mInputMapHat(sdlContext->bindings, SDL_BINDING_BUTTON, event->hat, -1);
579	if (allKeys == 0) {
580		return;
581	}
582
583	int keys = mInputMapHat(sdlContext->bindings, SDL_BINDING_BUTTON, event->hat, event->value);
584
585	mCoreThreadInterrupt(context);
586	context->core->clearKeys(context->core, allKeys ^ keys);
587	context->core->addKeys(context->core, keys);
588	mCoreThreadContinue(context);
589}
590
591static void _mSDLHandleJoyAxis(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyAxisEvent* event) {
592	int clearKeys = ~mInputClearAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, -1);
593	int newKeys = 0;
594	int key = mInputMapAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, event->value);
595	if (key != -1) {
596		newKeys |= 1 << key;
597	}
598	clearKeys &= ~newKeys;
599	mCoreThreadInterrupt(context);
600	context->core->clearKeys(context->core, clearKeys);
601	context->core->addKeys(context->core, newKeys);
602	mCoreThreadContinue(context);
603
604}
605
606#if SDL_VERSION_ATLEAST(2, 0, 0)
607static void _mSDLHandleWindowEvent(struct mSDLPlayer* sdlContext, const struct SDL_WindowEvent* event) {
608	switch (event->event) {
609	case SDL_WINDOWEVENT_SIZE_CHANGED:
610		sdlContext->windowUpdated = 1;
611		break;
612	}
613}
614#endif
615
616void mSDLHandleEvent(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const union SDL_Event* event) {
617	switch (event->type) {
618	case SDL_QUIT:
619		mCoreThreadEnd(context);
620		break;
621#if SDL_VERSION_ATLEAST(2, 0, 0)
622	case SDL_WINDOWEVENT:
623		_mSDLHandleWindowEvent(sdlContext, &event->window);
624		break;
625#else
626	case SDL_VIDEORESIZE:
627		sdlContext->newWidth = event->resize.w;
628		sdlContext->newHeight = event->resize.h;
629		sdlContext->windowUpdated = 1;
630		break;
631#endif
632	case SDL_KEYDOWN:
633	case SDL_KEYUP:
634		_mSDLHandleKeypress(context, sdlContext, &event->key);
635		break;
636	case SDL_JOYBUTTONDOWN:
637	case SDL_JOYBUTTONUP:
638		_mSDLHandleJoyButton(context, sdlContext, &event->jbutton);
639		break;
640	case SDL_JOYHATMOTION:
641		_mSDLHandleJoyHat(context, sdlContext, &event->jhat);
642		break;
643	case SDL_JOYAXISMOTION:
644		_mSDLHandleJoyAxis(context, sdlContext, &event->jaxis);
645		break;
646	}
647}
648
649#if SDL_VERSION_ATLEAST(2, 0, 0)
650static void _mSDLSetRumble(struct mRumble* rumble, int enable) {
651	struct mSDLRumble* sdlRumble = (struct mSDLRumble*) rumble;
652	if (!sdlRumble->p->joystick || !sdlRumble->p->joystick->haptic || !SDL_HapticRumbleSupported(sdlRumble->p->joystick->haptic)) {
653		return;
654	}
655	int8_t originalLevel = sdlRumble->level;
656	sdlRumble->level += enable;
657	if (CircleBufferSize(&sdlRumble->history) == RUMBLE_PWM) {
658		int8_t oldLevel;
659		CircleBufferRead8(&sdlRumble->history, &oldLevel);
660		sdlRumble->level -= oldLevel;
661	}
662	CircleBufferWrite8(&sdlRumble->history, enable);
663	if (sdlRumble->level == originalLevel) {
664		return;
665	}
666	float activeLevel = ceil(RUMBLE_STEPS * sdlRumble->level / (float) RUMBLE_PWM) / RUMBLE_STEPS;
667	if (fabsf(sdlRumble->activeLevel - activeLevel) < 0.75 / RUMBLE_STEPS) {
668		return;
669	}
670	sdlRumble->activeLevel = activeLevel;
671	if (sdlRumble->activeLevel > 0.5 / RUMBLE_STEPS) {
672		SDL_HapticRumbleStop(sdlRumble->p->joystick->haptic);
673		SDL_HapticRumblePlay(sdlRumble->p->joystick->haptic, activeLevel, 500);
674	} else {
675		SDL_HapticRumbleStop(sdlRumble->p->joystick->haptic);
676	}
677}
678#endif
679
680static int32_t _readTilt(struct mSDLPlayer* player, int axis) {
681	if (!player->joystick) {
682		return 0;
683	}
684	return SDL_JoystickGetAxis(player->joystick->joystick, axis) * 0x3800;
685}
686
687static int32_t _mSDLReadTiltX(struct mRotationSource* source) {
688	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
689	return _readTilt(rotation->p, rotation->axisX);
690}
691
692static int32_t _mSDLReadTiltY(struct mRotationSource* source) {
693	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
694	return _readTilt(rotation->p, rotation->axisY);
695}
696
697static int32_t _mSDLReadGyroZ(struct mRotationSource* source) {
698	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
699	float z = rotation->zDelta;
700	return z * rotation->gyroSensitivity;
701}
702
703static void _mSDLRotationSample(struct mRotationSource* source) {
704	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
705	SDL_JoystickUpdate();
706	if (!rotation->p->joystick) {
707		return;
708	}
709
710	int x = SDL_JoystickGetAxis(rotation->p->joystick->joystick, rotation->gyroX);
711	int y = SDL_JoystickGetAxis(rotation->p->joystick->joystick, rotation->gyroY);
712	union {
713		float f;
714		int32_t i;
715	} theta = { .f = atan2f(y, x) - atan2f(rotation->oldY, rotation->oldX) };
716	if (isnan(theta.f)) {
717		theta.f = 0.0f;
718	} else if (theta.f > M_PI) {
719		theta.f -= 2.0f * M_PI;
720	} else if (theta.f < -M_PI) {
721		theta.f += 2.0f * M_PI;
722	}
723	rotation->oldX = x;
724	rotation->oldY = y;
725
726	float oldZ = 0;
727	if (CircleBufferSize(&rotation->zHistory) == GYRO_STEPS * sizeof(float)) {
728		CircleBufferRead32(&rotation->zHistory, (int32_t*) &oldZ);
729	}
730	CircleBufferWrite32(&rotation->zHistory, theta.i);
731	rotation->zDelta += theta.f - oldZ;
732}
733
734#if SDL_VERSION_ATLEAST(2, 0, 0)
735void mSDLSuspendScreensaver(struct mSDLEvents* events) {
736	if (events->screensaverSuspendDepth == 0 && events->screensaverSuspendable) {
737		SDL_DisableScreenSaver();
738	}
739	++events->screensaverSuspendDepth;
740}
741
742void mSDLResumeScreensaver(struct mSDLEvents* events) {
743	--events->screensaverSuspendDepth;
744	if (events->screensaverSuspendDepth == 0 && events->screensaverSuspendable) {
745		SDL_EnableScreenSaver();
746	}
747}
748
749void mSDLSetScreensaverSuspendable(struct mSDLEvents* events, bool suspendable) {
750	bool wasSuspendable = events->screensaverSuspendable;
751	events->screensaverSuspendable = suspendable;
752	if (events->screensaverSuspendDepth > 0) {
753		if (suspendable && !wasSuspendable) {
754			SDL_DisableScreenSaver();
755		} else if (!suspendable && wasSuspendable) {
756			SDL_EnableScreenSaver();
757		}
758	} else {
759		SDL_EnableScreenSaver();
760	}
761}
762#endif