Cogs.Core
EmscriptenGamepad.h
1#pragma once
2
3#include "ViewContext.h"
4
5#include <emscripten/html5.h>
6
7#include "Input/InputManager.h"
8#include "Input/GamepadMapping.h"
9
10using namespace Cogs::Core;
11
12namespace Cogs
13{
14 namespace Platform
15 {
16 static EM_BOOL gamepadCallback(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData);
17
19 {
20 public:
21 void initialize(Core::ViewContext* viewContext)
22 {
23 this->view = viewContext;
24
25 emscripten_set_gamepadconnected_callback(this, 1, gamepadCallback);
26 emscripten_set_gamepaddisconnected_callback(this, 1, gamepadCallback);
27 }
28
29 const int axisMapping[6] = {
30 Gamepad::AxisNo::StickLeftX,
31 Gamepad::AxisNo::StickLeftY,
32 Gamepad::AxisNo::StickRightX,
33 Gamepad::AxisNo::StickRightY,
34 Gamepad::AxisNo::TriggerLeft,
35 Gamepad::AxisNo::TriggerRight,
36 };
37
38 const float axisMultiplier[6] = {
39 1.0f,
40 -1.0f,
41 1.0f,
42 -1.0f,
43 1.0f,
44 1.0f
45 };
46
47 const int buttonMapping[16] = {
48 Gamepad::ButtonNo::A,
49 Gamepad::ButtonNo::B,
50 Gamepad::ButtonNo::Y,
51 Gamepad::ButtonNo::X,
52 Gamepad::ButtonNo::LeftShoulder,
53 Gamepad::ButtonNo::RightShoulder,
54 Gamepad::ButtonNo::PlaceHolder0,
55 Gamepad::ButtonNo::PlaceHolder1,
56 Gamepad::ButtonNo::Back,
57 Gamepad::ButtonNo::Start,
58 Gamepad::ButtonNo::LeftThumb,
59 Gamepad::ButtonNo::RightThumb,
60 Gamepad::ButtonNo::DPadUp,
61 Gamepad::ButtonNo::DPadDown,
62 Gamepad::ButtonNo::DPadLeft,
63 Gamepad::ButtonNo::DPadRight,
64 };
65
66 void update()
67 {
68 auto inputManager = view->inputManager.get();
69
70 int numGamepads = 0;
71 if (EMSCRIPTEN_RESULT_SUCCESS == emscripten_sample_gamepad_data()) {
72 numGamepads = emscripten_get_num_gamepads();
73 }
74
75 for (int i = 0; i < numGamepads; ++i) {
76 EmscriptenGamepadEvent g{};
77 emscripten_get_gamepad_status(i, &g);
78
79 auto & state = inputManager->getDevice((InputDevices::EValues)(InputDevices::Gamepad0 + i));
80 state.isConnected = true;
81
82 state.axisMask = 0x000000000000003F;
83 state.buttonMask = 0x000000000000FFFF;
84
85 for (int i = 0; i < g.numButtons; ++i) {
86 state.setButton(buttonMapping[i], g.digitalButton[i]);
87 }
88
89 for (int i = 0; i < g.numAxes; ++i) {
90 state.setAxis(axisMapping[i], axisMultiplier[i] * static_cast<float>(g.axis[i]));
91 }
92 }
93 }
94
95 private:
97 };
98
99 EM_BOOL gamepadCallback(int /*eventType*/, const EmscriptenGamepadEvent */*gamepadEvent*/, void * /*userData*/)
100 {
101 return 1;
102 }
103 }
104}
std::unique_ptr< class InputManager > inputManager
Definition: ViewContext.h:78
Contains the Engine, Renderer, resource managers and other systems needed to run Cogs....
Contains all Cogs related functionality.
Definition: FieldSetter.h:23