all repos — mgba @ 4fd170ac38a9c312f3dd1d0dd912d2c761f60fdb

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