Mountain  1.0.0
Simple C++ 2D Game Framework
state_machine.hpp
1 #pragma once
2 
3 #include "Mountain/core.hpp"
4 
5 #include <magic_enum/magic_enum.hpp>
6 
7 #include "Mountain/scene/component/component.hpp"
11 
12 namespace Mountain
13 {
15  {
16  Action update{};
17  Action begin{};
18  Action end{};
19  CoroutineFunction<> coroutine{};
20  };
21 
22  template <Concepts::EnumT T>
23  class StateMachine : public Component
24  {
25  public:
26  using Type = T;
27  using UnderlyingType = Meta::UnderlyingEnumType<T>;
28 
29  bool_t locked = false;
30 
31  using Component::operator=;
32 
33  StateMachine() = default;
34  ~StateMachine() override;
35 
36  // Because of the Coroutine, we cannot copy the StateMachine
37  // Delete copy operations
38  StateMachine(const StateMachine&) = delete;
39  StateMachine& operator=(const StateMachine&) = delete;
40 
41  // Define move operations
42  [[nodiscard]]
43  StateMachine(StateMachine&& other) noexcept;
44  StateMachine& operator=(StateMachine&& other) noexcept;
45 
47  void SetCallbacks(T state, StateMachineCallbacks&& callbacks); // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
48 
49  void Update() override;
50 
52  [[nodiscard]]
53  T GetState() const;
55  [[nodiscard]]
56  UnderlyingType GetStateIntegral() const;
58  void SetState(T newState);
60  void ForceState(T newState);
62  // ReSharper disable once CppEnforceOverridingFunctionStyle
63  StateMachine& operator=(T newState);
64 
66  [[nodiscard]]
67  T GetPreviousState() const;
69  [[nodiscard]]
70  UnderlyingType GetPreviousStateIntegral() const;
71 
73  [[nodiscard]]
74  bool_t GetStateChanged() const;
75 
76  [[nodiscard]]
77  // ReSharper disable once CppNonExplicitConversionOperator
78  operator T();
79 
80  private:
81  template <typename U>
82  using Array = std::array<U, magic_enum::enum_count<T>()>;
83 
84  Array<Action> m_Begins;
85  Array<Action> m_Updates;
86  Array<Action> m_Ends;
87  Array<CoroutineFunction<>> m_Coroutines;
88 
89  Coroutine m_CurrentCoroutine;
90 
91  T m_State = static_cast<T>(0);
92  T m_PreviousState = static_cast<T>(0);
93  bool_t m_StateChanged = false;
94  };
95 }
96 
97 #include "Mountain/scene/component/state_machine.inl"
Represents a behavior that can be attached to an Entity.
Definition: component.hpp:10
Defines the Coroutine class.
std::function< Coroutine(Args...)> CoroutineFunction
Coroutine function prototype.
Definition: coroutine.hpp:217
Wrapper around C++20 Coroutines.
Definition: coroutine.hpp:61
Defines utilities for meta programming and template manipulation.
Defines the Mountain::Concepts namespace which contains useful concepts used in the engine...
Contains all declarations of the Mountain Framework.
Definition: audio.hpp:22