all repos — mgba @ a748e0c795a4ab7117eaac78349cecb303873ddf

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				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[16];
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, const struct Configuration* config) {
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
343			const char* joystickName;
344#if SDL_VERSION_ATLEAST(2, 0, 0)
345			joystickName = SDL_JoystickName(joystick->joystick);
346#else
347			joystickName = SDL_JoystickName(SDL_JoystickIndex(joystick->joystick));
348#endif
349			size_t i;
350			for (i = 0; (int) i < events->playersAttached; ++i) {
351				if (events->players[i]->joystick) {
352					continue;
353				}
354				if (events->preferredJoysticks[i] && strcmp(events->preferredJoysticks[i], joystickName) == 0) {
355					events->players[i]->joystick = joystick;
356					if (config) {
357						mInputProfileLoad(events->players[i]->bindings, SDL_BINDING_BUTTON, config, joystickName);
358					}
359					return;
360				}
361			}
362			for (i = 0; (int) i < events->playersAttached; ++i) {
363				if (events->players[i]->joystick) {
364					continue;
365				}
366				events->players[i]->joystick = joystick;
367				if (config) {
368					mInputProfileLoad(events->players[i]->bindings, SDL_BINDING_BUTTON, config, joystickName);
369				}
370				break;
371			}
372		} else if (event.type == SDL_JOYDEVICEREMOVED) {
373			SDL_JoystickID ids[MAX_PLAYERS] = { 0 };
374			size_t i;
375			for (i = 0; (int) i < events->playersAttached; ++i) {
376				if (events->players[i]->joystick) {
377					ids[i] = events->players[i]->joystick->id;
378					events->players[i]->joystick = 0;
379				} else {
380					ids[i] = -1;
381				}
382			}
383			for (i = 0; i < SDL_JoystickListSize(&events->joysticks);) {
384				struct SDL_JoystickCombo* joystick = SDL_JoystickListGetPointer(&events->joysticks, i);
385				if (joystick->id == event.jdevice.which) {
386					SDL_JoystickListShift(&events->joysticks, i, 1);
387					continue;
388				}
389				SDL_JoystickListGetPointer(&events->joysticks, i)->index = i;
390				int p;
391				for (p = 0; p < events->playersAttached; ++p) {
392					if (joystick->id == ids[p]) {
393						events->players[p]->joystick = SDL_JoystickListGetPointer(&events->joysticks, i);
394					}
395				}
396				++i;
397			}
398		}
399	}
400#endif
401}
402
403static void _pauseAfterFrame(struct mCoreThread* context) {
404	context->frameCallback = 0;
405	mCoreThreadPauseFromThread(context);
406}
407
408static void _mSDLHandleKeypress(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_KeyboardEvent* event) {
409	int key = -1;
410	if (!(event->keysym.mod & ~(KMOD_NUM | KMOD_CAPS))) {
411		key = mInputMapKey(sdlContext->bindings, SDL_BINDING_KEY, event->keysym.sym);
412	}
413	if (key != -1) {
414		mCoreThreadInterrupt(context);
415		if (event->type == SDL_KEYDOWN) {
416			context->core->addKeys(context->core, 1 << key);
417		} else {
418			context->core->clearKeys(context->core, 1 << key);
419		}
420		mCoreThreadContinue(context);
421		return;
422	}
423	if (event->keysym.sym == SDLK_TAB) {
424		context->impl->sync.audioWait = event->type != SDL_KEYDOWN;
425		return;
426	}
427	if (event->keysym.sym == SDLK_BACKQUOTE) {
428		mCoreThreadSetRewinding(context, event->type == SDL_KEYDOWN);
429	}
430	if (event->type == SDL_KEYDOWN) {
431		switch (event->keysym.sym) {
432#ifdef USE_DEBUGGERS
433		case SDLK_F11:
434			if (context->core->debugger) {
435				mDebuggerEnter(context->core->debugger, DEBUGGER_ENTER_MANUAL, NULL);
436			}
437			return;
438#endif
439#ifdef USE_PNG
440		case SDLK_F12:
441			mCoreTakeScreenshot(context->core);
442			return;
443#endif
444		case SDLK_BACKSLASH:
445			mCoreThreadPause(context);
446			context->frameCallback = _pauseAfterFrame;
447			mCoreThreadUnpause(context);
448			return;
449#ifdef BUILD_PANDORA
450		case SDLK_ESCAPE:
451			mCoreThreadEnd(context);
452			return;
453#endif
454		default:
455			if ((event->keysym.mod & GUI_MOD) && (event->keysym.mod & GUI_MOD) == event->keysym.mod) {
456				switch (event->keysym.sym) {
457#if SDL_VERSION_ATLEAST(2, 0, 0)
458				case SDLK_f:
459					SDL_SetWindowFullscreen(sdlContext->window, sdlContext->fullscreen ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);
460					sdlContext->fullscreen = !sdlContext->fullscreen;
461					sdlContext->windowUpdated = 1;
462					break;
463#endif
464				case SDLK_p:
465					mCoreThreadTogglePause(context);
466					break;
467				case SDLK_n:
468					mCoreThreadPause(context);
469					context->frameCallback = _pauseAfterFrame;
470					mCoreThreadUnpause(context);
471					break;
472				case SDLK_r:
473					mCoreThreadReset(context);
474					break;
475				default:
476					break;
477				}
478			}
479			if (event->keysym.mod & KMOD_SHIFT) {
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					mCoreSaveState(context->core, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SAVEDATA | SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
492					mCoreThreadContinue(context);
493					break;
494				default:
495					break;
496				}
497			} else {
498				switch (event->keysym.sym) {
499				case SDLK_F1:
500				case SDLK_F2:
501				case SDLK_F3:
502				case SDLK_F4:
503				case SDLK_F5:
504				case SDLK_F6:
505				case SDLK_F7:
506				case SDLK_F8:
507				case SDLK_F9:
508					mCoreThreadInterrupt(context);
509					mCoreLoadState(context->core, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
510					mCoreThreadContinue(context);
511					break;
512				default:
513					break;
514				}
515			}
516			return;
517		}
518	}
519}
520
521static void _mSDLHandleJoyButton(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyButtonEvent* event) {
522	int key = 0;
523	key = mInputMapKey(sdlContext->bindings, SDL_BINDING_BUTTON, event->button);
524	if (key == -1) {
525		return;
526	}
527
528	mCoreThreadInterrupt(context);
529	if (event->type == SDL_JOYBUTTONDOWN) {
530		context->core->addKeys(context->core, 1 << key);
531	} else {
532		context->core->clearKeys(context->core, 1 << key);
533	}
534	mCoreThreadContinue(context);
535}
536
537static void _mSDLHandleJoyHat(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyHatEvent* event) {
538	int allKeys = mInputMapHat(sdlContext->bindings, SDL_BINDING_BUTTON, event->hat, -1);
539	if (allKeys == 0) {
540		return;
541	}
542
543	int keys = mInputMapHat(sdlContext->bindings, SDL_BINDING_BUTTON, event->hat, event->value);
544
545	mCoreThreadInterrupt(context);
546	context->core->clearKeys(context->core, allKeys ^ keys);
547	context->core->addKeys(context->core, keys);
548	mCoreThreadContinue(context);
549}
550
551static void _mSDLHandleJoyAxis(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyAxisEvent* event) {
552	int clearKeys = ~mInputClearAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, -1);
553	int newKeys = 0;
554	int key = mInputMapAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, event->value);
555	if (key != -1) {
556		newKeys |= 1 << key;
557	}
558	clearKeys &= ~newKeys;
559	mCoreThreadInterrupt(context);
560	context->core->clearKeys(context->core, clearKeys);
561	context->core->addKeys(context->core, newKeys);
562	mCoreThreadContinue(context);
563
564}
565
566#if SDL_VERSION_ATLEAST(2, 0, 0)
567static void _mSDLHandleWindowEvent(struct mSDLPlayer* sdlContext, const struct SDL_WindowEvent* event) {
568	switch (event->event) {
569	case SDL_WINDOWEVENT_SIZE_CHANGED:
570		sdlContext->windowUpdated = 1;
571		break;
572	}
573}
574#endif
575
576void mSDLHandleEvent(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const union SDL_Event* event) {
577	switch (event->type) {
578	case SDL_QUIT:
579		mCoreThreadEnd(context);
580		break;
581#if SDL_VERSION_ATLEAST(2, 0, 0)
582	case SDL_WINDOWEVENT:
583		_mSDLHandleWindowEvent(sdlContext, &event->window);
584		break;
585#endif
586	case SDL_KEYDOWN:
587	case SDL_KEYUP:
588		_mSDLHandleKeypress(context, sdlContext, &event->key);
589		break;
590	case SDL_JOYBUTTONDOWN:
591	case SDL_JOYBUTTONUP:
592		_mSDLHandleJoyButton(context, sdlContext, &event->jbutton);
593		break;
594	case SDL_JOYHATMOTION:
595		_mSDLHandleJoyHat(context, sdlContext, &event->jhat);
596		break;
597	case SDL_JOYAXISMOTION:
598		_mSDLHandleJoyAxis(context, sdlContext, &event->jaxis);
599		break;
600	}
601}
602
603#if SDL_VERSION_ATLEAST(2, 0, 0)
604static void _mSDLSetRumble(struct mRumble* rumble, int enable) {
605	struct mSDLRumble* sdlRumble = (struct mSDLRumble*) rumble;
606	if (!sdlRumble->p->joystick || !sdlRumble->p->joystick->haptic || !SDL_HapticRumbleSupported(sdlRumble->p->joystick->haptic)) {
607		return;
608	}
609	int8_t originalLevel = sdlRumble->level;
610	sdlRumble->level += enable;
611	if (CircleBufferSize(&sdlRumble->history) == RUMBLE_PWM) {
612		int8_t oldLevel;
613		CircleBufferRead8(&sdlRumble->history, &oldLevel);
614		sdlRumble->level -= oldLevel;
615	}
616	CircleBufferWrite8(&sdlRumble->history, enable);
617	if (sdlRumble->level == originalLevel) {
618		return;
619	}
620	float activeLevel = ceil(RUMBLE_STEPS * sdlRumble->level / (float) RUMBLE_PWM) / RUMBLE_STEPS;
621	if (fabsf(sdlRumble->activeLevel - activeLevel) < 0.75 / RUMBLE_STEPS) {
622		return;
623	}
624	sdlRumble->activeLevel = activeLevel;
625	if (sdlRumble->activeLevel > 0.5 / RUMBLE_STEPS) {
626		SDL_HapticRumbleStop(sdlRumble->p->joystick->haptic);
627		SDL_HapticRumblePlay(sdlRumble->p->joystick->haptic, activeLevel, 500);
628	} else {
629		SDL_HapticRumbleStop(sdlRumble->p->joystick->haptic);
630	}
631}
632#endif
633
634static int32_t _readTilt(struct mSDLPlayer* player, int axis) {
635	if (!player->joystick) {
636		return 0;
637	}
638	return SDL_JoystickGetAxis(player->joystick->joystick, axis) * 0x3800;
639}
640
641static int32_t _mSDLReadTiltX(struct mRotationSource* source) {
642	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
643	return _readTilt(rotation->p, rotation->axisX);
644}
645
646static int32_t _mSDLReadTiltY(struct mRotationSource* source) {
647	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
648	return _readTilt(rotation->p, rotation->axisY);
649}
650
651static int32_t _mSDLReadGyroZ(struct mRotationSource* source) {
652	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
653	float z = rotation->zDelta;
654	return z * rotation->gyroSensitivity;
655}
656
657static void _mSDLRotationSample(struct mRotationSource* source) {
658	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
659	SDL_JoystickUpdate();
660	if (!rotation->p->joystick) {
661		return;
662	}
663
664	int x = SDL_JoystickGetAxis(rotation->p->joystick->joystick, rotation->gyroX);
665	int y = SDL_JoystickGetAxis(rotation->p->joystick->joystick, rotation->gyroY);
666	union {
667		float f;
668		int32_t i;
669	} theta = { .f = atan2f(y, x) - atan2f(rotation->oldY, rotation->oldX) };
670	if (isnan(theta.f)) {
671		theta.f = 0.0f;
672	} else if (theta.f > M_PI) {
673		theta.f -= 2.0f * M_PI;
674	} else if (theta.f < -M_PI) {
675		theta.f += 2.0f * M_PI;
676	}
677	rotation->oldX = x;
678	rotation->oldY = y;
679
680	float oldZ = 0;
681	if (CircleBufferSize(&rotation->zHistory) == GYRO_STEPS * sizeof(float)) {
682		CircleBufferRead32(&rotation->zHistory, (int32_t*) &oldZ);
683	}
684	CircleBufferWrite32(&rotation->zHistory, theta.i);
685	rotation->zDelta += theta.f - oldZ;
686}
687
688#if SDL_VERSION_ATLEAST(2, 0, 0)
689void mSDLSuspendScreensaver(struct mSDLEvents* events) {
690	if (events->screensaverSuspendDepth == 0 && events->screensaverSuspendable) {
691		SDL_DisableScreenSaver();
692	}
693	++events->screensaverSuspendDepth;
694}
695
696void mSDLResumeScreensaver(struct mSDLEvents* events) {
697	--events->screensaverSuspendDepth;
698	if (events->screensaverSuspendDepth == 0 && events->screensaverSuspendable) {
699		SDL_EnableScreenSaver();
700	}
701}
702
703void mSDLSetScreensaverSuspendable(struct mSDLEvents* events, bool suspendable) {
704	bool wasSuspendable = events->screensaverSuspendable;
705	events->screensaverSuspendable = suspendable;
706	if (events->screensaverSuspendDepth > 0) {
707		if (suspendable && !wasSuspendable) {
708			SDL_DisableScreenSaver();
709		} else if (!suspendable && wasSuspendable) {
710			SDL_EnableScreenSaver();
711		}
712	} else {
713		SDL_EnableScreenSaver();
714	}
715}
716#endif