-
Notifications
You must be signed in to change notification settings - Fork 47
/
GameConnection.cpp
372 lines (335 loc) · 11.8 KB
/
GameConnection.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#include <zmq.hpp>
#undef min
#undef max
#include "GameConnection.h"
#include "MessageTCP.h"
#include "Camera/GlobalCamera.h"
#include "inode.h"
#include "ientity.h"
#include "map/Map.h"
#include "selection/RadiantSelectionSystem.h"
#include "modulesystem/StaticModule.h"
#include <sigc++/signal.h>
//note: I have no idea where to put it
//I guess if another user of ZeroMQ appears,
//then this context should go to independent common place.
zmq::context_t g_ZeroMqContext;
namespace gameconn {
//this is how often this class "thinks" when idle
static const int THINK_INTERVAL = 123;
static std::string seqnoPreamble(int seq) {
return fmt::format("seqno {}\n", seq);
}
static std::string messagePreamble(std::string type) {
return fmt::format("message \"{}\"\n", type);
}
static std::string actionPreamble(std::string type) {
return messagePreamble("action") + fmt::format("action \"{}\"\n", type);
}
static std::string queryPreamble(std::string type) {
return messagePreamble("query") + fmt::format("query \"{}\"\n", type);
}
int GameConnection::newSeqno() {
return ++_seqno;
}
void GameConnection::sendRequest(const std::string &request) {
assert(_seqnoInProgress == 0);
int seqno = newSeqno();
std::string fullMessage = seqnoPreamble(seqno) + request;
_connection->writeMessage(fullMessage.data(), fullMessage.size());
_seqnoInProgress = seqno;
}
bool GameConnection::sendAnyPendingAsync() {
if (_mapObserver.getChanges().size() && _updateMapAlways) {
//note: this is blocking
doUpdateMap();
return true;
}
return sendPendingCameraUpdate();
}
void GameConnection::think() {
_connection->think();
if (_seqnoInProgress) {
//check if full response is here
if (_connection->readMessage(_response)) {
//validate and remove preamble
int responseSeqno, lineLen;
int ret = sscanf(_response.data(), "response %d\n%n", &responseSeqno, &lineLen);
assert(ret == 1); ret;
assert(responseSeqno == _seqnoInProgress);
_response.erase(_response.begin(), _response.begin() + lineLen);
//mark request as "no longer in progress"
//note: response can be used in outer function
_seqnoInProgress = 0;
}
}
else {
//doing nothing now: send async command if present
bool sentAsync = sendAnyPendingAsync();
sentAsync = false; //unused
}
_connection->think();
}
void GameConnection::waitAction() {
while (_seqnoInProgress)
think();
}
void GameConnection::finish() {
//wait for current request in progress to finish
waitAction();
//send pending async commands and wait for them to finish
while (sendAnyPendingAsync())
waitAction();
}
std::string GameConnection::executeRequest(const std::string &request) {
//make sure current request is finished (if any)
waitAction();
assert(_seqnoInProgress == 0);
//prepend seqno line and send message
sendRequest(request);
//wait until response is ready
waitAction();
return std::string(_response.begin(), _response.end());
}
bool GameConnection::connect() {
if (_connection && _connection->isAlive())
return true; //already connected
if (_connection)
_connection.reset();
if (_thinkTimer)
_thinkTimer.reset();
if (_mapEventListener)
_mapEventListener.reset();
//connection using ZeroMQ socket
std::unique_ptr<zmq::socket_t> zmqConnection(new zmq::socket_t(g_ZeroMqContext, ZMQ_STREAM));
zmqConnection->connect(fmt::format("tcp://127.0.0.1:{}", 3879));
_connection.reset(new MessageTcp());
_connection->init(std::move(zmqConnection));
if (!_connection->isAlive())
return false;
_thinkTimer.reset(new wxTimer());
_thinkTimer->Connect(wxEVT_TIMER, wxTimerEventHandler(GameConnection::onTimerEvent), NULL, this);
_thinkTimer->Start(THINK_INTERVAL);
_mapEventListener.reset(new sigc::connection(
GlobalMap().signal_mapEvent().connect(
sigc::mem_fun(*this, &GameConnection::onMapEvent)
)
));
return true;
}
void GameConnection::disconnect() {
setUpdateMapLevel(false, false);
setCameraSyncEnabled(false);
if (_connection) {
finish();
_connection.reset();
}
if (_thinkTimer) {
_thinkTimer->Stop();
_thinkTimer.reset();
}
if (_mapEventListener)
_mapEventListener.reset();
}
GameConnection::~GameConnection() {
disconnect();
};
//-------------------------------------------------------------
const std::string& GameConnection::getName() const {
static std::string _name = MODULE_GAMECONNECTION;
return _name;
}
const StringSet& GameConnection::getDependencies() const {
static StringSet _dependencies;
if (_dependencies.empty()) {
_dependencies.insert(MODULE_CAMERA);
_dependencies.insert(MODULE_COMMANDSYSTEM);
_dependencies.insert(MODULE_MAP);
_dependencies.insert(MODULE_SCENEGRAPH);
_dependencies.insert(MODULE_SELECTIONSYSTEM);
}
return _dependencies;
}
void GameConnection::initialiseModule(const ApplicationContext& ctx) {
}
void GameConnection::shutdownModule() {
disconnect();
}
module::StaticModule<GameConnection> gameConnectionModule;
//-------------------------------------------------------------
std::string GameConnection::composeConExecRequest(std::string consoleLine) {
//remove trailing spaces/EOLs
while (!consoleLine.empty() && isspace(consoleLine.back()))
consoleLine.pop_back();
return actionPreamble("conexec") + "content:\n" + consoleLine + "\n";
}
void GameConnection::executeSetTogglableFlag(const std::string &toggleCommand, bool enable, const std::string &offKeyword) {
if (!connect())
return;
std::string text = composeConExecRequest(toggleCommand);
int attempt;
for (attempt = 0; attempt < 2; attempt++) {
std::string response = executeRequest(text);
bool isEnabled = (response.find(offKeyword) == std::string::npos);
if (enable == isEnabled)
break;
//wrong state: toggle it again
}
assert(attempt < 2); //two toggles not enough?...
}
std::string GameConnection::executeGetCvarValue(const std::string &cvarName, std::string *defaultValue) {
if (!connect())
return "";
std::string text = composeConExecRequest(cvarName);
std::string response = executeRequest(text);
//parse response (imagine how easy that would be with regex...)
while (response.size() && isspace(response.back()))
response.pop_back();
std::string expLeft = fmt::format("\"{}\" is:\"", cvarName);
std::string expMid = "\" default:\"";
std::string expRight = "\"";
int posLeft = response.find(expLeft);
int posMid = response.find(expMid);
if (posLeft < 0 || posMid < 0) {
rError() << fmt::format("ExecuteGetCvarValue: can't parse value of {}", cvarName);
return "";
}
int posLeftEnd = posLeft + expLeft.size();
int posMidEnd = posMid + expMid.size();
int posRight = response.size() - expRight.size();
std::string currValue = response.substr(posLeftEnd, posMid - posLeftEnd);
std::string defValue = response.substr(posMidEnd, posRight - posMidEnd);
//return results
if (defaultValue)
*defaultValue = defValue;
return currValue;
}
void GameConnection::updateCamera() {
connect();
if (auto camWnd = GlobalCamera().getActiveCamWnd()) {
Vector3 orig = camWnd->getCameraOrigin(), angles = camWnd->getCameraAngles();
_cameraOutData[0] = orig;
_cameraOutData[1] = angles;
//note: the update is not necessarily sent right now
_cameraOutPending = true;
}
think();
}
bool GameConnection::sendPendingCameraUpdate() {
if (_cameraOutPending) {
std::string text = composeConExecRequest(fmt::format(
"setviewpos {:0.3f} {:0.3f} {:0.3f} {:0.3f} {:0.3f} {:0.3f}",
_cameraOutData[0].x(), _cameraOutData[0].y(), _cameraOutData[0].z(),
-_cameraOutData[1].x(), _cameraOutData[1].y(), _cameraOutData[1].z()
));
sendRequest(text);
_cameraOutPending = false;
return true;
}
return false;
}
class GameConnection_CameraObserver : public CameraObserver {
GameConnection &_owner;
public:
GameConnection_CameraObserver(GameConnection &owner) : _owner(owner) {}
virtual void cameraMoved() override {
_owner.updateCamera();
}
};
void GameConnection::setCameraSyncEnabled(bool enable) {
if (!enable && _cameraObserver) {
GlobalCamera().removeCameraObserver(_cameraObserver.get());
_cameraObserver.reset();
}
if (enable) {
if (!_cameraObserver) {
_cameraObserver.reset(new GameConnection_CameraObserver(*this));
GlobalCamera().addCameraObserver(_cameraObserver.get());
}
executeSetTogglableFlag("god", true, "OFF");
executeSetTogglableFlag("noclip", true, "OFF");
executeSetTogglableFlag("notarget", true, "OFF");
//sync camera location right now
updateCamera();
finish();
}
}
void GameConnection::backSyncCamera() {
if (!connect())
return;
std::string text = executeRequest(composeConExecRequest("getviewpos"));
Vector3 orig, angles;
if (sscanf(text.c_str(), "%lf%lf%lf%lf%lf%lf", &orig.x(), &orig.y(), &orig.z(), &angles.x(), &angles.y(), &angles.z()) == 6) {
if (auto camWnd = GlobalCamera().getActiveCamWnd()) {
angles.x() *= -1.0;
camWnd->setCameraOrigin(orig);
camWnd->setCameraAngles(angles);
}
}
}
void GameConnection::togglePauseGame() {
if (!connect())
return;
std::string value = executeGetCvarValue("g_stopTime");
std::string oppositeValue = (value == "0" ? "1" : "0");
std::string text = composeConExecRequest(fmt::format("g_stopTime {}", oppositeValue));
executeRequest(text);
}
void GameConnection::respawnSelectedEntities() {
if (!connect())
return;
std::set<std::string> selectedEntityNames;
GlobalSelectionSystem().foreachSelected([&selectedEntityNames](const scene::INodePtr &node) -> void {
//Node_isEntity
if (Entity* entity = Node_getEntity(node)) {
const std::string &name = entity->getKeyValue("name");
if (!name.empty()) {
selectedEntityNames.insert(name);
}
}
});
std::string command;
for (const std::string &name : selectedEntityNames)
command += "respawn " + name + "\n";
std::string text = composeConExecRequest(command);
executeRequest(text);
}
void GameConnection::reloadMap() {
if (!connect())
return;
std::string text = composeConExecRequest("reloadMap nocheck");
executeRequest(text);
}
void GameConnection::onMapEvent(IMap::MapEvent ev) {
if (ev == IMap::MapSaved && _autoReloadMap) {
reloadMap();
_mapObserver.clear();
}
if (ev == IMap::MapLoading || ev == IMap::MapUnloading) {
disconnect();
}
}
void GameConnection::setAutoReloadMapEnabled(bool enable) {
_autoReloadMap = enable;
}
void GameConnection::setUpdateMapLevel(bool on, bool always) {
if (on && !_mapObserver.isEnabled()) {
//save map to file, and reload from file, to ensure DR and TDM are in sync
GlobalCommandSystem().executeCommand("SaveMap");
reloadMap();
}
_mapObserver.setEnabled(on);
_updateMapAlways = always;
}
void GameConnection::doUpdateMap() {
if (!connect())
return;
std::string diff = GlobalMap().saveMapDiff(_mapObserver.getChanges());
if (diff.empty()) {
return; //TODO: fail
}
std::string response = executeRequest(actionPreamble("reloadmap-diff") + "content:\n" + diff);
if (response.find("HotReload: SUCCESS") != std::string::npos)
_mapObserver.clear();
}
}