-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhfsm.cpp
134 lines (106 loc) · 2.32 KB
/
hfsm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include "hfsm.hpp"
Hfsm::Hfsm(State *initial) :
active{initial}
{
callEntry(root(), active);
}
Hfsm::~Hfsm()
{
callExit(root(), active);
}
void Hfsm::handle(const Event *event)
{
active = handle(active, event);
}
static bool isAncestorOf(const State *state, const State *active)
{
if (active == nullptr)
{
return false;
}
if (state == active)
{
return true;
}
return isAncestorOf(state, active->parent());
}
const Transition *transitionFor(const State *state, const State *active)
{
for (std::size_t i = 0; i < state->transitionCount(); i++)
{
const Transition *itr = state->transition(i);
if (isAncestorOf(&itr->source(), active))
{
return itr;
}
}
return nullptr;
}
std::pair<const Transition *, State *> Hfsm::firstTransitionTopDown(State *state, const Event *event, const State *active)
{
if (state == nullptr)
{
return {};
}
const auto transition = transitionFor(state, active);
if (transition)
{
if (transition->canHandle(event))
{
return {transition, state};
}
}
if (state == state->parent())
{
return {};
}
return firstTransitionTopDown(state->parent(), event, active);
// this code is for fallback transition
// const auto transition = firstTransitionTopDown(state->parent(), event, active);
// if (transition)
// {
// return transition;
// }
// return state->transitionFor(event, active);
}
State *Hfsm::handle(State *active, const Event *event)
{
const auto result = firstTransitionTopDown(active, event, active);
if (result.first)
{
const auto transition = result.first;
const auto context = result.second;
const auto source = active;
const auto destination = transition->destination().initial();
callExit(context, source);
transition->execute(event);
callEntry(context, destination);
return destination;
}
return active;
}
State *Hfsm::root() const
{
State* walker = active;
while (walker->parent() != nullptr)
{
walker = walker->parent();
}
return walker;
}
void Hfsm::callEntry(State *top, State *bottom) const
{
if (top != bottom)
{
callEntry(top, bottom->parent());
bottom->entry();
}
}
void Hfsm::callExit(State *top, State *bottom) const
{
if (top != bottom)
{
bottom->exit();
callExit(top, bottom->parent());
}
}