all repos — mgba @ 9dfcef3f45efe580e252ec8bc3852257e9de9fd6

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