all repos — mgba @ 78526ae71a7776c57b3a63a74c46031bf7a9a4f8

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