all repos — mgba @ e2807b39158b867d1226b211dc592d5d9a24dbba

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