summaryrefslogtreecommitdiffstats
path: root/src/core/hle/service/hid/hid.cpp
blob: 6254237faecb818c9d1e31b33247ff550b36aea3 (plain) (blame)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Copyright 2018 yuzu emulator team
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#include <atomic>
#include "common/logging/log.h"
#include "core/core_timing.h"
#include "core/frontend/input.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/client_port.h"
#include "core/hle/kernel/client_session.h"
#include "core/hle/kernel/shared_memory.h"
#include "core/hle/service/hid/hid.h"
#include "core/hle/service/service.h"

namespace Service {
namespace HID {

// Updating period for each HID device.
// TODO(shinyquagsire23): These need better values.
constexpr u64 pad_update_ticks = BASE_CLOCK_RATE / 234;
constexpr u64 accelerometer_update_ticks = BASE_CLOCK_RATE / 104;
constexpr u64 gyroscope_update_ticks = BASE_CLOCK_RATE / 101;

class IAppletResource final : public ServiceFramework<IAppletResource> {
public:
    IAppletResource() : ServiceFramework("IAppletResource") {
        static const FunctionInfo functions[] = {
            {0, &IAppletResource::GetSharedMemoryHandle, "GetSharedMemoryHandle"},
        };
        RegisterHandlers(functions);

        shared_mem = Kernel::SharedMemory::Create(
            nullptr, 0x40000, Kernel::MemoryPermission::ReadWrite, Kernel::MemoryPermission::Read,
            0, Kernel::MemoryRegion::BASE, "HID:SharedMemory");

        // Register update callbacks
        pad_update_event = CoreTiming::RegisterEvent(
            "HID::UpdatePadCallback",
            [this](u64 userdata, int cycles_late) { UpdatePadCallback(userdata, cycles_late); });

        // TODO(shinyquagsire23): Other update callbacks? (accel, gyro?)

        CoreTiming::ScheduleEvent(pad_update_ticks, pad_update_event);
    }

private:
    void GetSharedMemoryHandle(Kernel::HLERequestContext& ctx) {
        IPC::RequestBuilder rb{ctx, 2, 1};
        rb.Push(RESULT_SUCCESS);
        rb.PushCopyObjects(shared_mem);
        LOG_DEBUG(Service, "called");
    }

    void LoadInputDevices() {
        std::transform(Settings::values.buttons.begin() + Settings::NativeButton::BUTTON_HID_BEGIN,
                       Settings::values.buttons.begin() + Settings::NativeButton::BUTTON_HID_END,
                       buttons.begin(), Input::CreateDevice<Input::ButtonDevice>);
        // TODO(shinyquagsire23): sticks, gyro, touch, mouse, keyboard
    }

