#include #include #include #include #include "input.h" struct pw_input *pw_input_init(SDL_Window *window) { if (!window) { SDL_InvalidParamError("window"); return NULL; } struct pw_input *input = SDL_calloc(1, sizeof(*input)); if (!input) { return NULL; } input->clipboard.size = 1024; input->clipboard.buffer = SDL_calloc(input->clipboard.size, sizeof(*input->clipboard.buffer)); if (!input->clipboard.buffer) { SDL_free(input); return NULL; } input->window = window; return input; } void pw_input_free(struct pw_input *input) { if (!input) { SDL_InvalidParamError("input"); return; } SDL_free(input->clipboard.buffer); SDL_free(input); } static void clear_queue(struct pw_keyboard_queue *queue) { queue->start = queue->end = 0; } bool pw_input_reset(struct pw_input *input, struct pw_players *players) { if (!input) { return SDL_InvalidParamError("input"); } if (!players) { return SDL_InvalidParamError("players"); } bool connected[PW_PLAYERS_MAX]; input->nplayers = pw_players_status(players, connected); SDL_zeroa(input->players); clear_queue(&input->keyboard.scancodes); clear_queue(&input->keyboard.text); SDL_zerop(&input->mouse.rel); *input->clipboard.buffer = '\0'; return true; } static bool handle_connection(struct pw_input *input, struct pw_players *players) { size_t previous = input->nplayers; bool connected[PW_PLAYERS_MAX]; input->nplayers = pw_players_status(players, connected); for (size_t i = 0; i < SDL_arraysize(connected); ++i) { input->players[i] *= (uint8_t)connected[i]; } // We need to clear the button states of player 2 in case it was // set because of the special POOM handling, and a new controller // connected. if (previous == 1 && input->nplayers > 1) { input->players[1] = 0; } return players; } static void set_button(enum pw_button *player, enum pw_button button, bool pressed) { // Note that we map several different controls (axis and buttons) to the // same PICO-8 button, meaning that they can compete for the 'set' state // of these buttons. We opt to, for simplicity, to just take the value // of the last control that set this state. This means that if you press // both buttons for X, and release one of them, PICO-8 will think that // the button was released (even while the second button was held). We // are OK with this for now, and will consider changing this in case it // ends up feeling unatural while playing. if (pressed) { *player |= button; } else { *player &= ~button; } } static bool handle_axis(struct pw_input *input, struct pw_players *players, SDL_GamepadAxisEvent *event) { size_t i = pw_player_find(players, event->which); if (i >= PW_PLAYERS_MAX) { return true; } enum pw_button *player = &input->players[i]; switch (event->axis) { case SDL_GAMEPAD_AXIS_LEFTX: set_button(player, PW_BUTTON_LEFT, event->value < -PW_AXIS_THRESHOLD); set_button(player, PW_BUTTON_RIGHT, event->value > PW_AXIS_THRESHOLD); break; case SDL_GAMEPAD_AXIS_LEFTY: set_button(player, PW_BUTTON_UP, event->value < -PW_AXIS_THRESHOLD); set_button(player, PW_BUTTON_DOWN, event->value > PW_AXIS_THRESHOLD); break; } // Some special POOM handling, which uses both player's inputs for controls. // This allows one player's directions be used for turning, and another for // strafing. if (!i && input->nplayers == 1) { enum pw_button *p2 = &input->players[1]; switch (event->axis) { case SDL_GAMEPAD_AXIS_RIGHTX: set_button(p2, PW_BUTTON_LEFT, event->value < -PW_AXIS_THRESHOLD); set_button(p2, PW_BUTTON_RIGHT, event->value > PW_AXIS_THRESHOLD); break; case SDL_GAMEPAD_AXIS_RIGHTY: set_button(p2, PW_BUTTON_UP, event->value < -PW_AXIS_THRESHOLD); set_button(p2, PW_BUTTON_DOWN, event->value > PW_AXIS_THRESHOLD); break; case SDL_GAMEPAD_AXIS_LEFT_TRIGGER: set_button(p2, PW_BUTTON_O, event->value > PW_TRIGGER_THRESHOLD); break; case SDL_GAMEPAD_AXIS_RIGHT_TRIGGER: set_button(p2, PW_BUTTON_X, event->value > PW_TRIGGER_THRESHOLD); break; } } return true; } static bool handle_button(struct pw_input *input, struct pw_players *players, SDL_GamepadButtonEvent *event) { size_t i = pw_player_find(players, event->which); if (i >= PW_PLAYERS_MAX) { return true; } enum pw_button *player = &input->players[i]; switch (event->button) { case SDL_GAMEPAD_BUTTON_SOUTH: set_button(player, PW_BUTTON_O, event->down); break; case SDL_GAMEPAD_BUTTON_EAST: set_button(player, PW_BUTTON_X, event->down); break; case SDL_GAMEPAD_BUTTON_WEST: set_button(player, PW_BUTTON_X, event->down); break; case SDL_GAMEPAD_BUTTON_NORTH: set_button(player, PW_BUTTON_O, event->down); break; case SDL_GAMEPAD_BUTTON_BACK: set_button(player, PW_BUTTON_MENU, event->down); break; case SDL_GAMEPAD_BUTTON_START: set_button(player, PW_BUTTON_MENU, event->down); break; case SDL_GAMEPAD_BUTTON_LEFT_SHOULDER: set_button(player, PW_BUTTON_O, event->down); break; case SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER: set_button(player, PW_BUTTON_X, event->down); break; case SDL_GAMEPAD_BUTTON_DPAD_UP: set_button(player, PW_BUTTON_UP, event->down); break; case SDL_GAMEPAD_BUTTON_DPAD_DOWN: set_button(player, PW_BUTTON_DOWN, event->down); break; case SDL_GAMEPAD_BUTTON_DPAD_LEFT: set_button(player, PW_BUTTON_LEFT, event->down); break; case SDL_GAMEPAD_BUTTON_DPAD_RIGHT: set_button(player, PW_BUTTON_RIGHT, event->down); break; } return true; } static bool enqueue_item(struct pw_keyboard_queue *queue, uint32_t item) { size_t next = (queue->end + 1) % PW_KEYBOARD_BUFFER_SIZE; if (next == queue->start) { return false; } queue->items[queue->end] = item; queue->end = next; return true; } static bool dequeue_item(struct pw_keyboard_queue *queue, uint32_t *item) { if (queue->start == queue->end) { return false; } *item = queue->items[queue->start]; queue->start = (queue->start + 1) % PW_KEYBOARD_BUFFER_SIZE; return true; } static int8_t scancode_to_p8scii(SDL_Scancode sc, SDL_Keymod mod) { switch (sc) { case SDL_SCANCODE_TAB: return 9; case SDL_SCANCODE_RETURN: case SDL_SCANCODE_KP_ENTER: return 13; case SDL_SCANCODE_BACKSPACE: return 8; case SDL_SCANCODE_ESCAPE: return 27; default: break; } // Clear other modifiers, PICO-8 requests things like Ctrl and Alt through a // separate `pw_input_keymod` call. mod &= SDL_KMOD_SHIFT | SDL_KMOD_CAPS; SDL_Keycode keycode = SDL_GetKeyFromScancode(sc, mod, false); if (keycode < 32 || keycode > 126) { // Non-ASCII characters (including the exceptions above) are mapped to // negative values which are ignored. Note that we _still_ need to push // these to the queue, as they trigger some generic "key pressed" code // in the PICO-8 runtime. return -1; } return (int8_t)keycode; } // SDL has a `SDL_SCANCODE_COUNT` of 512, so we can mask the scan code with // `512 - 1 = 0x1ff`. #define PW_SCANCODE_MASK 0x1ff #define PW_SCANCODE_PRESSED 0x80000000 #define PW_SCANCODE_REPEAT 0x40000000 #define PW_SCANCODE_MOD_SHIFT 9 static bool handle_key(struct pw_input *input, SDL_KeyboardEvent *event) { uint32_t sc = (uint32_t)event->scancode; if (sc > PW_SCANCODE_MASK) { // Ignore unsupported scancodes. return true; } if (event->down) { sc |= PW_SCANCODE_PRESSED; } if (event->repeat) { sc |= PW_SCANCODE_REPEAT; } sc |= (uint32_t)event->mod << PW_SCANCODE_MOD_SHIFT; // The scancode and key queue size was selected to not be an issue under // regular use, PICO-8 seems to drain many of the queue items ever frame // so I do not believe we will run into issues where the queue is full // in practice (which would manifest as dropped keys and potentially // keyboard state in PICO-8 drifting from the real keyboard state). Warn // in case either queue is full, and if this proves to be an issue in // practice consider either making the queue bigger or dynamically sized. if (!enqueue_item(&input->keyboard.scancodes, sc)) { SDL_LogDebug(0, "keyboard event queue full, dropping scancode"); } if (event->down) { int8_t key = scancode_to_p8scii(event->scancode, event->mod); if (!enqueue_item(&input->keyboard.text, (uint32_t)key)) { SDL_LogDebug(0, "keyboard text queue full, dropping key %d", key); } } return true; } static int32_t saturating_add(int32_t a, int32_t b) { int64_t result = (int64_t)a + (int64_t)b; return (int32_t)SDL_clamp(result, INT32_MIN, INT32_MAX); } static bool handle_wheel(struct pw_input *input, SDL_MouseWheelEvent *wheel) { #if SDL_VERSION_ATLEAST(3, 2, 12) input->mouse.wheel.dx = saturating_add(input->mouse.wheel.dx, wheel->integer_x); input->mouse.wheel.dy = saturating_add(input->mouse.wheel.dy, wheel->integer_y); #else // We approximate wheel movement for older SDL versions that do not support // the integer event values. This is slightly wrong (as we lose fractional // movement across frames), but good enough: this will likely only affect // homebrew versions with older SDL 3 ports that don't have mouse wheels // anyway. If this becomes a problem, we can change mouse wheel deltas to // be floats and report full ticks (similar to how we handle relative mouse // positions). if (!SDL_isnanf(wheel->x)) { input->mouse.wheel.dx = saturating_add( input->mouse.wheel.dx, (int32_t)SDL_clamp(wheel->x, -PW_MAX_SAFE_INT, PW_MAX_SAFE_INT)); } if (!SDL_isnanf(wheel->y)) { input->mouse.wheel.dy = saturating_add( input->mouse.wheel.dy, (int32_t)SDL_clamp(wheel->y, -PW_MAX_SAFE_INT, PW_MAX_SAFE_INT)); } #endif return true; } bool pw_input_event(struct pw_input *input, struct pw_players *players, SDL_Event *event) { if (!input) { SDL_InvalidParamError("input"); return false; } if (!players) { SDL_InvalidParamError("players"); return false; } if (!event) { SDL_InvalidParamError("event"); return false; } switch (event->type) { case SDL_EVENT_GAMEPAD_ADDED: case SDL_EVENT_GAMEPAD_REMOVED: return handle_connection(input, players); case SDL_EVENT_GAMEPAD_AXIS_MOTION: return handle_axis(input, players, &event->gaxis); case SDL_EVENT_GAMEPAD_BUTTON_UP: case SDL_EVENT_GAMEPAD_BUTTON_DOWN: return handle_button(input, players, &event->gbutton); case SDL_EVENT_KEY_DOWN: case SDL_EVENT_KEY_UP: return handle_key(input, &event->key); case SDL_EVENT_MOUSE_WHEEL: return handle_wheel(input, &event->wheel); default: return true; } } static uint32_t convert_scancode(SDL_Scancode scancode) { // Some of the scancodes have slightly different numbering. switch (scancode) { // TODO(nlordell): remap scancodes that are different in case we run into // any issues. default: return scancode; } } static int32_t convert_keycode(SDL_Scancode scancode, SDL_Keymod mod) { SDL_Keycode keycode = SDL_GetKeyFromScancode(scancode, mod, true); if (keycode & SDLK_EXTENDED_MASK) { // Not supported in older SDL versions. return 0; } else if (keycode & SDLK_SCANCODE_MASK) { // Scancode keys are encoded differently by Emscripten, so imitate that // here: return (int32_t)(keycode & ~SDLK_SCANCODE_MASK) + 1024; } else { return (int32_t)keycode; } } static enum pw_keymod convert_keymod_state(SDL_Keymod state) { enum pw_keymod mod = PW_KEYMOD_NONE; if (state & SDL_KMOD_LSHIFT) { mod |= PW_KEYMOD_LSHIFT; } if (state & SDL_KMOD_RSHIFT) { mod |= PW_KEYMOD_RSHIFT; } if (state & SDL_KMOD_LCTRL) { mod |= PW_KEYMOD_LCTRL; } if (state & SDL_KMOD_RCTRL) { mod |= PW_KEYMOD_RCTRL; } if (state & SDL_KMOD_LALT) { mod |= PW_KEYMOD_LALT; } if (state & SDL_KMOD_RALT) { mod |= PW_KEYMOD_RALT; } return mod; } static void update_keymod(struct pw_input *input) { SDL_Keymod state = SDL_GetModState(); input->keyboard.mod = convert_keymod_state(state); } static bool update_mouse(struct pw_input *input, struct pw_framebuffer *fb) { float x, y; SDL_MouseButtonFlags flags = SDL_GetMouseState(&x, &y); float xrel, yrel; SDL_GetRelativeMouseState(&xrel, &yrel); struct pw_coordinates pos; struct pw_coordinates rel; if (!pw_fb_coordinates(fb, x, y, false, &pos) || !pw_fb_coordinates(fb, xrel, yrel, true, &rel)) { return false; } input->mouse.button = PW_MOUSE_BUTTON_NONE; if (flags & SDL_BUTTON_LMASK) { input->mouse.button |= PW_MOUSE_BUTTON_LEFT; } if (flags & SDL_BUTTON_MMASK) { input->mouse.button |= PW_MOUSE_BUTTON_MIDDLE; } if (flags & SDL_BUTTON_RMASK) { input->mouse.button |= PW_MOUSE_BUTTON_RIGHT; } // PICO-8 computes coordinates based on the mouse window position (so, // when you scale the PICO-8 window such that there are black borders, // mouse movements within those borders correspond to positions // outside of `[0, 128)`. Since we run PICO-8 pretending that it has // an exact 128x128 window, clamp the mouse position to that. input->mouse.pos.x = SDL_clamp(pos.x, 0, PW_FB_WIDTH - 1); input->mouse.pos.y = SDL_clamp(pos.y, 0, PW_FB_HEIGHT - 1); // PICO-8 reports relative mouse motion in different units than the // absolute mouse positions. In paricular, it seems to expect a scale of // 4: under pointer lock, PICO-8 will increase `STAT(32)` by 1 for every // `STAT(38)` moved by 4. Convert the units. input->mouse.rel.x += rel.x * PW_MOUSE_RELATIVE_SCALE; input->mouse.rel.y += rel.y * PW_MOUSE_RELATIVE_SCALE; return true; } bool pw_input_iterate(struct pw_input *input, struct pw_framebuffer *fb) { if (!input) { SDL_InvalidParamError("input"); return false; } if (!fb) { SDL_InvalidParamError("fb"); return false; } update_keymod(input); return update_mouse(input, fb); } enum pw_window_flags pw_input_window(struct pw_input *input) { enum pw_window_flags result = PW_WINDOW_NONE; if (!input) { SDL_InvalidParamError("input"); return result; } SDL_WindowFlags flags = SDL_GetWindowFlags(input->window); if (!(flags & (SDL_WINDOW_OCCLUDED | SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED))) { result |= PW_WINDOW_VISIBLE; } if (flags & SDL_WINDOW_INPUT_FOCUS) { result |= PW_WINDOW_FOCUS; } return result; } size_t pw_input_players(struct pw_input *input) { if (!input) { SDL_InvalidParamError("input"); return 0; } return input->nplayers; } enum pw_button pw_input_btn(struct pw_input *input, size_t player) { if (!input) { SDL_InvalidParamError("input"); return PW_BUTTON_NONE; } if (player >= PW_PLAYERS_MAX) { SDL_InvalidParamError("player"); return PW_BUTTON_NONE; } enum pw_button button = input->players[player]; // PICO-8 only checks the menu state for player 1, so for that player, the // menu needs to be set if it is set for any player. if (!player) { for (size_t i = 1; i < PW_PLAYERS_MAX; i++) { button |= input->players[i] & PW_BUTTON_MENU; } } return button & PW_BUTTON_ALL; } enum pw_keymod pw_input_keymod(struct pw_input *input) { if (!input) { SDL_InvalidParamError("input"); return PW_KEYMOD_NONE; } return input->keyboard.mod; } bool pw_input_key(struct pw_input *input, int32_t *key) { if (!input) { if (key) { *key = -1; } return SDL_InvalidParamError("input"); } struct pw_keyboard_queue *q = &input->keyboard.text; if (key) { return dequeue_item(q, (uint32_t *)key); } else { return q->start != q->end; } } enum pw_mouse_button pw_input_mouse(struct pw_input *input, struct pw_coordinates *pos) { if (!input) { SDL_InvalidParamError("input"); return PW_MOUSE_BUTTON_NONE; } if (pos) { SDL_memcpy(pos, &input->mouse.pos, sizeof(*pos)); } return input->mouse.button; } void pw_input_wheel(struct pw_input *input, int32_t *dx, int32_t *dy) { static struct pw_mouse_wheel zero = {0}; struct pw_mouse_wheel *w; if (input) { w = &input->mouse.wheel; } else { SDL_InvalidParamError("input"); w = &zero; } if (dx) { *dx = w->dx; w->dx = 0; } if (dy) { *dy = w->dy; w->dy = 0; } } char *pw_input_clipboard(struct pw_input *input, size_t len) { if (!input) { SDL_InvalidParamError("input"); return NULL; } if (len == SIZE_MAX) { SDL_OutOfMemory(); return NULL; } size_t size = len + 1; if (size > input->clipboard.size) { char *buffer = SDL_realloc(input->clipboard.buffer, size); if (!buffer) { return NULL; } SDL_memset(buffer + input->clipboard.size, 0, size - input->clipboard.size); input->clipboard.buffer = buffer; input->clipboard.size = size; } return input->clipboard.buffer; } bool pw_input_clipboard_commit(struct pw_input *input) { if (!input) { return SDL_InvalidParamError("input"); } // Just to be sure always make the buffer end with NUL to prevent reads // past the end of the buffer. input->clipboard.buffer[input->clipboard.size - 1] = '\0'; return SDL_SetClipboardText(input->clipboard.buffer); } bool pw_input_clipboard_fetch(struct pw_input *input, size_t *len) { if (!input) { return SDL_InvalidParamError("input"); } if (!SDL_HasClipboardText()) { *input->clipboard.buffer = '\0'; *len = 0; return true; } char *text = SDL_GetClipboardText(); if (!text || !*text) { if (text) { SDL_free(text); } return false; } *len = SDL_strlen(text); if (*len >= input->clipboard.size) { SDL_free(input->clipboard.buffer); input->clipboard.buffer = text; input->clipboard.size = *len + 1; } else { SDL_memcpy(input->clipboard.buffer, text, *len + 1); SDL_free(text); } return true; } bool pw_input_poll(struct pw_input *input, union pw_input_event *event) { if (!input) { return SDL_InvalidParamError("input"); } if (!event) { // Just check whether or not there is queued event and return. return input->keyboard.scancodes.start != input->keyboard.scancodes.end || (int32_t)input->mouse.rel.x || (int32_t)input->mouse.rel.y; } uint32_t sc; if (dequeue_item(&input->keyboard.scancodes, &sc)) { SDL_Scancode scancode = (SDL_Scancode)(sc & PW_SCANCODE_MASK); SDL_Keymod mod = (SDL_Keymod)(sc >> PW_SCANCODE_MOD_SHIFT); event->type = PW_INPUT_EVENT_KEY; event->key.pressed = sc & PW_SCANCODE_PRESSED; event->key.repeat = sc & PW_SCANCODE_REPEAT; event->key.scancode = convert_scancode(scancode); event->key.keycode = convert_keycode(scancode, mod); event->key.mod = convert_keymod_state(mod); return true; } if ((int32_t)input->mouse.rel.x || (int32_t)input->mouse.rel.y) { event->type = PW_INPUT_EVENT_MOUSE; event->mouse.button = input->mouse.button; event->mouse.x = (int32_t)input->mouse.pos.x; event->mouse.y = (int32_t)input->mouse.pos.y; event->mouse.xrel = (int32_t)input->mouse.rel.x; event->mouse.yrel = (int32_t)input->mouse.rel.y; // Perserve inter-frame fractional mouse movements. This matters // because the FB pixels are very big, so moving your mouse slowly // (less than a single pixel per frame) would effectively cause it // to not move over time. float unused; input->mouse.rel.x = SDL_modff(input->mouse.rel.x, &unused); input->mouse.rel.y = SDL_modff(input->mouse.rel.y, &unused); return true; } return false; } bool pw_input_set_pointer_lock(struct pw_input *input, bool lock) { // TODO(nlordell): Unfortunately, we don't have access to PICO-8's exact // mouse position. Since it compute it internally based on relative mouse // movement, and because of different clamping and rounding semantics, it // is possible (i.e. likely) that we "jump" positions by a few coordinates // when exiting pointer lock mode, as it will start reading the system's // mouse coordinates which will disagree with its internal values. If we // did have PICO-8's mouse coordinates somehow, we should first warp the // mouse with `SDL_WarpMouseInWindow` to fix the jump. return SDL_SetWindowRelativeMouseMode(input->window, lock); } bool pw_input_get_pointer_lock(struct pw_input *input) { return SDL_GetWindowRelativeMouseMode(input->window); }