package me.hammerle.snuviengine.api; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import static org.lwjgl.glfw.GLFW.*; public final class Gamepad { public static final class GamepadButton { private final String name; private final int mapping; private boolean isDown = false; private int time = 0; private boolean isReleased = false; protected GamepadButton(String name, int mapping) { this.name = name; this.mapping = mapping; } public String getName() { return name; } protected int getMapping() { return mapping; } protected void tick(boolean isDown) { if(isReleased) { isReleased = false; time = 0; } if(this.isDown && !isDown) { isReleased = true; time++; } this.isDown = isDown; if(isDown) { time++; } } public boolean isDown() { return isDown; } public boolean isReleased() { return isReleased; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } } public final GamepadButton a = new GamepadButton("A", 1); public final GamepadButton b = new GamepadButton("B", 2); public final GamepadButton x = new GamepadButton("X", 0); public final GamepadButton y = new GamepadButton("Y", 3); public final GamepadButton l = new GamepadButton("L", 4); public final GamepadButton r = new GamepadButton("R", 5); public final GamepadButton start = new GamepadButton("Start", 9); public final GamepadButton select = new GamepadButton("Select", 8); public final GamepadButton left = new GamepadButton("Left", 0); public final GamepadButton right = new GamepadButton("Right", 0); public final GamepadButton up = new GamepadButton("Up", 1); public final GamepadButton down = new GamepadButton("Down", 1); private final GamepadButton[] buttons = new GamepadButton[]{ a, b, x, y, l, r, start, select }; public final GamepadButton[] bindings = new GamepadButton[]{ a, b, x, y, l, r, start, select, left, right, up, down }; public final int joystickId; protected Gamepad(int joystickId) { this.joystickId = joystickId; } protected void tick() { if(!glfwJoystickPresent(joystickId)) { return; } updateButtons(); updateAxes(); } private void updateButtons() { ByteBuffer buttonBuffer = glfwGetJoystickButtons(joystickId); if(buttonBuffer == null) { return; } for(GamepadButton binding : buttons) { binding.tick(buttonBuffer.get(binding.getMapping()) != 0); } } private void updateAxes() { FloatBuffer axesBuffer = glfwGetJoystickAxes(joystickId); if(axesBuffer == null) { return; } left.tick(axesBuffer.get(left.getMapping()) < -0.5f); right.tick(axesBuffer.get(right.getMapping()) > 0.5f); up.tick(axesBuffer.get(up.getMapping()) < -0.5f); down.tick(axesBuffer.get(down.getMapping()) > 0.5f); } }