    void UpdatePadCallback(u64 userdata, int cycles_late) {
        SharedMemory* mem = reinterpret_cast<SharedMemory*>(shared_mem->GetPointer());

        if (is_device_reload_pending.exchange(false))
            LoadInputDevices();

        // Set up controllers as neon red+blue Joy-Con attached to console
        ControllerHeader& controller_header = mem->controllers[Controller_Handheld].header;
        controller_header.type = ControllerType_Handheld | ControllerType_JoyconPair;
        controller_header.single_colors_descriptor = ColorDesc_ColorsNonexistent;
        controller_header.right_color_body = JOYCON_BODY_NEON_RED;
        controller_header.right_color_buttons = JOYCON_BUTTONS_NEON_RED;
        controller_header.left_color_body = JOYCON_BODY_NEON_BLUE;
        controller_header.left_color_buttons = JOYCON_BUTTONS_NEON_BLUE;

        for (int layoutIdx = 0; layoutIdx < HID_NUM_LAYOUTS; layoutIdx++) {
            ControllerLayout& layout = mem->controllers[Controller_Handheld].layouts[layoutIdx];
            layout.header.num_entries = HID_NUM_ENTRIES;
            layout.header.max_entry_index = HID_NUM_ENTRIES - 1;

            // HID shared memory stores the state of the past 17 samples in a circlular buffer,
            // each with a timestamp in number of samples since boot.
            layout.header.timestamp_ticks = CoreTiming::GetTicks();
            layout.header.latest_entry = (layout.header.latest_entry + 1) % HID_NUM_ENTRIES;

            ControllerInputEntry& entry = layout.entries[layout.header.latest_entry];
            entry.connection_state = ConnectionState_Connected | ConnectionState_Wired;
            entry.timestamp++;
            entry.timestamp_2++; // TODO(shinyquagsire23): Is this always identical to timestamp?

            // TODO(shinyquagsire23): Set up some LUTs for each layout mapping in the future?
            // For now everything is just the default handheld layout, but split Joy-Con will
            // rotate the face buttons and directions for certain layouts.
            ControllerPadState& state = entry.buttons;
            using namespace Settings::NativeButton;
            state.a.Assign(buttons[A - BUTTON_HID_BEGIN]->GetStatus());
            state.b.Assign(buttons[B - BUTTON_HID_BEGIN]->GetStatus());
            state.x.Assign(buttons[X - BUTTON_HID_BEGIN]->GetStatus());
            state.y.Assign(buttons[Y - BUTTON_HID_BEGIN]->GetStatus());
            state.lstick.Assign(buttons[LStick - BUTTON_HID_BEGIN]->GetStatus());
            state.rstick.Assign(buttons[RStick - BUTTON_HID_BEGIN]->GetStatus());
            state.l.Assign(buttons[L - BUTTON_HID_BEGIN]->GetStatus());
            state.r.Assign(buttons[R - BUTTON_HID_BEGIN]->GetStatus());
            state.zl.Assign(buttons[ZL - BUTTON_HID_BEGIN]->GetStatus());
            state.zr.Assign(buttons[ZR - BUTTON_HID_BEGIN]->GetStatus());
            state.plus.Assign(buttons[Plus - BUTTON_HID_BEGIN]->GetStatus());
            state.minus.Assign(buttons[Minus - BUTTON_HID_BEGIN]->GetStatus());

            state.dleft.Assign(buttons[DLeft - BUTTON_HID_BEGIN]->GetStatus());
            state.dup.Assign(buttons[DUp - BUTTON_HID_BEGIN]->GetStatus());
            state.dright.Assign(buttons[DRight - BUTTON_HID_BEGIN]->GetStatus());
            state.ddown.Assign(buttons[DDown - BUTTON_HID_BEGIN]->GetStatus());

            state.lstick_left.Assign(buttons[LStick_Left - BUTTON_HID_BEGIN]->GetStatus());
            state.lstick_up.Assign(buttons[LStick_Up - BUTTON_HID_BEGIN]->GetStatus());
            state.lstick_right.Assign(buttons[LStick_Right - BUTTON_HID_BEGIN]->GetStatus());
            state.lstick_down.Assign(buttons[LStick_Down - BUTTON_HID_BEGIN]->GetStatus());

            state.rstick_left.Assign(buttons[RStick_Left - BUTTON_HID_BEGIN]->GetStatus());
            state.rstick_up.Assign(buttons[RStick_Up - BUTTON_HID_BEGIN]->GetStatus());
            state.rstick_right.Assign(buttons[RStick_Right - BUTTON_HID_BEGIN]->GetStatus());
            state.rstick_down.Assign(buttons[RStick_Down - BUTTON_HID_BEGIN]->GetStatus());

            state.sl.Assign(buttons[SL - BUTTON_HID_BEGIN]->GetStatus());
            state.sr.Assign(buttons[SR - BUTTON_HID_BEGIN]->GetStatus());

            // TODO(shinyquagsire23): Analog stick vals

            // TODO(shinyquagsire23): Update pad info proper, (circular buffers, timestamps,
            // layouts)
        }

        // TODO(shinyquagsire23): Update touch info

        // TODO(shinyquagsire23): Signal events

        // Reschedule recurrent event
        CoreTiming::ScheduleEvent(pad_update_ticks - cycles_late, pad_update_event);
    }

    // Handle to shared memory region designated to HID service
    Kernel::SharedPtr<Kernel::SharedMemory> shared_mem;

    // CoreTiming update events
    CoreTiming::EventType* pad_update_event;

    // Stored input state info
    std::atomic<bool> is_device_reload_pending{true};
    std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeButton::NUM_BUTTONS_HID>
        buttons;
};

class Hid final : public ServiceFramework<Hid> {
public:
    Hid() : ServiceFramework("hid") {
        static const FunctionInfo functions[] = {
            {0x00000000, &Hid::CreateAppletResource, "CreateAppletResource"},
        };
        RegisterHandlers(functions);
    }
    ~Hid() = default;

private:
    void CreateAppletResource(Kernel::HLERequestContext& ctx) {
        auto client_port = std::make_shared<IAppletResource>()->CreatePort();
        auto session = client_port->Connect();
        if (session.Succeeded()) {
            LOG_DEBUG(Service, "called, initialized IAppletResource -> session=%u",
                      (*session)->GetObjectId());
            IPC::RequestBuilder rb{ctx, 2, 0, 1};
            rb.Push(RESULT_SUCCESS);
            rb.PushMoveObjects(std::move(session).Unwrap());
        } else {
            UNIMPLEMENTED();
        }
    }
};

void ReloadInputDevices() {}

void InstallInterfaces(SM::ServiceManager& service_manager) {
    std::make_shared<Hid>()->InstallAsService(service_manager);
}

} // namespace HID
} // namespace Service