forked from asyncwise/CoroBehaviour
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoroBehaviour.cpp
More file actions
107 lines (95 loc) · 2.37 KB
/
CoroBehaviour.cpp
File metadata and controls
107 lines (95 loc) · 2.37 KB
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
#include "CoroBehaviour.h"
class CoroInternal : public Coroutine
{
private:
CoroPull Pull;
public:
CoroInternal(CoroPull& InPull) : Pull(std::move(InPull)) { }
protected:
virtual void Tick(float DeltaTime) override { Pull(); }
virtual bool IsDone() override { return !Pull; }
virtual Coroutine* GetYieldReturn() override { return Pull.get(); }
};
CoroBehaviour::~CoroBehaviour()
{
StopAllCoroutines();
}
void CoroBehaviour::PushYieldReturn(Coroutine* CoroutinePtr)
{
Coroutine* YieldReturn = CoroutinePtr->GetYieldReturn();
if (YieldReturn)
{
YieldReturn->Next = CoroutinePtr;
CoroutinePtr->IsActive = false;
Coroutines.erase(CoroutinePtr);
if (YieldReturn->IsActive)
{
Coroutines.insert(YieldReturn);
}
}
}
Coroutine* CoroBehaviour::StartCoroutine(CoroEnumerator Enumerator)
{
CoroPull Pull(Enumerator);
if (Pull)
{
Coroutine* CoroutinePtr = new CoroInternal(Pull);
Coroutines.insert(CoroutinePtr);
PushYieldReturn(CoroutinePtr);
return CoroutinePtr;
}
return nullptr;
}
void CoroBehaviour::StopCoroutine(Coroutine* CoroutinePtr)
{
Coroutine* Caller = CoroutinePtr->Next;
if (Caller)
{
Coroutines.insert(Caller);
Caller->IsActive = true;
}
for (Coroutine* It = CoroutinePtr; It != nullptr; It = It->GetYieldReturn())
{
Coroutines.erase(It);
delete It;
}
}
void CoroBehaviour::StopAllCoroutines()
{
for (Coroutine* CoroutinePtr : Coroutines)
{
while (CoroutinePtr != nullptr)
{
Coroutine* Caller = CoroutinePtr->Next;
delete CoroutinePtr;
CoroutinePtr = Caller;
}
}
Coroutines.clear();
}
void CoroBehaviour::TickCoroutines(float DeltaTime)
{
CoroSet Copies = Coroutines;
for (Coroutine* It : Copies)
{
while (true)
{
It->Tick(DeltaTime);
if (!It->IsDone())
{
PushYieldReturn(It);
break;
}
Coroutine* Caller = It->Next;
Coroutines.erase(It);
delete It;
if (Caller == nullptr)
{
break;
}
Coroutines.insert(Caller);
It = Caller;
It->IsActive = true;
}
}
}