| 1 | // Copyright 2023 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #pragma once |
| 5 | |
| 6 | #include <atomic> |
| 7 | |
| 8 | #include "Common/CommonTypes.h" |
| 9 | |
| 10 | class TASControlState |
| 11 | { |
| 12 | public: |
| 13 | // Call this from the CPU thread to get the current value. (This function can also safely be |
| 14 | // called from the UI thread, but you're effectively just getting the value the UI control has.) |
| 15 | int GetValue() const; |
| 16 | // Call this from the CPU thread when the controller state changes. |
| 17 | // If the return value is true, queue up a call to ApplyControllerChangeValue on the UI thread. |
| 18 | bool OnControllerValueChanged(int new_value); |
| 19 | // Call this from the UI thread when the user changes the value using the UI. |
| 20 | void OnUIValueChanged(int new_value); |
| 21 | // Call this from the UI thread after OnControllerValueChanged returns true, |
| 22 | // and set the state of the UI control to the return value. |
| 23 | int ApplyControllerValueChange(); |
| 24 | |
| 25 | private: |
| 26 | // A description of how threading is handled: The UI thread can update its copy of the state |
| 27 | // whenever it wants to, and must *not* increment the version when doing so. The CPU thread can |
| 28 | // update its copy of the state whenever it wants to, and *must* increment the version when doing |
| 29 | // so. When the CPU thread updates its copy of the state, the UI thread should then (possibly |
| 30 | // after a delay) mirror the change by copying the CPU thread's state to the UI thread's state. |
| 31 | // This mirroring is the only way for the version number stored in the UI thread's state to |
| 32 | // change. The version numbers of the two copies can be compared to check if the UI thread's view |
| 33 | // of what has happened on the CPU thread is up to date. |
| 34 | |
| 35 | struct State |
| 36 | { |
| 37 | int version = 0; |
| 38 | int value = 0; |
| 39 | }; |
| 40 | |
| 41 | std::atomic<State> m_ui_thread_state = State{}; |
| 42 | std::atomic<State> m_cpu_thread_state = State{}; |
| 43 | }; |