all repos — mgba @ 2da3d3e6ba282d437c69a8d80b0a2e0f46214a39

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