Debian Codegraph @

Source/Core/InputCommon/ControllerInterface/CoreDevice.cpp

raw symbols SCIP
1 // Copyright 2013 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "InputCommon/ControllerInterface/CoreDevice.h"
5
6 #include <algorithm>
7 #include <cmath>
8 #include <memory>
9 #include <sstream>
10 #include <string>
11 #include <tuple>
12 #include <utility>
13
14 #include <fmt/format.h>
15
16 #include "Common/MathUtil.h"
17
18 namespace ciface::Core
19 {
20 // Compared to an input's current state (ideally 1.0) minus abs(initial_state) (ideally 0.0).
21 // Note: Detect() logic assumes this is greater than 0.5.
22 constexpr ControlState INPUT_DETECT_THRESHOLD = 0.55;
23
24 class CombinedInput final : public Device::Input
25 {
26 public:
27 using Inputs = std::pair<Device::Input*, Device::Input*>;
28
29 CombinedInput(std::string name, Inputs inputs)
30 : m_name(std::move(name)), m_inputs(std::move(inputs))
31 {
32 }
33 ControlState GetState() const override
34 {
35 ControlState result = 0;
36
37 if (m_inputs.first)
38 result = m_inputs.first->GetState();
39
40 if (m_inputs.second)
41 result = std::max(result, m_inputs.second->GetState());
42
43 return result;
44 }
45 std::string GetName() const override { return m_name; }
46 bool IsDetectable() const override { return false; }
47 bool IsChild(const Input* input) const override
48 {
49 return m_inputs.first == input || m_inputs.second == input;
50 }
51
52 private:
53 const std::string m_name;
54 const std::pair<Device::Input*, Device::Input*> m_inputs;
55 };
56
57 Device::~Device()
58 {
59 // delete inputs
60 for (Device::Input* input : m_inputs)
61 delete input;
62
63 // delete outputs
64 for (Device::Output* output : m_outputs)
65 delete output;
66 }
67
68 std::optional<int> Device::GetPreferredId() const
69 {
70 return {};
71 }
72
73 void Device::AddInput(Device::Input* const i)
74 {
75 m_inputs.push_back(i);
76 }
77
78 void Device::AddOutput(Device::Output* const o)
79 {
80 m_outputs.push_back(o);
81 }
82
83 std::string Device::GetQualifiedName() const
84 {
85 return fmt::format("{}/{}/{}", GetSource(), GetId(), GetName());
86 }
87
88 auto Device::GetParentMostInput(Input* child) const -> Input*
89 {
90 for (auto* input : m_inputs)
91 {
92 if (input->IsChild(child))
93 {
94 // Running recursively is currently unnecessary but it doesn't hurt.
95 return GetParentMostInput(input);
96 }
97 }
98
99 return child;
100 }
101
102 Device::Input* Device::FindInput(std::string_view name) const
103 {
104 for (Input* input : m_inputs)
105 {
106 if (input->IsMatchingName(name))
107 return input;
108 }
109
110 return nullptr;
111 }
112
113 Device::Output* Device::FindOutput(std::string_view name) const
114 {
115 for (Output* output : m_outputs)
116 {
117 if (output->IsMatchingName(name))
118 return output;
119 }
120
121 return nullptr;
122 }
123
124 bool Device::Control::IsMatchingName(std::string_view name) const
125 {
126 return GetName() == name;
127 }
128
129 bool Device::Control::IsHidden() const
130 {
131 return false;
132 }
133
134 class FullAnalogSurface final : public Device::Input
135 {
136 public:
137 FullAnalogSurface(Input* low, Input* high) : m_low(*low), m_high(*high) {}
138
139 ControlState GetState() const override
140 {
141 return (1 + std::max(0.0, m_high.GetState()) - std::max(0.0, m_low.GetState())) / 2;
142 }
143
144 std::string GetName() const override
145 {
146 // E.g. "Full Axis X+"
147 return "Full " + m_high.GetName();
148 }
149
150 bool IsDetectable() const override { return m_low.IsDetectable() && m_high.IsDetectable(); }
151
152 bool IsHidden() const override { return m_low.IsHidden() && m_high.IsHidden(); }
153
154 bool IsMatchingName(std::string_view name) const override
155 {
156 if (Control::IsMatchingName(name))
157 return true;
158
159 // Old naming scheme was "Axis X-+" which is too visually similar to "Axis X+".
160 // This has caused countless problems for users with mysterious misconfigurations.
161 // We match this old name to support old configurations.
162 const auto old_name = m_low.GetName() + *m_high.GetName().rbegin();
163
164 return old_name == name;
165 }
166
167 private:
168 Input& m_low;
169 Input& m_high;
170 };
171
172 void Device::AddFullAnalogSurfaceInputs(Input* low, Input* high)
173 {
174 AddInput(low);
175 AddInput(high);
176 AddInput(new FullAnalogSurface(low, high));
177 AddInput(new FullAnalogSurface(high, low));
178 }
179
180 void Device::AddCombinedInput(std::string name, const std::pair<std::string, std::string>& inputs)
181 {
182 AddInput(new CombinedInput(std::move(name), {FindInput(inputs.first), FindInput(inputs.second)}));
183 }
184
185 //
186 // DeviceQualifier :: ToString
187 //
188 // Get string from a device qualifier / serialize
189 //
190 std::string DeviceQualifier::ToString() const
191 {
192 if (source.empty() && (cid < 0) && name.empty())
193 return {};
194
195 if (cid > -1)
196 return fmt::format("{}/{}/{}", source, cid, name);
197 else
198 return fmt::format("{}//{}", source, name);
199 }
200
201 //
202 // DeviceQualifier :: FromString
203 //
204 // Set a device qualifier from a string / unserialize
205 //
206 void DeviceQualifier::FromString(const std::string& str)
207 {
208 *this = {};
209
210 std::istringstream ss(str);
211
212 std::getline(ss, source, '/');
213
214 // silly
215 std::getline(ss, name, '/');
216 std::istringstream(name) >> cid;
217
218 std::getline(ss, name);
219 }
220
221 //
222 // DeviceQualifier :: FromDevice
223 //
224 // Set a device qualifier from a device
225 //
226 void DeviceQualifier::FromDevice(const Device* const dev)
227 {
228 name = dev->GetName();
229 cid = dev->GetId();
230 source = dev->GetSource();
231 }
232
233 bool DeviceQualifier::operator==(const Device* const dev) const
234 {
235 if (dev->GetId() == cid)
236 if (dev->GetName() == name)
237 if (dev->GetSource() == source)
238 return true;
239
240 return false;
241 }
242
243 bool DeviceQualifier::operator==(const DeviceQualifier& devq) const
244 {
245 return std::tie(cid, name, source) == std::tie(devq.cid, devq.name, devq.source);
246 }
247
248 std::shared_ptr<Device> DeviceContainer::FindDevice(const DeviceQualifier& devq) const
249 {
250 std::lock_guard lk(m_devices_mutex);
251 for (const auto& d : m_devices)
252 {
253 if (devq == d.get())
254 return d;
255 }
256
257 return nullptr;
258 }
259
260 std::vector<std::shared_ptr<Device>> DeviceContainer::GetAllDevices() const
261 {
262 std::lock_guard lk(m_devices_mutex);
263
264 std::vector<std::shared_ptr<Device>> devices;
265
266 for (const auto& d : m_devices)
267 devices.emplace_back(d);
268
269 return devices;
270 }
271
272 std::vector<std::string> DeviceContainer::GetAllDeviceStrings() const
273 {
274 std::lock_guard lk(m_devices_mutex);
275
276 std::vector<std::string> device_strings;
277 DeviceQualifier device_qualifier;
278
279 for (const auto& d : m_devices)
280 {
281 device_qualifier.FromDevice(d.get());
282 device_strings.emplace_back(device_qualifier.ToString());
283 }
284
285 return device_strings;
286 }
287
288 bool DeviceContainer::HasDefaultDevice() const
289 {
290 std::lock_guard lk(m_devices_mutex);
291 // Devices are already sorted by priority
292 return !m_devices.empty() && m_devices[0]->GetSortPriority() >= 0;
293 }
294
295 std::string DeviceContainer::GetDefaultDeviceString() const
296 {
297 std::lock_guard lk(m_devices_mutex);
298 // Devices are already sorted by priority
299 if (m_devices.empty() || m_devices[0]->GetSortPriority() < 0)
300 return "";
301
302 DeviceQualifier device_qualifier;
303 device_qualifier.FromDevice(m_devices[0].get());
304 return device_qualifier.ToString();
305 }
306
307 Device::Input* DeviceContainer::FindInput(std::string_view name, const Device* def_dev) const
308 {
309 if (def_dev)
310 {
311 Device::Input* const inp = def_dev->FindInput(name);
312 if (inp)
313 return inp;
314 }
315
316 std::lock_guard lk(m_devices_mutex);
317 for (const auto& d : m_devices)
318 {
319 Device::Input* const i = d->FindInput(name);
320
321 if (i)
322 return i;
323 }
324
325 return nullptr;
326 }
327
328 Device::Output* DeviceContainer::FindOutput(std::string_view name, const Device* def_dev) const
329 {
330 return def_dev->FindOutput(name);
331 }
332
333 bool DeviceContainer::HasConnectedDevice(const DeviceQualifier& qualifier) const
334 {
335 const auto device = FindDevice(qualifier);
336 return device != nullptr && device->IsValid();
337 }
338
339 struct InputDetector::Impl
340 {
341 struct InputState
342 {
343 InputState(ciface::Core::Device::Input* input_) : input{input_} { stats.Push(0.0); }
344
345 ciface::Core::Device::Input* input;
346 ControlState initial_state = input->GetState();
347 ControlState last_state = initial_state;
348 MathUtil::RunningVariance<ControlState> stats;
349
350 // Prevent multiple detections until after release.
351 bool is_ready = true;
352
353 void Update()
354 {
355 const auto new_state = input->GetState();
356
357 if (!is_ready && new_state < (1 - INPUT_DETECT_THRESHOLD))
358 {
359 last_state = new_state;
360 is_ready = true;
361 stats.Clear();
362 }
363
364 const auto difference = new_state - last_state;
365 stats.Push(difference);
366 last_state = new_state;
367 }
368
369 bool IsPressed()
370 {
371 if (!is_ready)
372 return false;
373
374 // We want an input that was initially 0.0 and currently 1.0.
375 const auto detection_score = (last_state - std::abs(initial_state));
376 return detection_score > INPUT_DETECT_THRESHOLD;
377 }
378 };
379
380 struct DeviceState
381 {
382 std::shared_ptr<Device> device;
383
384 std::vector<InputState> input_states;
385 };
386
387 std::vector<DeviceState> device_states;
388 };
389
390 InputDetector::InputDetector() : m_start_time{}, m_state{}
391 {
392 }
393
394 void InputDetector::Start(const DeviceContainer& container,
395 std::span<const std::string> device_strings)
396
397 {
398 m_start_time = Clock::now();
399 m_detections = {};
400 m_state = std::make_unique<Impl>();
401
402 // Acquire devices and initial input states.
403 for (const auto& device_string : device_strings)
404 {
405 DeviceQualifier dq;
406 dq.FromString(device_string);
407 auto device = container.FindDevice(dq);
408
409 if (!device)
410 continue;
411
412 std::vector<Impl::InputState> input_states;
413
414 for (auto* input : device->Inputs())
415 {
416 // Don't detect things like absolute cursor positions, accelerometers, or gyroscopes.
417 if (!input->IsDetectable())
418 continue;
419
420 // Undesirable axes will have negative values here when trying to map a
421 // "FullAnalogSurface".
422 input_states.push_back(Impl::InputState{input});
423 }
424
425 if (!input_states.empty())
426 {
427 m_state->device_states.emplace_back(
428 Impl::DeviceState{std::move(device), std::move(input_states)});
429 }
430 }
431
432 // If no inputs were found via the supplied device strings, immediately complete.
433 if (m_state->device_states.empty())
434 m_state.reset();
435 }
436
437 void InputDetector::Update(std::chrono::milliseconds initial_wait,
438 std::chrono::milliseconds confirmation_wait,
439 std::chrono::milliseconds maximum_wait)
440 {
441 if (m_state)
442 {
443 const auto now = Clock::now();
444 const auto elapsed_time = now - m_start_time;
445
446 if (elapsed_time >= maximum_wait || (m_detections.empty() && elapsed_time >= initial_wait) ||
447 (!m_detections.empty() && m_detections.back().release_time.has_value() &&
448 now >= *m_detections.back().release_time + confirmation_wait))
449 {
450 m_state.reset();
451 return;
452 }
453
454 for (auto& device_state : m_state->device_states)
455 {
456 for (auto& input_state : device_state.input_states)
457 {
458 input_state.Update();
459
460 if (input_state.IsPressed())
461 {
462 input_state.is_ready = false;
463
464 // Digital presses will evaluate as 1 here.
465 // Analog presses will evaluate greater than 1.
466 const auto smoothness =
467 1 / std::sqrt(input_state.stats.Variance() / input_state.stats.Mean());
468
469 Detection new_detection;
470 new_detection.device = device_state.device;
471 new_detection.input = input_state.input;
472 new_detection.press_time = now;
473 new_detection.smoothness = smoothness;
474
475 // We found an input. Add it to our detections.
476 m_detections.emplace_back(std::move(new_detection));
477 }
478 }
479 }
480
481 // Check for any releases of our detected inputs.
482 for (auto& d : m_detections)
483 {
484 if (!d.release_time.has_value() && d.input->GetState() < (1 - INPUT_DETECT_THRESHOLD))
485 d.release_time = Clock::now();
486 }
487 }
488 }
489
490 InputDetector::~InputDetector() = default;
491
492 bool InputDetector::IsComplete() const
493 {
494 return !m_state;
495 }
496
497 auto InputDetector::GetResults() const -> const Results&
498 {
499 return m_detections;
500 }
501
502 auto InputDetector::TakeResults() -> Results
503 {
504 return std::move(m_detections);
505 }
506
507 } // namespace ciface::Core