| 1 | // Copyright 2023 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "DolphinQt/TAS/TASControlState.h" |
| 5 | |
| 6 | #include <atomic> |
| 7 | |
| 8 | int TASControlState::GetValue() const |
| 9 | { |
| 10 | const State ui_thread_state = m_ui_thread_state.load(std::memory_order_relaxed); |
| 11 | const State cpu_thread_state = m_cpu_thread_state.load(std::memory_order_relaxed); |
| 12 | |
| 13 | return (ui_thread_state.version != cpu_thread_state.version ? cpu_thread_state : ui_thread_state) |
| 14 | .value; |
| 15 | } |
| 16 | |
| 17 | bool TASControlState::OnControllerValueChanged(int new_value) |
| 18 | { |
| 19 | const State cpu_thread_state = m_cpu_thread_state.load(std::memory_order_relaxed); |
| 20 | |
| 21 | if (cpu_thread_state.value == new_value) |
| 22 | { |
| 23 | // The CPU thread state is already up to date with the controller. No need to do anything |
| 24 | return false; |
| 25 | } |
| 26 | |
| 27 | const State new_state{static_cast<int>(cpu_thread_state.version + 1), new_value}; |
| 28 | m_cpu_thread_state.store(new_state, std::memory_order_relaxed); |
| 29 | |
| 30 | return true; |
| 31 | } |
| 32 | |
| 33 | void TASControlState::OnUIValueChanged(int new_value) |
| 34 | { |
| 35 | const State ui_thread_state = m_ui_thread_state.load(std::memory_order_relaxed); |
| 36 | |
| 37 | const State new_state{ui_thread_state.version, new_value}; |
| 38 | m_ui_thread_state.store(new_state, std::memory_order_relaxed); |
| 39 | } |
| 40 | |
| 41 | int TASControlState::ApplyControllerValueChange() |
| 42 | { |
| 43 | const State ui_thread_state = m_ui_thread_state.load(std::memory_order_relaxed); |
| 44 | const State cpu_thread_state = m_cpu_thread_state.load(std::memory_order_relaxed); |
| 45 | |
| 46 | if (ui_thread_state.version == cpu_thread_state.version) |
| 47 | { |
| 48 | // The UI thread state is already up to date with the CPU thread. No need to do anything |
| 49 | return ui_thread_state.value; |
| 50 | } |
| 51 | else |
| 52 | { |
| 53 | m_ui_thread_state.store(cpu_thread_state, std::memory_order_relaxed); |
| 54 | return cpu_thread_state.value; |
| 55 | } |
| 56 | } |