aboutsummaryrefslogtreecommitdiffziptar.gz
path: root/src/Godosa.Core/Input/GamepadState.cs
blob: 5f1d5a5deeb4543f9e0e80bc5ae4fc76c7e23e0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System.Numerics;

namespace Godosa.Core.Input;

[Flags]
public enum PadButtons
{
    None = 0,
    A = 1 << 0,
    B = 1 << 1,
    X = 1 << 2,
    Y = 1 << 3,
    Back = 1 << 4,
    Start = 1 << 5,
    LeftShoulder = 1 << 6,
    RightShoulder = 1 << 7,
    DpadUp = 1 << 8,
    DpadDown = 1 << 9,
    DpadLeft = 1 << 10,
    DpadRight = 1 << 11,
}

/// <summary>Raw held pad state, no game meaning: sticks −1…1 (SDL convention, stick up =
/// −Y), triggers 0…1. Each game maps it to its own input frame.</summary>
public readonly record struct GamepadState(Vector2 LeftStick, Vector2 RightStick, float LeftTrigger, float RightTrigger, PadButtons Buttons)
{
    public bool Held(PadButtons button) => (Buttons & button) != 0;
}

/// <summary>Input-script pad events (<c>PadA PadB PadX PadY PadBack PadStart PadUp PadDown
/// PadLeft PadRight PadLB PadRB PadLT PadRT</c>, case-insensitive): triggers go full on/off.</summary>
public static class GamepadScript
{
    public static GamepadState? Apply(GamepadState state, string name, bool down)
    {
        string key = name.ToLowerInvariant();
        if (key == "padlt") return state with { LeftTrigger = down ? 1f : 0f };
        if (key == "padrt") return state with { RightTrigger = down ? 1f : 0f };
        PadButtons button = key switch
        {
            "pada" => PadButtons.A,
            "padb" => PadButtons.B,
            "padx" => PadButtons.X,
            "pady" => PadButtons.Y,
            "padback" => PadButtons.Back,
            "padstart" => PadButtons.Start,
            "padup" => PadButtons.DpadUp,
            "paddown" => PadButtons.DpadDown,
            "padleft" => PadButtons.DpadLeft,
            "padright" => PadButtons.DpadRight,
            "padlb" => PadButtons.LeftShoulder,
            "padrb" => PadButtons.RightShoulder,
            _ => PadButtons.None,
        };
        if (button == PadButtons.None) return null;
        return state with { Buttons = down ? state.Buttons | button : state.Buttons & ~button };
    }
}