YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
KeyboardJoypad.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT)
3 * All rights reserved.
4 *
5 * This software may be modified and distributed under the terms of the
6 * BSD-2-Clause license. See the accompanying LICENSE file for details.
7 */
8
9#define GL_GLEXT_PROTOTYPES
10#define GL3_PROTOTYPES
11#define GL_SILENCE_DEPRECATION
12
13#include <GL/glew.h>
14
15#if defined(__APPLE__)
16#include <OpenGL/gl.h>
17#else
18#include <GL/gl.h>
19#endif
20
21#include <GLFW/glfw3.h>
22
23#include <imgui.h>
24#include <imgui_impl_glfw.h>
25#include <imgui_impl_opengl3.h>
26#include <stdio.h>
27
28#include <mutex>
29#include <atomic>
30#include <unordered_map>
31#include <string>
32#include <vector>
33#include <algorithm>
34#include <cmath>
35#include <thread>
36#include <sstream>
37#include <iomanip>
38
39#include <yarp/os/LogStream.h>
40
41#include <KeyboardJoypad.h>
43
45{
46 int sign = 1;
47 size_t index = 0;
48};
49
50enum class ButtonType
51{
52 REGULAR,
53 TOGGLE,
54};
55
56
58 std::string alias;
60 std::vector<ImGuiKey> keys;
61 std::vector<ButtonValue> values;
62 std::vector<ButtonValue> joypadAxisInputs;
63 std::vector<int> joypadButtonIndices;
64 int col{ 0 };
65 bool active{ false };
66 bool buttonPressed{ false };
67
68 float deadzone(float input, float deadzone) const
69 {
70 if (input > deadzone)
71 return (input - deadzone) / (1.0f - deadzone);
72 else return 0.0;
73 }
74
75 void render(const ImVec4& button_active_color, const ImVec4& button_inactive_color,
76 const ImVec2& buttonSize, bool hold_active, double joypadDeadzone,
77 const std::vector<float>& joypadAxisValues, const std::vector<bool>& joypadButtonValues,
78 std::vector<double>& outputValues)
79 {
80 bool regularButton = type == ButtonType::REGULAR;
81 bool toggleButton = type == ButtonType::TOGGLE;
82 bool anyKeyPressed = false;
83 bool anyKeyReleased = false;
84 for (ImGuiKey key : keys)
85 {
86 if (ImGui::IsKeyPressed(key))
87 {
88 anyKeyPressed = true;
89 }
90 if (ImGui::IsKeyReleased(key))
91 {
92 anyKeyReleased = true;
93 }
94 }
95
96 for (int i : joypadButtonIndices)
97 {
98 if (i >= 0 && i < joypadButtonValues.size())
99 {
100 if (joypadButtonValues[static_cast<size_t>(i)])
101 {
102 anyKeyPressed = true;
103 }
104 else
105 {
106 anyKeyReleased = true;
107 }
108 }
109 else if (i >= 0 && joypadButtonValues.size() > 0)
110 {
111 yCErrorOnce(KEYBOARDJOYPAD) << "The joypad button index" << i << "is out of range.";
112 }
113 }
114
115 float valueFromJoypadAxes = 0.0;
116 for (auto& axis : joypadAxisInputs)
117 {
118 if (axis.index >= 0 && axis.index < joypadAxisValues.size())
119 {
120 valueFromJoypadAxes += deadzone(axis.sign * joypadAxisValues[static_cast<size_t>(axis.index)], static_cast<float>(joypadDeadzone));
121 }
122 else if (axis.index >= 0 && joypadAxisValues.size() > 0)
123 {
124 yCError(KEYBOARDJOYPAD) << "The joypad axis index" << axis.index << "is out of range.";
125 axis.index = -1;
126 }
127 }
128
129 if (anyKeyPressed)
130 {
131 buttonPressed = true;
132 if (toggleButton || (regularButton && !hold_active))
133 {
134 active = true;
135 }
136 else
137 {
138 active = !active;
139 }
140 }
141 else if (buttonPressed && anyKeyReleased)
142 {
143 buttonPressed = false;
144 if (toggleButton || (regularButton && !hold_active))
145 active = false;
146 }
147
148 ImGuiStyle& style = ImGui::GetStyle();
149 const ImVec4& buttonColor = active || valueFromJoypadAxes > 0 ? button_active_color : button_inactive_color;
150 style.Colors[ImGuiCol_Button] = buttonColor;
151 style.Colors[ImGuiCol_ButtonHovered] = buttonColor;
152 style.Colors[ImGuiCol_ButtonActive] = buttonColor;
153
154 // Create a button
155 bool buttonReleased = ImGui::Button(alias.c_str(), buttonSize);
156 bool buttonKeptPressed = ImGui::IsItemActive();
157
158 if (buttonReleased && (toggleButton || (regularButton && hold_active)))
159 {
160 active = !active; //Toggle the button
161 }
162 else if (regularButton && buttonKeptPressed && !hold_active) //The button is clicked and is not a toggling button
163 {
164 active = true;
165 }
166 else if (regularButton && !buttonPressed && !hold_active) //The button is not clicked and is not a toggling button
167 {
168 active = false;
169 }
170
171 for (auto& value : values)
172 {
173 outputValues[value.index] += value.sign * (active + valueFromJoypadAxes);
174 }
175 }
176};
177
179{
180 std::vector<std::vector<ButtonState>> rows;
182 std::string name;
183};
184
185static bool parseFloat(yarp::os::Searchable& cfg, const std::string& key, float min_value, float max_value, float& value)
186{
187 if (!cfg.check(key))
188 {
189 yCInfo(KEYBOARDJOYPAD) << "The key" << key << "is not present in the configuration file."
190 << "Using the default value:" << value;
191 return true;
192 }
193
194 if (!cfg.find(key).isFloat64() && !cfg.find(key).isInt64() && !cfg.find(key).isInt32())
195 {
196 yCError(KEYBOARDJOYPAD) << "The value of " << key << " is not a float";
197 return false;
198 }
199 float input = static_cast<float>(cfg.find(key).asFloat64());
200 if (input < min_value || input > max_value)
201 {
202 yCError(KEYBOARDJOYPAD) << "The value of " << key << " is out of range. It should be between" << min_value << "and" << max_value;
203 return false;
204 }
205 value = input;
206 return true;
207}
208
209static bool parseInt(yarp::os::Searchable& cfg, const std::string& key, int min_value, int max_value, int& value)
210{
211 if (!cfg.check(key))
212 {
213 yCInfo(KEYBOARDJOYPAD) << "The key" << key << "is not present in the configuration file."
214 << "Using the default value:" << value;
215 return true;
216 }
217
218 if (!cfg.find(key).isInt64() && !cfg.find(key).isInt32())
219 {
220 yCError(KEYBOARDJOYPAD) << "The value of " << key << " is not an integer";
221 return false;
222 }
223 int input = static_cast<int>(cfg.find(key).asInt64());
224 if (input < min_value || input > max_value)
225 {
226 yCError(KEYBOARDJOYPAD) << "The value of " << key << " is out of range. It should be between" << min_value << "and" << max_value;
227 return false;
228 }
229 value = input;
230 return true;
231}
232
233struct Settings {
234 float button_size = 100;
235 float min_button_size = 50;
236 float max_button_size = 200;
237 float font_multiplier = 1.0;
240 float gui_period = 0.033f;
241 float deadzone = 0.1f;
242 float padding = 100;
243 int window_width = 1280;
244 int window_height = 720;
247 std::atomic<bool> single_threaded { false };
248 std::vector<int> joypad_indices;
249
251 {
252 if (!parseFloat(cfg, "button_size", 1.f, 1e5f, button_size))
253 {
254 return false;
255 }
256
257 if (!parseFloat(cfg, "min_button_size", 1.f, 1e5f, min_button_size))
258 {
259 return false;
260 }
261
262 if (!parseFloat(cfg, "max_button_size", 1.f, 1e5f, max_button_size))
263 {
264 return false;
265 }
266
267 if (!parseFloat(cfg, "font_multiplier", 0.01f, 1e5f, font_multiplier))
268 {
269 return false;
270 }
271
272 if (!parseFloat(cfg, "min_font_multiplier", 0.01f, 1e5f, min_font_multiplier))
273 {
274 return false;
275 }
276
277 if (!parseFloat(cfg, "max_font_multiplier", 0.01f, 1e5f, max_font_multiplier))
278 {
279 return false;
280 }
281
282 if (!parseFloat(cfg, "gui_period", 1e-3f, 1e5f, gui_period))
283 {
284 return false;
285 }
286
287 if (!parseFloat(cfg, "joypad_deadzone", 0.f, 1.f, deadzone))
288 {
289 return false;
290 }
291
292 if (!parseFloat(cfg, "padding", 0.f, 1e5f, padding))
293 {
294 return false;
295 }
296
297 if (!parseInt(cfg, "window_width", 1, static_cast<int>(1e4), window_width))
298 {
299 return false;
300 }
301
302 if (!parseInt(cfg, "window_height", 1, static_cast<int>(1e4), window_height))
303 {
304 return false;
305 }
306
307 if (!parseInt(cfg, "buttons_per_row", 1, 100, buttons_per_row))
308 {
309 return false;
310 }
311
312 if (cfg.check("allow_window_closing"))
313 {
314 allow_window_closing = cfg.find("allow_window_closing").isNull() || cfg.find("allow_window_closing").asBool();
315 }
316 else
317 {
318 yCInfo(KEYBOARDJOYPAD) << "The key \"allow_window_closing\" is not present in the configuration file."
319 << "Using the default value:" << allow_window_closing;
320 }
321
322 //If macOs, the GUI thread must be the main thread. Hence use no GUI thread
323#ifdef __APPLE__
324 single_threaded = true;
325 yCWarning(KEYBOARDJOYPAD) << "In macOS the GUI thread should be the main thread. Hence, we are using true as default for \"no_gui_thread\"";
326
327#endif //__APPLE__
328
329
330 if (cfg.check("no_gui_thread"))
331 {
332 single_threaded = cfg.find("no_gui_thread").isNull() || cfg.find("no_gui_thread").asBool();
333 }
334 else
335 {
336 yCInfo(KEYBOARDJOYPAD) << "The key \"no_gui_thread\" is not present in the configuration file."
337 << "Using the default value:" << static_cast<bool>(single_threaded);
338 }
339
341 {
342 yCError(KEYBOARDJOYPAD) << "The configuration file is invalid. The keys \"no_gui_thread\" and \"allow_window_closing\" cannot be both true.";
343 return false;
344 }
345
346 if (cfg.check("joypad_indices"))
347 {
348 yarp::os::Value joypadsValue = cfg.find("joypad_indices");
349 if (joypadsValue.isInt32() || joypadsValue.isInt64())
350 {
351 int joypad_index = static_cast<int>(joypadsValue.asInt64());
352 if (joypad_index > GLFW_JOYSTICK_LAST)
353 {
354 yCError(KEYBOARDJOYPAD) << "The value of \"joypad_indices\" is out of range."
355 << "It should be between" << GLFW_JOYSTICK_1 << "and" << GLFW_JOYSTICK_LAST;
356 return false;
357 }
358 if (joypad_index >= GLFW_JOYSTICK_1)
359 {
360 joypad_indices.push_back(joypad_index);
361 }
362 }
363 else if (!joypadsValue.isList())
364 {
365 yCError(KEYBOARDJOYPAD) << "\"joypad_indices\" is found but it is neither an int nor a list.";
366 return false;
367 }
368
369 yarp::os::Bottle* joypads_index_list = joypadsValue.asList();
370
371 for (size_t i = 0; i < joypads_index_list->size(); i++)
372 {
373 if (!joypads_index_list->get(i).isInt64() && !joypads_index_list->get(i).isInt32())
374 {
375 yCError(KEYBOARDJOYPAD) << "The value at index" << i << "of the \"joypad_indices\" list is not an integer.";
376 return false;
377 }
378
379 int joypad_index = static_cast<int>(joypads_index_list->get(i).asInt64());
380 if (joypad_index < GLFW_JOYSTICK_1 || joypad_index > GLFW_JOYSTICK_LAST)
381 {
382 yCError(KEYBOARDJOYPAD) << "The value at index" << i << "of the joypads_index list is out of range."
383 << "It should be between" << GLFW_JOYSTICK_1 << "and" << GLFW_JOYSTICK_LAST;
384 return false;
385 }
386
387 joypad_indices.push_back(joypad_index);
388 }
389 }
390 else
391 {
392 yCInfo(KEYBOARDJOYPAD) << "The key \"joypads_index\" is not present in the configuration file."
393 << "Using only the joypad with index 0 (if present).";
394 joypad_indices.push_back(GLFW_JOYSTICK_1);
395 }
396
397 return true;
398 }
399};
400
401enum class Axis
402{
403 WS = 0,
404 AD = 1,
405 UP_DOWN = 2,
406 LEFT_RIGHT = 3
407};
408
410{
411 int sign;
412 size_t index;
413};
414
416{
417 std::unordered_map<Axis, std::vector<AxisSettings>> axes;
418 size_t number_of_axes = 0;
419
420 std::string wasd_label = "WASD";
421 std::string arrows_label = "Arrows";
426
428 {
429 if (!cfg.check("axes"))
430 {
431 yCInfo(KEYBOARDJOYPAD) << "The key \"axes\" is not present in the configuration file. Enabling both wasd and the arrows.";
432 axes[Axis::AD].push_back({+1, 0});
433 axes[Axis::WS].push_back({+1, 1});
434 axes[Axis::LEFT_RIGHT].push_back({+1, 2});
435 axes[Axis::UP_DOWN].push_back({+1, 3});
436 number_of_axes = 4;
437 }
438 else
439 {
440 if (!cfg.find("axes").isList())
441 {
442 yCError(KEYBOARDJOYPAD) << "The value of \"axes\" is not a list";
443 return false;
444 }
445
446 yarp::os::Bottle* axes_list = cfg.find("axes").asList();
447
448 for (size_t i = 0; i < axes_list->size(); i++)
449 {
450 if (!axes_list->get(i).isString())
451 {
452 yCError(KEYBOARDJOYPAD) << "The value at index" << i << "of the axes list is not a string.";
453 return false;
454 }
455
456 std::string axis = axes_list->get(i).asString();
457
458 //Check if the first character is a - or a + and remove it
459 int sign = +1;
460 if (axis[0] == '-' || axis[0] == '+')
461 {
462 sign = axis[0] == '-' ? -1 : +1;
463 axis = axis.substr(1);
464 }
465
466 std::transform(axis.begin(), axis.end(), axis.begin(), ::tolower);
467
468 if (axis == "ws")
469 {
470 axes[Axis::WS].push_back({ sign, i });
471 }
472 else if (axis == "ad")
473 {
474 axes[Axis::AD].push_back({ sign, i });
475 }
476 else if (axis == "up_down")
477 {
478 axes[Axis::UP_DOWN].push_back({ sign, i });
479 }
480 else if (axis == "left_right")
481 {
482 axes[Axis::LEFT_RIGHT].push_back({ sign, i });
483 }
484 else if (axis != "" && axis != "none")
485 {
486 yCError(KEYBOARDJOYPAD) << "The value of the axes list (" << axis << ") is not a valid axis."
487 << "Allowed values(\"ws\", \"ad\", \"up_down\", \"left_right\","
488 << "eventually with a + or - as prefix, \"none\" and \"\")";
489 return false;
490 }
491 }
492 number_of_axes = axes_list->size();
493 }
494
495 if (cfg.check("wasd_label"))
496 {
497 wasd_label = cfg.find("wasd_label").asString();
498 }
499 else
500 {
501 yCInfo(KEYBOARDJOYPAD) << "The key \"wasd_label\" is not present in the configuration file."
502 << "Using the default value:" << wasd_label;
503 }
504
505 if (cfg.check("arrows_label"))
506 {
507 arrows_label = cfg.find("arrows_label").asString();
508 }
509 else
510 {
511 yCInfo(KEYBOARDJOYPAD) << "The key \"arrows_label\" is not present in the configuration file."
512 << "Using the default value:" << arrows_label;
513 }
514
515 std::vector<std::pair<std::string, int&>> joypad_axis_index = { {"ad_joypad_axis_index", ad_joypad_axis_index},
516 {"ws_joypad_axis_index", ws_joypad_axis_index},
517 {"left_right_joypad_axis_index", left_right_joypad_axis_index},
518 {"up_down_joypad_axis_index", up_down_joypad_axis_index} };
519
520 for (auto& [name, index] : joypad_axis_index)
521 {
522 if (!parseInt(cfg, name, -1, 100, index))
523 {
524 return false;
525 }
526 }
527
528 return true;
529 }
530};
531
533{
534 std::string name;
535 int index;
536 int axes;
540 bool active;
541};
542
544{
545public:
546 GLFWwindow* window = nullptr;
547
548 std::atomic_bool need_to_close{false}, closed{false}, initialized{false};
549
550 std::mutex mutex;
551
554
557
558 std::vector<ButtonsTable> sticks;
559 std::vector<std::vector<size_t>> sticks_to_axes;
562 std::vector<double> ctrl_value;
563 std::vector<double> axes_values;
564 std::vector<std::vector<double>> sticks_values;
565 std::vector<double> buttons_values;
566
567 std::vector<JoypadInfo> joypads;
568 std::vector<float> joypad_axis_values;
569 std::vector<bool> joypad_button_values;
570 bool using_joypad = false;
571
573 std::thread::id gui_thread_id;
574
575 ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
576
577
578 static void GLMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei, const GLchar* message, const void*) {
579 yCError(KEYBOARDJOYPAD, "GL CALLBACK: %s source = 0x%x, type = 0x%x, id = 0x%x, severity = 0x%x, message = %s",
580 (type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : ""),
581 source, type, id, severity, message);
582 }
583
584 static void glfwErrorCallback(int error, const char* description) {
585 yCError(KEYBOARDJOYPAD, "GLFW error %d: %s", error, description);
586 }
587
589 {
590 buttons.name = "Buttons";
591 if (!cfg.check("buttons"))
592 {
593 yCInfo(KEYBOARDJOYPAD) << "The key \"buttons\" is not present in the configuration file. No buttons will be created.";
594 return true;
595 }
596
597 if (!cfg.find("buttons").isList())
598 {
599 yCError(KEYBOARDJOYPAD) << "The value of \"buttons\" is not a list";
600 return false;
601 }
602
603 yarp::os::Bottle* buttons_list = cfg.find("buttons").asList();
604
605 std::unordered_map<std::string, std::pair<size_t, size_t>> buttons_map; //map existing buttons to their location
606
607 int col = 0;
608 for (size_t i = 0; i < buttons_list->size(); i++)
609 {
610 std::string buttons_with_alias;
611 if (!buttons_list->get(i).isString())
612 {
613 if (buttons_list->get(i).isInt64() || buttons_list->get(i).isInt32())
614 {
615 buttons_with_alias = std::to_string(buttons_list->get(i).asInt64());
616 }
617 else
618 {
619 yCError(KEYBOARDJOYPAD) << "The value at index" << i << "of the buttons list is not a string.";
620 return false;
621 }
622 }
623 else
624 {
625 buttons_with_alias = buttons_list->get(i).asString();
626 }
627
628 if (buttons_with_alias == "" || buttons_with_alias == "none")
629 {
630 continue;
631 }
632
633 std::string buttons_keys = buttons_with_alias;
634 std::string alias = "";
635
636 size_t pos = buttons_with_alias.find(':');
637 bool have_alias = false;
638 if (pos != std::string::npos)
639 {
640 buttons_keys = buttons_with_alias.substr(0, pos);
641 alias = buttons_with_alias.substr(pos + 1);
642 have_alias = true;
643 }
644 else
645 {
646 alias = buttons_keys;
647 }
648
649 std::transform(buttons_keys.begin(), buttons_keys.end(), buttons_keys.begin(), ::toupper);
650
651 std::vector<std::string> buttons_key_list;
652 std::string delimiter = "-";
653 pos = buttons_keys.find(delimiter);
654 while (pos != std::string::npos)
655 {
656 buttons_key_list.push_back(buttons_keys.substr(0, pos));
657 buttons_keys.erase(0, pos + delimiter.length());
658 pos = buttons_keys.find(delimiter);
659 }
660 buttons_key_list.push_back(buttons_keys);
661
662 ButtonState newButton;
663 newButton.values.push_back({ .sign = 1, .index = i });
664
665 std::unordered_map<std::string, ImGuiKey> supportedButtons = {
666 {"SPACE", ImGuiKey_Space},
667 {"ENTER", ImGuiKey_Enter},
668 {"ESCAPE", ImGuiKey_Escape},
669 {"BACKSPACE", ImGuiKey_Backspace},
670 {"DELETE", ImGuiKey_Delete},
671 {"LEFT", ImGuiKey_LeftArrow},
672 {"RIGHT", ImGuiKey_RightArrow},
673 {"UP", ImGuiKey_UpArrow},
674 {"DOWN", ImGuiKey_DownArrow},
675 {"TAB", ImGuiKey_Tab}
676 };
677
678 std::string parsedButtons;
679 for (auto& button : buttons_key_list)
680 {
681 bool parsed = true;
682 if (button.size() == 1 && button[0] >= 'A' && button[0] <= 'Z')
683 {
684 newButton.keys.push_back(static_cast<ImGuiKey>(ImGuiKey_A + button[0] - 'A'));
685 }
686 else if (button.size() && button[0] >= '0' && button[0] <= '9')
687 {
688 newButton.keys.push_back(static_cast<ImGuiKey>(ImGuiKey_0 + button[0] - '0'));
689 newButton.keys.push_back(static_cast<ImGuiKey>(ImGuiKey_Keypad0 + button[0] - '0'));
690 }
691 else if (button.size() > 1 && button[0] == 'J' && std::find_if(button.begin() + 1,
692 button.end(), [](unsigned char c) { return !std::isdigit(c); }) == button.end()) //J followed by a number
693 {
694 int joypad_button = std::stoi(button.substr(1));
695 newButton.joypadButtonIndices.push_back(joypad_button);
696 }
697 else if (supportedButtons.find(button) != supportedButtons.end())
698 {
699 newButton.keys.push_back(supportedButtons[button]);
700 }
701 else
702 {
703 parsed = false;
704 }
705
706 if (parsed)
707 {
708 if (!parsedButtons.empty())
709 {
710 parsedButtons += ", " + button;
711 }
712 else
713 {
714 parsedButtons = button;
715 }
716 }
717 }
718
719 if (!parsedButtons.empty() && have_alias)
720 {
721 alias += " (" + parsedButtons + ")";
722 }
723 else if (!parsedButtons.empty() && !have_alias)
724 {
725 alias = parsedButtons;
726 }
727
728 newButton.alias = alias;
729
730 if (buttons_map.find(newButton.alias) != buttons_map.end())
731 {
732 size_t button_row = buttons_map[newButton.alias].first;
733 size_t button_col = buttons_map[newButton.alias].second;
734 buttons.rows[button_row][button_col].values.push_back(newButton.values.front());
735 }
736 else
737 {
738 if (buttons.rows.empty() || buttons.rows.back().size() == settings.buttons_per_row)
739 {
740 buttons.rows.emplace_back();
741 col = 0;
742 }
743 newButton.col = col++;
744 buttons.rows.back().push_back(newButton);
745 buttons_map[newButton.alias] = std::make_pair(buttons.rows.size() - 1, buttons.rows.back().size() - 1);
746 }
747 }
748 buttons_values.resize(buttons_list->size(), 0.0);
749 if (!buttons.rows.empty())
750 {
751 ctrl_button = {.alias = "Hold (Ctrl)", .type = ButtonType::TOGGLE, .keys = {ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl}, .values = {{.sign = 1, .index = 0}} };
752 ctrl_value.resize(1, 0.0);
753 }
754
755 return true;
756 }
757
758 void prepareWindow(const ImVec2& position, const std::string& name)
759 {
760 ImGui::SetNextWindowPos(position, ImGuiCond_FirstUseEver);
761 ImGui::Begin(name.c_str(), 0, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings);
762 ImGui::SetWindowFontScale(settings.font_multiplier);
763 }
764
765 void renderButtonsTable(ButtonsTable& buttons_table, bool hold_active, double joypadDeadzone,
766 const std::vector<float>& joypadAxisValues, const std::vector<bool>& joypadButtonValues,
767 std::vector<double>& values) const
768 {
769 //Define the size of the buttons
770 ImVec2 buttonSize(settings.button_size, settings.button_size);
771 const int& n_cols = buttons_table.numberOfColumns;
772
773 ImGui::BeginTable(buttons_table.name.c_str(), n_cols, ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_SizingMask_);
774
775 for (auto& row : buttons_table.rows)
776 {
777 ImGui::TableNextRow();
778
779 for (auto& button : row)
780 {
781 ImGui::TableSetColumnIndex(button.col);
782
783 button.render(button_active_color, button_inactive_color, buttonSize, hold_active, joypadDeadzone, joypadAxisValues, joypadButtonValues, values);
784 }
785 if (row.empty())
786 {
787 ImGui::TableSetColumnIndex(0);
788 ImGui::Dummy(buttonSize);
789 }
790 }
791 ImGui::EndTable();
792 }
793
795 {
796 glfwSetErrorCallback(&KeyboardJoypad::Impl::glfwErrorCallback);
797 if (!glfwInit()) {
798 yCError(KEYBOARDJOYPAD, "Unable to initialize GLFW");
799 return false;
800 }
801
802 this->window = glfwCreateWindow(this->settings.window_width, this->settings.window_height,
803 "YARP Keyboard as Joypad Device Window", nullptr, nullptr);
804 if (!this->window) {
805 yCError(KEYBOARDJOYPAD, "Could not create window");
806 return false;
807 }
808
809 glfwMakeContextCurrent(this->window);
810 glfwSwapInterval(1);
811
812 // Initialize the GLEW OpenGL 3.x bindings
813 // GLEW must be initialized after creating the window
814 glewExperimental = GL_TRUE;
815 GLenum err = glewInit();
816 if (err != GLEW_OK) {
817 yCError(KEYBOARDJOYPAD) << "glewInit failed, aborting.";
818 return false;
819 }
820 yCInfo(KEYBOARDJOYPAD) << "Using GLEW" << (const char*)glewGetString(GLEW_VERSION);
821
822 glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE); //This is to ignore message 0x20071 about the use of the VIDEO memory
823
824 glDebugMessageCallback(&KeyboardJoypad::Impl::GLMessageCallback, NULL);
825 glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
826 glEnable(GL_DEBUG_OUTPUT);
827
828
829 // Setup Dear ImGui context
830 IMGUI_CHECKVERSION();
831 ImGui::CreateContext();
832 ImGuiIO& io = ImGui::GetIO();
833 io.ConfigFlags |= ImGuiConfigFlags_NavNoCaptureKeyboard;
834
835 // Setup Dear ImGui style
836 ImGui::StyleColorsDark();
837
838 // Setup Platform/Renderer backends
839 ImGui_ImplGlfw_InitForOpenGL(this->window, true);
840 ImGui_ImplOpenGL3_Init();
841
842 for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i) {
843 if (glfwJoystickPresent(i)) {
844 int axes_count, button_count;
845 glfwGetJoystickAxes(i, &axes_count);
846 glfwGetJoystickButtons(i, &button_count);
847 std::string name {glfwGetJoystickName(i)};
848 this->joypads.push_back({ .name = name, .index = i, .axes = axes_count, .buttons = button_count });
849 yCInfo(KEYBOARDJOYPAD) << "Joypad" << name << "is available (index" << i
850 << "axes =" << axes_count << "buttons = " << button_count << ").";
851 }
852 }
853
854 if (!this->joypads.size()) {
855 yCInfo(KEYBOARDJOYPAD) << "No joypad found.";
856 }
857
858 size_t axes_offset = 0;
859 size_t buttons_offset = 0;
860
861 for (int& joypad_index : this->settings.joypad_indices)
862 {
863 if (joypad_index >= this->joypads.size())
864 {
865 yCWarning(KEYBOARDJOYPAD) << "The joypad with index" << joypad_index << "is not available. It will be skipped";
866 continue;
867 }
868 this->joypads[static_cast<size_t>(joypad_index)].axes_offset = axes_offset;
869 this->joypads[static_cast<size_t>(joypad_index)].buttons_offset = buttons_offset;
870 this->joypads[static_cast<size_t>(joypad_index)].active = true;
871 axes_offset += this->joypads[static_cast<size_t>(joypad_index)].axes;
872 buttons_offset += this->joypads[static_cast<size_t>(joypad_index)].buttons;
873 this->using_joypad = true;
874 }
875 this->joypad_axis_values.resize(axes_offset, 0.0);
876 this->joypad_button_values.resize(buttons_offset, false);
877
878 this->button_inactive_color = ImGui::GetStyle().Colors[ImGuiCol_Button];
879 this->button_active_color = ImVec4(0.7f, 0.5f, 0.3f, 1.0f);
880
881 this->gui_thread_id = std::this_thread::get_id();
882 this->initialized = true;
883
884 return true;
885 }
886
888 {
889 glfwPollEvents();
890
891 // Start the Dear ImGui frame
892 ImGui_ImplOpenGL3_NewFrame();
893 ImGui_ImplGlfw_NewFrame();
894 ImGui::NewFrame();
895
896 for (double& value : this->axes_values)
897 {
898 value = 0;
899 }
900
901 for (double& value : this->buttons_values)
902 {
903 value = 0;
904 }
905
906 for (auto& value : this->ctrl_value)
907 {
908 value = 0;
909 }
910
911 for (auto& value : this->joypad_axis_values)
912 {
913 value = 0;
914 }
915
916 for (size_t i = 0; i < this->joypad_button_values.size(); ++i) //The for(auto& v : ..) does not work with bool arrays
917 {
918 this->joypad_button_values[i] = false;
919 }
920 }
921
922 void update()
923 {
924
925 if (!this->initialized || this->gui_thread_id != std::this_thread::get_id())
926 {
927 return;
928 }
929
930 this->prepareFrame();
931
932 if (this->using_joypad)
933 {
934 for (auto& joypad : this->joypads)
935 {
936 if (!glfwJoystickPresent(joypad.index) || !joypad.active)
937 {
938 continue;
939 }
940
941 int new_axes, new_buttons;
942 const float* axes = glfwGetJoystickAxes(joypad.index, &new_axes);
943 const unsigned char* buttons = glfwGetJoystickButtons(joypad.index, &new_buttons);
944
945 for (size_t i = 0; i < std::min(joypad.axes, new_axes); ++i)
946 {
947 this->joypad_axis_values[joypad.axes_offset + i] = axes[i];
948 }
949
950 for (size_t i = 0; i < std::min(joypad.buttons, new_buttons); ++i)
951 {
952 this->joypad_button_values[joypad.buttons_offset + i] = buttons[i] == GLFW_PRESS;
953 }
954 }
955 }
956
957 ImVec2 position(this->settings.padding, this->settings.padding);
958 float button_table_height = position.y;
959 for (auto& stick : this->sticks)
960 {
961 position.y = this->settings.padding; //Keep the sticks on the save level
962 this->prepareWindow(position, stick.name);
963 this->renderButtonsTable(stick, false, this->settings.deadzone,
964 this->joypad_axis_values, this->joypad_button_values,this->axes_values);
965 ImGui::End();
966 position.x += stick.numberOfColumns * this->settings.button_size + this->settings.padding; // Move the next table to the right (n columns + 1 space)
967 position.y += stick.rows.size() * this->settings.button_size + this->settings.padding; // Move the next table down (n rows + 1 space)
968 button_table_height = std::max(button_table_height, position.y);
969 }
970
971 //Clamp axes values to the range -1, 1
972 for (auto& axis_value : this->axes_values)
973 {
974 if (axis_value > 1)
975 {
976 axis_value = 1;
977 }
978 else if (axis_value < -1)
979 {
980 axis_value = -1;
981 }
982 }
983
984 //Update sticks values from axes values
985 for (size_t i = 0; i < this->sticks_to_axes.size(); ++i)
986 {
987 for (size_t j = 0; j < this->sticks_to_axes[i].size(); j++)
988 {
989 this->sticks_values[i][j] = this->axes_values[this->sticks_to_axes[i][j]];
990 }
991 }
992
993 if (!this->buttons.rows.empty())
994 {
995 position.y = this->settings.padding; //Keep the buttons on the save level of the sticks
996 this->prepareWindow(position, this->buttons.name);
997 ImGui::BeginTable("Buttons_layout", 1, ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_SizingMask_ | ImGuiTableFlags_BordersInner);
998 ImGui::TableNextRow();
999 ImGui::TableSetColumnIndex(0);
1000 this->ctrl_button.render(this->button_active_color, this->button_inactive_color, ImVec2(this->settings.button_size, this->settings.button_size), false, this->settings.deadzone,
1001 this->joypad_axis_values, this->joypad_button_values, this->ctrl_value);
1002 ImGui::TableNextRow();
1003 ImGui::TableSetColumnIndex(0);
1004 bool hold_active = this->ctrl_value.front() > 0;
1005 this->renderButtonsTable(this->buttons, hold_active, this->settings.deadzone,
1006 this->joypad_axis_values, this->joypad_button_values, this->buttons_values);
1007 ImGui::EndTable();
1008 ImGui::End();
1009 }
1010
1011 //Apply clamping to buttons values in the range 0, 1 and round them to 0 or 1
1012 for (auto& button_value : this->buttons_values)
1013 {
1014 if (button_value > 0)
1015 {
1016 button_value = 1;
1017 }
1018 else
1019 {
1020 button_value = 0;
1021 }
1022 }
1023
1024 position.x = this->settings.padding; //Reset the x position
1025 position.y = button_table_height; //Move the next table down
1026
1027 this->prepareWindow(position, "Settings");
1028 ImGuiIO& io = ImGui::GetIO();
1029 ImGui::Text("Application average %.1f ms/frame (%.1f FPS)", io.DeltaTime * 1000.0f, io.Framerate);
1030
1031 int width, height;
1032 glfwGetWindowSize(this->window, &width, &height);
1033
1034 ImGui::Text("Window size: %d x %d", width, height);
1035 ImGui::SliderFloat("Button size", &this->settings.button_size, this->settings.min_button_size, this->settings.max_button_size);
1036 ImGui::SliderFloat("Font multiplier", &this->settings.font_multiplier, this->settings.min_font_multiplier, this->settings.max_font_multiplier);
1037 if (this->using_joypad)
1038 {
1039 ImGui::SliderFloat("Joypad deadzone", &this->settings.deadzone, 0.0, 1.0);
1040 // Display the joypad values
1041 std::string connectedJoypads = "Connected joypads: ";
1042 for (size_t i = 0; i < this->joypads.size(); ++i)
1043 {
1044 connectedJoypads += this->joypads[i].name;
1045 if (i != this->joypads.size() - 1)
1046 {
1047 connectedJoypads += ", ";
1048 }
1049 }
1050 ImGui::Separator();
1051 ImGui::TextUnformatted(connectedJoypads.c_str());
1052 std::string axes_values = "Joypad axes values: ";
1053 for (size_t i = 0; i < this->joypad_axis_values.size(); ++i)
1054 {
1055 // Print the values of the axes in the format "axis_index: value" with a 1 decimal precision
1056 std::stringstream stream;
1057 stream << std::fixed << std::setprecision(2) << this->joypad_axis_values[i];
1058 std::string sign = this->joypad_axis_values[i] >= 0 ? "+" : "";
1059 axes_values += "<" + std::to_string(i) + "> " + sign + stream.str();
1060 if (i != this->joypad_axis_values.size() - 1)
1061 {
1062 axes_values += ", ";
1063 }
1064 }
1065 ImGui::TextUnformatted(axes_values.c_str());
1066 std::string buttons_values = "Joypad buttons values: ";
1067 for (size_t i = 0; i < this->joypad_button_values.size(); ++i)
1068 {
1069 buttons_values += "<" + std::to_string(i) + "> " + (this->joypad_button_values[i] ? "1" : "0");
1070 if (i != this->joypad_button_values.size() - 1)
1071 {
1072 buttons_values += ", ";
1073 }
1074 }
1075 ImGui::TextUnformatted(buttons_values.c_str());
1076 }
1077 ImGui::Separator();
1078 std::string output_axes_values = "Output axes values: ";
1079 for (size_t i = 0; i < this->axes_values.size(); ++i)
1080 {
1081 // Print the values of the axes in the format "axis_index: value" with a 1 decimal precision
1082 std::stringstream stream;
1083 stream << std::fixed << std::setprecision(2) << this->axes_values[i];
1084 std::string sign = this->axes_values[i] >= 0 ? "+" : "";
1085 output_axes_values += "<" + std::to_string(i) + "> " + sign + stream.str();
1086 if (i != this->axes_values.size() - 1)
1087 {
1088 output_axes_values += ", ";
1089 }
1090 }
1091 ImGui::TextUnformatted(output_axes_values.c_str());
1092 std::string output_buttons_values = "Output buttons values: ";
1093 if (this->buttons_values.empty())
1094 {
1095 output_buttons_values += "None";
1096 }
1097 for (size_t i = 0; i < this->buttons_values.size(); ++i)
1098 {
1099 std::stringstream stream;
1100 stream << std::fixed << std::setprecision(1) << this->buttons_values[i];
1101 output_buttons_values += "<" + std::to_string(i) + "> " + stream.str();
1102 if (i != this->buttons_values.size() - 1)
1103 {
1104 output_buttons_values += ", ";
1105 }
1106 }
1107 ImGui::TextUnformatted(output_buttons_values.c_str());
1108 ImGui::End();
1109
1110 // Rendering
1111 ImGui::Render();
1112 int display_w, display_h;
1113 glfwGetFramebufferSize(this->window, &display_w, &display_h);
1114 glViewport(0, 0, display_w, display_h);
1115 glClearColor(this->clear_color.x * this->clear_color.w, this->clear_color.y * this->clear_color.w, this->clear_color.z * this->clear_color.w, this->clear_color.w);
1116 glClear(GL_COLOR_BUFFER_BIT);
1117 ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
1118
1119 glfwSwapBuffers(this->window);
1120
1121 this->last_gui_update_time = yarp::os::Time::now();
1122 }
1123
1124 bool needUpdate() const
1125 {
1126 if (this->closed)
1127 {
1128 return false;
1129 }
1130 return yarp::os::Time::now() - this->last_gui_update_time > this->settings.gui_period;
1131 }
1132
1133 void close()
1134 {
1135 if (this->closed || !this->initialized)
1136 return;
1137
1138 ImGui_ImplOpenGL3_Shutdown();
1139 ImGui_ImplGlfw_Shutdown();
1140 ImGui::DestroyContext();
1141
1142 if (this->window)
1143 {
1144 glfwDestroyWindow(this->window);
1145 glfwTerminate();
1146 this->window = nullptr;
1147 }
1148
1149 this->closed = true;
1150 }
1151
1152};
1153
1154
1155
1157 : yarp::dev::DeviceDriver(),
1158 yarp::os::PeriodicThread(0.033, yarp::os::ShouldUseSystemClock::Yes)
1159{
1160 m_pimpl = std::make_unique<Impl>();
1161}
1162
1164{
1165 this->stop();
1166 m_pimpl->close();
1167}
1168
1170{
1171 if (!m_pimpl->settings.parseFromConfigFile(cfg))
1172 {
1173 return false;
1174 }
1175
1176 if (!m_pimpl->axes_settings.parseFromConfigFile(cfg))
1177 {
1178 return false;
1179 }
1180
1181 m_pimpl->buttons.numberOfColumns = m_pimpl->settings.buttons_per_row;
1182
1183 if (!m_pimpl->parseButtonsSettings(cfg))
1184 {
1185 return false;
1186 }
1187
1188 int ws = m_pimpl->axes_settings.axes.find(Axis::WS) != m_pimpl->axes_settings.axes.end();
1189 int ad = m_pimpl->axes_settings.axes.find(Axis::AD) != m_pimpl->axes_settings.axes.end();
1190 int up_down = m_pimpl->axes_settings.axes.find(Axis::UP_DOWN) != m_pimpl->axes_settings.axes.end();
1191 int left_right = m_pimpl->axes_settings.axes.find(Axis::LEFT_RIGHT) != m_pimpl->axes_settings.axes.end();
1192
1193 m_pimpl->axes_values.resize(static_cast<size_t>(m_pimpl->axes_settings.number_of_axes), 0.0);
1194 m_pimpl->sticks_to_axes.clear();
1195
1196 if (ws || ad)
1197 {
1198 m_pimpl->sticks_to_axes.emplace_back();
1199 m_pimpl->sticks_values.emplace_back();
1200 ButtonsTable& wasd = m_pimpl->sticks.emplace_back();
1201 wasd.name = m_pimpl->axes_settings.wasd_label;
1202 wasd.numberOfColumns = ad ? 3 : 1; //Number of columns
1203 if (ws)
1204 {
1205 std::vector<ButtonValue> values;
1206 for (AxisSettings& ws_settings : m_pimpl->axes_settings.axes[Axis::WS])
1207 {
1208 values.push_back({ .sign = -ws_settings.sign, .index = ws_settings.index });
1209 }
1210 wasd.rows.push_back({ {.alias = "W", .type = ButtonType::TOGGLE, .keys = {ImGuiKey_W}, .values = values,
1211 .joypadAxisInputs = {{.sign = -1, .index = static_cast<size_t>(m_pimpl->axes_settings.ws_joypad_axis_index)}},
1212 .col = ad} });
1213 }
1214 if (ad)
1215 {
1216 std::vector<ButtonValue> a_values;
1217 std::vector<ButtonValue> d_values;
1218 for (AxisSettings& ws_settings : m_pimpl->axes_settings.axes[Axis::AD])
1219 {
1220 a_values.push_back({ .sign = -ws_settings.sign, .index = ws_settings.index });
1221 d_values.push_back({ .sign = ws_settings.sign, .index = ws_settings.index });
1222 }
1223 if (a_values.size() > 0)
1224 {
1225 m_pimpl->sticks_to_axes.back().push_back(a_values.front().index);
1226 m_pimpl->sticks_values.back().push_back(0);
1227 }
1228
1229 wasd.rows.push_back({ {.alias = "A", .type = ButtonType::TOGGLE, .keys = {ImGuiKey_A}, .values = a_values,
1230 .joypadAxisInputs = {{.sign = -1, .index = static_cast<size_t>(m_pimpl->axes_settings.ad_joypad_axis_index)}},
1231 .col = 0},
1232 {.alias = "D", .type = ButtonType::TOGGLE, .keys = {ImGuiKey_D}, .values = d_values,
1233 .joypadAxisInputs = {{.sign = +1, .index = static_cast<size_t>(m_pimpl->axes_settings.ad_joypad_axis_index)}},
1234 .col = 2} });
1235 }
1236 else
1237 {
1238 wasd.rows.emplace_back(); //empty row
1239 }
1240 if (ws)
1241 {
1242 std::vector<ButtonValue> values;
1243 for (AxisSettings& ws_settings : m_pimpl->axes_settings.axes[Axis::WS])
1244 {
1245 values.push_back({ .sign = ws_settings.sign, .index = ws_settings.index });
1246 }
1247 if (values.size() > 0)
1248 {
1249 m_pimpl->sticks_to_axes.back().push_back(values.front().index);
1250 m_pimpl->sticks_values.back().push_back(0);
1251 }
1252
1253 wasd.rows.push_back({ {.alias = "S", .type = ButtonType::TOGGLE, .keys = {ImGuiKey_S}, .values = values,
1254 .joypadAxisInputs = {{.sign = +1, .index = static_cast<size_t>(m_pimpl->axes_settings.ws_joypad_axis_index)}},
1255 .col = ad}});
1256 }
1257 }
1258
1259 if (up_down || left_right)
1260 {
1261 m_pimpl->sticks_to_axes.emplace_back();
1262 m_pimpl->sticks_values.emplace_back();
1263 ButtonsTable& arrows = m_pimpl->sticks.emplace_back();
1264 arrows.name = m_pimpl->axes_settings.arrows_label;
1265 arrows.numberOfColumns = left_right ? 3 : 1; //Number of columns
1266 if (up_down)
1267 {
1268 std::vector<ButtonValue> values;
1269 for (AxisSettings& ws_settings : m_pimpl->axes_settings.axes[Axis::UP_DOWN])
1270 {
1271 values.push_back({ .sign = -ws_settings.sign, .index = ws_settings.index });
1272 }
1273 arrows.rows.push_back({ {.alias = "top", .type = ButtonType::TOGGLE, .keys = {ImGuiKey_UpArrow}, .values = values,
1274 .joypadAxisInputs = {{.sign = -1, .index = static_cast<size_t>(m_pimpl->axes_settings.up_down_joypad_axis_index)}},
1275 .col = left_right} });
1276 }
1277 if (left_right)
1278 {
1279 std::vector<ButtonValue> l_values;
1280 std::vector<ButtonValue> r_values;
1281 for (AxisSettings& ws_settings : m_pimpl->axes_settings.axes[Axis::LEFT_RIGHT])
1282 {
1283 l_values.push_back({ .sign = -ws_settings.sign, .index = ws_settings.index });
1284 r_values.push_back({ .sign = ws_settings.sign, .index = ws_settings.index });
1285 }
1286 if (l_values.size() > 0)
1287 {
1288 m_pimpl->sticks_to_axes.back().push_back(l_values.front().index);
1289 m_pimpl->sticks_values.back().push_back(0);
1290 }
1291 arrows.rows.push_back({ {.alias = "left", .type = ButtonType::TOGGLE, .keys = {ImGuiKey_LeftArrow}, .values = l_values,
1292 .joypadAxisInputs = {{.sign = -1, .index = static_cast<size_t>(m_pimpl->axes_settings.left_right_joypad_axis_index)}},
1293 .col = 0},
1294 {.alias = "right", .type = ButtonType::TOGGLE, .keys = {ImGuiKey_RightArrow}, .values = r_values,
1295 .joypadAxisInputs = {{.sign = +1, .index = static_cast<size_t>(m_pimpl->axes_settings.left_right_joypad_axis_index)}},
1296 .col = 2} });
1297 }
1298 else
1299 {
1300 arrows.rows.emplace_back(); //empty row
1301 }
1302 if (up_down)
1303 {
1304 std::vector<ButtonValue> values;
1305 for (AxisSettings& ws_settings : m_pimpl->axes_settings.axes[Axis::UP_DOWN])
1306 {
1307 values.push_back({ .sign = ws_settings.sign, .index = ws_settings.index });
1308 }
1309 if (values.size() > 0)
1310 {
1311 m_pimpl->sticks_to_axes.back().push_back(values.front().index);
1312 m_pimpl->sticks_values.back().push_back(0);
1313 }
1314 arrows.rows.push_back({ {.alias = "bottom", .type = ButtonType::TOGGLE, .keys = {ImGuiKey_DownArrow}, .values = values,
1315 .joypadAxisInputs = {{.sign = +1, .index = static_cast<size_t>(m_pimpl->axes_settings.up_down_joypad_axis_index)}},
1316 .col = left_right} });
1317 }
1318 }
1319
1320 if (m_pimpl->settings.single_threaded)
1321 {
1322 yCInfo(KEYBOARDJOYPAD) << "The device is running in single threaded mode.";
1323 }
1324 else
1325 {
1326 yCInfo(KEYBOARDJOYPAD) << "The device is running in multi threaded mode.";
1327 this->setPeriod(m_pimpl->settings.gui_period);
1328
1329 // Start the thread
1330 if (!this->start()) {
1331 yCError(KEYBOARDJOYPAD) << "Thread start failed, aborting.";
1332 this->close();
1333 return false;
1334 }
1335 }
1336
1337 return true;
1338}
1339
1341{
1342 yCInfo(KEYBOARDJOYPAD) << "Closing the device";
1343 this->askToStop();
1344 if (m_pimpl->settings.single_threaded)
1345 {
1346 m_pimpl->close();
1347 }
1348 return true;
1349}
1350
1352{
1353 if (m_pimpl->closed || m_pimpl->settings.single_threaded)
1354 {
1355 return false;
1356 }
1357
1358 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1359
1360 return m_pimpl->initialize();
1361}
1362
1364{
1365 if (m_pimpl->closed || m_pimpl->settings.single_threaded)
1366 {
1367 return;
1368 }
1369
1370 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1371
1372 m_pimpl->close();
1373}
1374
1376{
1377 if (m_pimpl->closed || m_pimpl->settings.single_threaded)
1378 {
1379 return;
1380 }
1381 {
1382 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1383 if (m_pimpl->settings.allow_window_closing)
1384 {
1385 m_pimpl->need_to_close = glfwWindowShouldClose(m_pimpl->window);
1386 }
1387 }
1388 double period = 0;
1389 double desired_period = 0;
1390
1391 if (!m_pimpl->need_to_close)
1392 {
1393 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1394
1395 m_pimpl->update();
1396
1397 desired_period = getPeriod();
1398 period = getEstimatedUsed();
1399
1400 }
1401 else
1402 {
1403 this->close();
1404 }
1405
1406 if (period > desired_period)
1407 {
1408 yCWarningThrottle(KEYBOARDJOYPAD, 5.0, "The period of the GUI is higher than the period of the thread. The GUI will be updated at a lower rate.");
1409 yarp::os::Time::delay(1e-3); //Sleep for 1 ms to avoid the other threads to go to starvation
1410 }
1411
1412
1413}
1414
1416{
1417 //To let the device driver knowing that it need to poll updateService continuosly
1418 return false;
1419}
1420
1422{
1423 //To let the device driver that we are still alive
1424 if (m_pimpl->settings.single_threaded && !m_pimpl->closed)
1425 {
1426 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1427 if (!m_pimpl->initialized)
1428 {
1429 if (!m_pimpl->initialize())
1430 {
1431 return false;
1432 }
1433 }
1434 m_pimpl->update();
1435 }
1436 return !m_pimpl->closed;
1437}
1438
1440{
1441 yCInfo(KEYBOARDJOYPAD) << "Stopping the service";
1442 return this->close();
1443}
1444
1446{
1447 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1448 axis_count = m_pimpl->axes_values.size();
1449 return ReturnValue_ok;
1450}
1451
1453{
1454 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1455 button_count = m_pimpl->buttons_values.size();
1456 return ReturnValue_ok;
1457}
1458
1460{
1461 trackball_count = 0;
1462 return ReturnValue_ok;
1463}
1464
1466{
1467 hat_count = 0;
1468 return ReturnValue_ok;
1469}
1470
1472{
1473 touch_count = 0;
1474 return ReturnValue_ok;
1475}
1476
1478{
1479 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1480 stick_count = m_pimpl->sticks_to_axes.size();
1481 return ReturnValue_ok;
1482}
1483
1485{
1486 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1487 if (!m_pimpl->initialized)
1488 {
1489 if (!m_pimpl->initialize())
1490 {
1492 }
1493 }
1494 if (m_pimpl->settings.single_threaded && m_pimpl->needUpdate())
1495 {
1496 m_pimpl->update();
1497 }
1498 if (button_id >= m_pimpl->buttons_values.size())
1499 {
1500 yCError(KEYBOARDJOYPAD) << "The button with id" << button_id << "does not exist.";
1502 }
1503 value = m_pimpl->buttons_values[button_id];
1504 return ReturnValue_ok;
1505}
1506
1508{
1509 yCError(KEYBOARDJOYPAD) << "This device does not consider trackballs.";
1511}
1512
1513yarp::dev::ReturnValue yarp::dev::KeyboardJoypad::getHat(size_t /*hat_id*/, unsigned char& /*value*/)
1514{
1515 yCError(KEYBOARDJOYPAD) << "This device does not consider hats.";
1517}
1518
1520{
1521 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1522 if (!m_pimpl->initialized)
1523 {
1524 if (!m_pimpl->initialize())
1525 {
1527 }
1528 }
1529 if (m_pimpl->settings.single_threaded && m_pimpl->needUpdate())
1530 {
1531 m_pimpl->update();
1532 }
1533 if (axis_id >= m_pimpl->axes_values.size())
1534 {
1535 yCError(KEYBOARDJOYPAD) << "The axis with id" << axis_id << "does not exist.";
1537 }
1538 value = m_pimpl->axes_values[axis_id];
1539 return ReturnValue_ok;
1540}
1541
1543{
1544 std::lock_guard<std::mutex> lock(m_pimpl->mutex);
1545 if (!m_pimpl->initialized)
1546 {
1547 if (!m_pimpl->initialize())
1548 {
1550 }
1551 }
1552 if (m_pimpl->settings.single_threaded && m_pimpl->needUpdate())
1553 {
1554 m_pimpl->update();
1555 }
1556 if (stick_id >= m_pimpl->sticks_values.size())
1557 {
1558 yCError(KEYBOARDJOYPAD) << "The stick with id" << stick_id << "does not exist.";
1560 }
1561
1562 auto& stick_vals = m_pimpl->sticks_values[stick_id];
1563 value.s1 = stick_vals.size() > 0 ? stick_vals[0] : 0.0;
1564 value.s2 = stick_vals.size() > 1 ? stick_vals[1] : 0.0;
1565
1566 if (coordinate_mode == JoypadCtrl_coordinateMode::JypCtrlcoord_POLAR)
1567 {
1568 double norm = sqrt(value.s1 * value.s1 + value.s2 * value.s2);
1569 double angle = atan2(value.s2, value.s1);
1570 value.s1 = norm;
1571 value.s2 = angle;
1572 }
1573
1574 return ReturnValue_ok;
1575}
1576
1577yarp::dev::ReturnValue yarp::dev::KeyboardJoypad::getTouch(size_t /*touch_id*/, std::vector<yarp::dev::TouchData>& /*value*/)
1578{
1579 yCError(KEYBOARDJOYPAD) << "This device does not consider touch surfaces.";
1581}
const yarp::os::LogComponent & KEYBOARDJOYPAD()
static bool parseFloat(yarp::os::Searchable &cfg, const std::string &key, float min_value, float max_value, float &value)
static bool parseInt(yarp::os::Searchable &cfg, const std::string &key, int min_value, int max_value, int &value)
ButtonType
@ UP_DOWN
@ LEFT_RIGHT
#define ReturnValue_ok
Definition ReturnValue.h:82
#define ReturnValue_error_not_ready
Definition ReturnValue.h:88
#define ReturnValue_error_not_implemented_by_device
Definition ReturnValue.h:84
#define ReturnValue_error_input_out_of_bounds
Definition ReturnValue.h:89
Interface implemented by all device drivers.
void prepareWindow(const ImVec2 &position, const std::string &name)
std::vector< double > axes_values
static void glfwErrorCallback(int error, const char *description)
std::vector< bool > joypad_button_values
bool parseButtonsSettings(yarp::os::Searchable &cfg)
void renderButtonsTable(ButtonsTable &buttons_table, bool hold_active, double joypadDeadzone, const std::vector< float > &joypadAxisValues, const std::vector< bool > &joypadButtonValues, std::vector< double > &values) const
std::vector< float > joypad_axis_values
std::vector< ButtonsTable > sticks
std::vector< double > buttons_values
std::vector< JoypadInfo > joypads
std::vector< std::vector< double > > sticks_values
std::vector< std::vector< size_t > > sticks_to_axes
static void GLMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei, const GLchar *message, const void *)
virtual bool close() override
Close the DeviceDriver.
virtual yarp::dev::ReturnValue getStick(size_t stick_id, yarp::dev::StickData &value, JoypadCtrl_coordinateMode coordinate_mode) override
Get the value of a stick if present, return false otherwise.
virtual yarp::dev::ReturnValue getHat(size_t hat_id, unsigned char &value) override
Get the value of an Hat.
virtual bool startService() override
Initiate the service, whatever it is.
virtual yarp::dev::ReturnValue getTrackball(size_t trackball_id, yarp::dev::TrackballData &value) override
Get the axes change of a Trackball.
virtual yarp::dev::ReturnValue getButton(size_t button_id, double &value) override
Get the value of a button.
virtual bool open(yarp::os::Searchable &cfg) override
Open the DeviceDriver.
virtual void run() override
Loop function.
virtual yarp::dev::ReturnValue getButtonCount(size_t &button_count) override
Get number of buttons.
virtual yarp::dev::ReturnValue getAxis(size_t axis_id, double &value) override
Get the value of an axis if present, return false otherwise.
virtual yarp::dev::ReturnValue getTouch(size_t touch_id, std::vector< yarp::dev::TouchData > &value) override
Get the value of a touch if present, return false otherwise.
virtual yarp::dev::ReturnValue getAxisCount(size_t &axis_count) override
Get number of axes.
virtual yarp::dev::ReturnValue getHatCount(size_t &hat_count) override
Get number of hats.
virtual void threadRelease() override
Release method.
virtual yarp::dev::ReturnValue getStickCount(size_t &stick_count) override
Get the number of the sticks.
virtual yarp::dev::ReturnValue getTouchSurfaceCount(size_t &touch_count) override
Get the number of touch surface.
virtual bool stopService() override
Shut down the service, whatever it is.
virtual bool threadInit() override
Initialization method.
virtual bool updateService() override
Give the service the chance to run for a while.
virtual yarp::dev::ReturnValue getTrackballCount(size_t &trackball_count) override
Get number of trackballs.
A simple collection of objects that can be described and transmitted in a portable way.
Definition Bottle.h:64
size_type size() const
Gets the number of elements in the bottle.
Definition Bottle.cpp:252
Value & get(size_type index) const
Reads a Value v from a certain part of the list.
Definition Bottle.cpp:247
A base class for nested structures that can be searched.
Definition Searchable.h:31
virtual bool check(const std::string &key) const =0
Check if there exists a property of the given name.
virtual Value & find(const std::string &key) const =0
Gets a value corresponding to a given keyword.
A single value (typically within a Bottle).
Definition Value.h:44
virtual bool isString() const
Checks if value is a string.
Definition Value.cpp:156
virtual std::int64_t asInt64() const
Get 64-bit integer value.
Definition Value.cpp:210
virtual bool isList() const
Checks if value is a list.
Definition Value.cpp:162
virtual Bottle * asList() const
Get list value.
Definition Value.cpp:246
virtual bool isInt32() const
Checks if value is a 32-bit integer.
Definition Value.cpp:132
virtual bool isInt64() const
Checks if value is a 64-bit integer.
Definition Value.cpp:138
virtual std::string asString() const
Get string value.
Definition Value.cpp:240
#define yCInfo(component,...)
#define yCError(component,...)
#define yCWarning(component,...)
#define yCErrorOnce(component,...)
#define yCWarningThrottle(component, period,...)
double now()
Return the current time in seconds, relative to an arbitrary starting point.
Definition Time.cpp:121
void delay(double seconds)
Wait for a certain number of seconds.
Definition Time.cpp:111
The main, catch-all namespace for YARP.
Definition dirs.h:16
bool parseFromConfigFile(yarp::os::Searchable &cfg)
std::unordered_map< Axis, std::vector< AxisSettings > > axes
std::string wasd_label
std::string arrows_label
int left_right_joypad_axis_index
std::vector< int > joypadButtonIndices
void render(const ImVec4 &button_active_color, const ImVec4 &button_inactive_color, const ImVec2 &buttonSize, bool hold_active, double joypadDeadzone, const std::vector< float > &joypadAxisValues, const std::vector< bool > &joypadButtonValues, std::vector< double > &outputValues)
std::vector< ButtonValue > joypadAxisInputs
std::vector< ImGuiKey > keys
float deadzone(float input, float deadzone) const
ButtonType type
std::string alias
std::vector< ButtonValue > values
std::vector< std::vector< ButtonState > > rows
std::string name
size_t buttons_offset
std::string name
float min_button_size
float min_font_multiplier
float max_button_size
float font_multiplier
std::atomic< bool > single_threaded
std::vector< int > joypad_indices
bool parseFromConfigFile(yarp::os::Searchable &cfg)
bool allow_window_closing
float max_font_multiplier