Line data Source code
1 : /* Copyright (C) 2025 Wildfire Games. 2 : * This file is part of 0 A.D. 3 : * 4 : * 0 A.D. is free software: you can redistribute it and/or modify 5 : * it under the terms of the GNU General Public License as published by 6 : * the Free Software Foundation, either version 2 of the License, or 7 : * (at your option) any later version. 8 : * 9 : * 0 A.D. is distributed in the hope that it will be useful, 10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 : * GNU General Public License for more details. 13 : * 14 : * You should have received a copy of the GNU General Public License 15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>. 16 : */ 17 : 18 : #ifndef FSM_H 19 : #define FSM_H 20 : 21 : #include <cstddef> 22 : #include <limits> 23 : #include <unordered_map> 24 : 25 : constexpr unsigned int FSM_INVALID_STATE{std::numeric_limits<unsigned int>::max()}; 26 : 27 : /** 28 : * Represents a signal in the state machine that a change has occurred. 29 : * The CFsmEvent objects are under the control of CFsm so 30 : * they are created and deleted via CFsm. 31 : */ 32 : template <typename MessageType> 33 : class CFsmEvent 34 : { 35 : public: 36 11 : CFsmEvent(unsigned int type, MessageType param) : 37 11 : m_Type{type}, 38 2 : m_Param{param} 39 : {} 40 : 41 0 : unsigned int GetType() const 42 : { 43 0 : return m_Type; 44 : } 45 : 46 2 : MessageType GetParamRef() 47 : { 48 2 : return m_Param; 49 : } 50 : 51 : private: 52 : unsigned int m_Type; // Event type 53 : MessageType m_Param; // Event paramater 54 : }; 55 : 56 : /** 57 : * Manages states, events, actions and transitions 58 : * between states. It provides an interface for advertising 59 : * events and track the current state. The implementation is 60 : * a Mealy state machine, so the system respond to events 61 : * and execute some action. 62 : * 63 : * A Mealy state machine has behaviour associated with state 64 : * transitions; Mealy machines are event driven where an 65 : * event triggers a state transition. 66 : */ 67 : template <typename Context, typename MessageType> 68 4 : class CFsm 69 : { 70 : using Action = bool(Context* pContext, CFsmEvent<MessageType>* pEvent); 71 : 72 : struct CallbackFunction 73 : { 74 : Action* pFunction{nullptr}; 75 : Context* pContext{nullptr}; 76 : 77 11 : bool operator()(CFsmEvent<MessageType>& event) const 78 : { 79 11 : return !pFunction || pFunction(pContext, &event); 80 : } 81 : }; 82 : public: 83 : /** 84 : * Adds a new transistion to the state machine. 85 : */ 86 2 : void AddTransition(unsigned int state, unsigned int eventType, unsigned int nextState, 87 : Action* pAction = nullptr, Context* pContext = nullptr) 88 : { 89 2 : m_Transitions.insert({TransitionKey{state, eventType}, 90 : Transition{{pAction, pContext}, nextState}}); 91 : } 92 : 93 : /** 94 : * Sets the initial state for FSM. 95 : */ 96 2 : void SetFirstState(unsigned int firstState) 97 : { 98 2 : m_FirstState = firstState; 99 : } 100 : 101 : /** 102 : * Sets the current state and update the last state to the current state. 103 : */ 104 11 : void SetCurrState(unsigned int state) 105 : { 106 11 : m_CurrState = state; 107 : } 108 1 : unsigned int GetCurrState() const 109 : { 110 1 : return m_CurrState; 111 : } 112 : 113 22 : void SetNextState(unsigned int nextState) 114 : { 115 22 : m_NextState = nextState; 116 0 : } 117 : 118 11 : unsigned int GetNextState() const 119 : { 120 11 : return m_NextState; 121 : } 122 : 123 : /** 124 : * Updates the FSM and retrieves next state. 125 : * @return whether the state was changed. 126 : */ 127 19 : bool Update(unsigned int eventType, MessageType eventData) 128 : { 129 19 : if (IsFirstTime()) 130 2 : m_CurrState = m_FirstState; 131 : 132 : // Lookup transition 133 19 : auto transitionIterator = m_Transitions.find({m_CurrState, eventType}); 134 19 : if (transitionIterator == m_Transitions.end()) 135 : return false; 136 : 137 11 : CFsmEvent<MessageType> event{eventType, eventData}; 138 : 139 : // Save the default state transition (actions might call SetNextState 140 : // to override this) 141 11 : SetNextState(transitionIterator->second.nextState); 142 : 143 19 : if (!transitionIterator->second.action(event)) 144 : return false; 145 : 146 11 : SetCurrState(GetNextState()); 147 : 148 : // Reset the next state since it's no longer valid 149 11 : SetNextState(FSM_INVALID_STATE); 150 : 151 11 : return true; 152 : } 153 : 154 : /** 155 : * Tests whether the state machine has finished its work. 156 : */ 157 : bool IsDone() const 158 : { 159 : return m_Done; 160 : } 161 : 162 : private: 163 : struct TransitionKey 164 : { 165 : using UnderlyingType = unsigned int; 166 : UnderlyingType state; 167 : UnderlyingType eventType; 168 : 169 : struct Hash 170 : { 171 33 : size_t operator()(const TransitionKey& key) const noexcept 172 : { 173 33 : constexpr size_t count{std::numeric_limits<size_t>::digits / 2}; 174 33 : const size_t wideState{static_cast<size_t>(key.state)}; 175 33 : const size_t rotatedState{(wideState << count) | (wideState >> count)}; 176 33 : return static_cast<size_t>(key.eventType) ^ rotatedState; 177 : } 178 : }; 179 : 180 11 : friend bool operator==(const TransitionKey& lhs, const TransitionKey& rhs) noexcept 181 : { 182 11 : return lhs.state == rhs.state && lhs.eventType == rhs.eventType; 183 : } 184 : }; 185 : 186 : struct Transition 187 : { 188 : CallbackFunction action; 189 : unsigned int nextState; 190 : }; 191 : 192 : using TransitionMap = std::unordered_map<TransitionKey, const Transition, 193 : typename TransitionKey::Hash>; 194 : 195 : /** 196 : * Verifies whether state machine has already been updated. 197 : */ 198 19 : bool IsFirstTime() const 199 : { 200 19 : return m_CurrState == FSM_INVALID_STATE; 201 : } 202 : 203 : bool m_Done{false}; 204 : unsigned int m_FirstState{FSM_INVALID_STATE}; 205 : unsigned int m_CurrState{FSM_INVALID_STATE}; 206 : unsigned int m_NextState{FSM_INVALID_STATE}; 207 : TransitionMap m_Transitions; 208 : }; 209 : 210 : #endif // FSM_H