1 /* Copyright (C) 2024 Wildfire Games.
2 * This file is part of 0 A.D.
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.
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.
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/>.
18 #include "precompiled.h"
22 CFsmEvent::CFsmEvent(unsigned int type
, void* pParam
)
28 CFsmEvent::~CFsmEvent()
36 m_FirstState
= FSM_INVALID_STATE
;
37 m_CurrState
= FSM_INVALID_STATE
;
38 m_NextState
= FSM_INVALID_STATE
;
48 // Does nothing by default
54 m_Transitions
.clear();
57 m_FirstState
= FSM_INVALID_STATE
;
58 m_CurrState
= FSM_INVALID_STATE
;
59 m_NextState
= FSM_INVALID_STATE
;
62 void CFsm::AddState(unsigned int state
)
64 m_States
.insert(state
);
67 void CFsm::AddTransition(unsigned int state
, unsigned int eventType
, unsigned int nextState
,
68 Action
* pAction
/* = nullptr */, void* pContext
/* = nullptr*/)
70 // Make sure we store the current state
73 // Make sure we store the next state
76 m_Transitions
.insert({TransitionKey
{state
, eventType
}, Transition
{{pAction
, pContext
}, nextState
}});
79 void CFsm::SetFirstState(unsigned int firstState
)
81 m_FirstState
= firstState
;
84 void CFsm::SetCurrState(unsigned int state
)
89 bool CFsm::IsFirstTime() const
91 return (m_CurrState
== FSM_INVALID_STATE
);
94 bool CFsm::Update(unsigned int eventType
, void* pEventParam
)
97 m_CurrState
= m_FirstState
;
99 if (!IsValidState(m_CurrState
))
103 auto transitionIterator
= m_Transitions
.find({m_CurrState
, eventType
});
104 if (transitionIterator
== m_Transitions
.end())
107 CFsmEvent event
{eventType
, pEventParam
};
109 // Save the default state transition (actions might call SetNextState
111 SetNextState(transitionIterator
->second
.nextState
);
113 if (!transitionIterator
->second
.action(event
))
116 SetCurrState(GetNextState());
118 // Reset the next state since it's no longer valid
119 SetNextState(FSM_INVALID_STATE
);
124 bool CFsm::IsDone() const
126 // By default the internal flag m_Done is tested
130 bool CFsm::IsValidState(unsigned int state
) const
132 StateSet::const_iterator it
= m_States
.find(state
);
133 if (it
== m_States
.end())