-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEngine.cpp
executable file
·156 lines (120 loc) · 2.52 KB
/
Engine.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#include "engine.h"
Engine::Engine(int width, int height)
{
board = new Board();
isRunning = false;
this->width = width;
this->height = height;
frameCap = 1.0 / FRAMES_PER_SECOND;
firstTime = 0;
lastTime = clock() / (double)CLOCKS_PER_SEC;
updateTime = lastTime;
passedTime = 0;
unprocessedTime = 0;
oneSecTime = 0;
updateTime = 0;
frames = 0;
fps = 0;
}
Engine::~Engine()
{
delete board;
}
void Engine::start()
{
if(isRunning) return;
run();
}
void Engine::run()
{
isRunning = true;
while(isRunning)
{
kbhit(); //?
firstTime = clock() / (double)CLOCKS_PER_SEC;
if(firstTime < lastTime && lastTime > 0) passedTime = 0.0001;
else passedTime = firstTime - lastTime;
lastTime = firstTime;
unprocessedTime += passedTime;
oneSecTime += passedTime;
updateTime += passedTime;
/////////
update(); //?
/////////
if(unprocessedTime >= frameCap)
{
// 25 frames per second
unprocessedTime -= frameCap;
////////
render();
////////
showFrames();
}
frames++;
}
}
void Engine::update()
{
//////////////////////////////////////////////////////
/* UPDATE DATA HERE */
double maxUpdateTime = 0;
w = board->findFirst();
if(w) maxUpdateTime = w->getUpdateTime();
while (w)
{
if(fmod(updateTime, (double)w->getUpdateTime()) > 0 && fmod(updateTime, (double)w->getUpdateTime()) < 0.0001)
{
w->update();
}
w = board->findNext();
if(w)
{
if(maxUpdateTime < w->getUpdateTime()) maxUpdateTime = w->getUpdateTime();
}
}
if(updateTime >= maxUpdateTime) updateTime = 0.0;
/////////////////////////////////////////////////////
}
void Engine::render()
{
Start(width, height);
Background(0, 0, 0);
//////////////////////////////////////////////////////
/* RENDER PICS HERE */
board->render();
//////////////////////////////////////////////////////
End();
}
void Engine::showFrames()
{
if(oneSecTime >= 1)
{
printf("frames: [%d], fps: [%d]\n", frames, fps);
oneSecTime = 0;
frames = 0;
fps = 0;
}
fps++;
}
int Engine::kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
isRunning = false;
return 1;
}
return 0;
}