Skip to content

Commit

Permalink
Cleaning the code.
Browse files Browse the repository at this point in the history
1) Same style of commenting.
2) Reorder methods.
3) Removed unnecessary commands, bool return values.
  • Loading branch information
stgatilov committed Aug 6, 2021
1 parent de42044 commit 8782a96
Show file tree
Hide file tree
Showing 4 changed files with 141 additions and 169 deletions.
6 changes: 3 additions & 3 deletions plugins/dm.gameconnection/AutomationEngine.cpp
Expand Up @@ -90,7 +90,7 @@ int AutomationEngine::generateNewSequenceNumber()
return ++_seqno;
}

AutomationEngine::Request* AutomationEngine::sendRequest(const std::string& request, int tag) {
AutomationEngine::Request* AutomationEngine::sendRequest(int tag, const std::string& request) {
assert(tag < 31);
if (!_connection)
throw DisconnectException();
Expand Down Expand Up @@ -255,7 +255,7 @@ void AutomationEngine::waitForTags(int tagMask)

std::string AutomationEngine::executeRequestBlocking(int tag, const std::string& request)
{
Request* req = sendRequest(request, tag);
Request* req = sendRequest(tag, request);
int seqno = req->_seqno;

std::string response;
Expand All @@ -272,7 +272,7 @@ std::string AutomationEngine::executeRequestBlocking(int tag, const std::string&

int AutomationEngine::executeRequestAsync(int tag, const std::string& request, const std::function<void(int)>& callback)
{
Request* req = sendRequest(request, tag);
Request* req = sendRequest(tag, request);
req->_callback = callback;
return req->_seqno;
}
Expand Down
61 changes: 28 additions & 33 deletions plugins/dm.gameconnection/AutomationEngine.h
Expand Up @@ -17,11 +17,11 @@ class DisconnectException : public std::runtime_error {
DisconnectException() : std::runtime_error("Game connection lost") {}
};

//bitmask with all tag bits set
// Bitmask with all tag bits set.
static const int TAGMASK_ALL = -1;

// Putting this to wait-list of multistep procedure
// results in it waking up on next think (timer tick).
// results in waking up on next think (suitable for polling).
static const int SEQNO_WAIT_POLL = -10000;

struct MultistepProcReturn {
Expand All @@ -35,7 +35,7 @@ struct MultistepProcReturn {


/**
* stgatilov: This is engine for connection to TheDarkMod's automation via socket
* stgatilov: The engine for connection to TheDarkMod's automation via socket.
*/
class AutomationEngine
{
Expand All @@ -47,7 +47,6 @@ class AutomationEngine
// Connect to TDM instance if not connected yet.
// Returns false if failed to connect, true on success.
bool connect();

// Disconnect from TDM instance if connected.
// If force = false, then it waits until all pending requests are finished.
// If force = true, then all pending requests are dropped, no blocking for sure.
Expand All @@ -59,40 +58,44 @@ class AutomationEngine
bool hasLostConnection() const;


//check how socket is doing, accept responses, call callbacks
//this should be done regularly: in fact, timer calls it often
// Check how socket is doing, accept responses, call callbacks.
// This should be done regularly, e.g. in a timer.
void think();

// Return true iff any of the given requests of multistep procedures are not finished yet.
bool areInProgress(const std::vector<int>& reqSeqnos, const std::vector<int>& procIds);
// Wait for specified requests and multistep procedures to finish.
// Throws DisconnectException if it cannot be done due to lost connection.
void wait(const std::vector<int>& reqSeqnos, const std::vector<int>& procIds);

// Return true iff any of the given requests of multistep procedures are not finished yet.
bool areTagsInProgress(int tagMask = TAGMASK_ALL);
// Wait for all active requests and multistep procedures matching the given mask to finish.
// Throws DisconnectException if it cannot be done due to lost connection.
void waitForTags(int tagMask = TAGMASK_ALL);


// Send given request synchronously, i.e. wait until its completition.
// Returns response content.
// Throws DisconnectException if connection is missing or lost during execution.
std::string executeRequestBlocking(int tag, const std::string& request);

// Send request !a!synchronously, i.e. send it to socket and return immediately.
// Returns seqno of the request: it can be put to wait-list of multistep procedure or used for polling.
// Returns seqno of the request: it can be put to wait-list of multistep procedure or used in queries.
// When request is finished, optional callback will be executed (from "think" method).
// Note that if connection is lost already of while request is being executed, NO special callback is called.
// May throw DisconnectException is connection is missing (but never throws if isAlive() is true).
// Note that if connection is lost, NO special callback is called.
// May throw DisconnectException if connection is missing (but never throws if isAlive() is true before call).
int executeRequestAsync(int tag, const std::string& request, const std::function<void(int)>& callback = {});

// Execute given multistep procedure, starting on the next think.
// Returns ID of procedure for future queries.
// Returns ID of procedure for queries.
// Multistep procedure is like a DFA of "steps", each step is executed till start to end.
// When step is over, you can specify async requests to wait for, and which step to resume when they are finished.
int executeMultistepProc(int tag, const std::function<MultistepProcReturn(int)>& function, int startStep = 0);


// Return true iff any of the given requests or multistep procedures are not finished yet.
bool areInProgress(const std::vector<int>& reqSeqnos, const std::vector<int>& procIds);
// Wait for specified requests and multistep procedures to finish.
// Throws DisconnectException if it cannot be done due to lost connection.
void wait(const std::vector<int>& reqSeqnos, const std::vector<int>& procIds);

// Return true iff any request or multistep procedure matching the given mask is not finished yet.
// Note: tagMask is a bitmask, so pass (1<<tag) in order to wait for one tag only.
bool areTagsInProgress(int tagMask = TAGMASK_ALL);
// Wait for all active requests and multistep procedures matching the given mask to finish.
// Throws DisconnectException if it cannot be done due to lost connection.
void waitForTags(int tagMask = TAGMASK_ALL);


// Returns response for just finished request with given seqno.
// Can be called inside:
// * executeRequestAsync callback
Expand All @@ -101,7 +104,7 @@ class AutomationEngine

private:
// Connection to TDM game (i.e. the socket with custom message framing).
// Tt can be "dead" in two ways:
// It can be "dead" in two ways:
// _connection is NULL --- no connection
// *_connection is dead --- just lost connection
std::unique_ptr<MessageTcp> _connection;
Expand All @@ -114,8 +117,8 @@ class AutomationEngine

struct Request {
int _seqno = 0;
bool _finished = false;
int _tag = 0;
bool _finished = false;
std::string _request;
std::string _response;

Expand All @@ -132,22 +135,14 @@ class AutomationEngine
};
std::vector<MultistepProcedure> _multistepProcs;

// Every request should get unique seqno, otherwise we won't be able to distinguish their responses.
int generateNewSequenceNumber();
Request* sendRequest(int tag, const std::string& request);

Request* findRequest(int seqno) const;
MultistepProcedure* findMultistepProc(int id) const;

bool isMultistepProcStillWaiting(const MultistepProcedure& proc, bool waitForPoll) const;


// Prepend seqno to specified request and send it to game.
// Returns pointer to the created request.
Request* sendRequest(const std::string& request, int tag);

//execute next step of the current multistep procedure
void resumeMultistepProcedure(int id);

};

}
59 changes: 22 additions & 37 deletions plugins/dm.gameconnection/GameConnection.cpp
Expand Up @@ -531,20 +531,20 @@ void GameConnection::enableGhostMode()
executeSetTogglableFlag("notarget", true, "OFF");
}

bool GameConnection::setCameraSyncEnabled(bool enable)
void GameConnection::setCameraSyncEnabled(bool enable)
{
try {
if (!enable) {
_cameraChangedSignal.disconnect();
}
if (enable) {
enableGhostMode();

_cameraChangedSignal.disconnect();
_cameraChangedSignal = GlobalCameraManager().signal_cameraChanged().connect(
sigc::mem_fun(this, &GameConnection::updateCamera)
);

enableGhostMode();

//sync camera location right now
updateCamera();
_engine->waitForTags(1 << TAG_CAMERA);
Expand All @@ -554,9 +554,7 @@ bool GameConnection::setCameraSyncEnabled(bool enable)
}
catch (const DisconnectException&) {
//disconnected: will be handled during next think
return false;
}
return true;
}

bool GameConnection::isCameraSyncEnabled() const
Expand Down Expand Up @@ -664,14 +662,13 @@ void GameConnection::onMapEvent(IMap::MapEvent ev)
}
}

bool GameConnection::setAutoReloadMapEnabled(bool enable)
void GameConnection::setAutoReloadMapEnabled(bool enable)
{
if (enable && !_engine->isAlive())
return false;
return;

_autoReloadMap = enable;
signal_StatusChanged.emit(0);
return true;
}

bool GameConnection::isAutoReloadMapEnabled() const
Expand Down Expand Up @@ -699,18 +696,17 @@ void GameConnection::setUpdateMapObserverEnabled(bool enable)
signal_StatusChanged.emit(0);
}

bool GameConnection::setAlwaysUpdateMapEnabled(bool enable)
void GameConnection::setAlwaysUpdateMapEnabled(bool enable)
{
if (enable) {
if (!_engine->isAlive())
return false;
return;
if (enable)
setUpdateMapObserverEnabled(true);
}

_updateMapAlways = enable;
signal_StatusChanged.emit(0);
return true;
}

bool GameConnection::isAlwaysUpdateMapEnabled() const
Expand Down Expand Up @@ -809,36 +805,30 @@ void GameConnection::initialiseModule(const IApplicationContext& ctx)
// Construct toggles
_camSyncToggle = GlobalEventManager().addAdvancedToggle(
"GameConnectionToggleCameraSync",
[this](bool v) { return setCameraSyncEnabled(v); }
);
GlobalEventManager().addAdvancedToggle(
"GameConnectionToggleAutoMapReload",
[this](bool v) { return setAutoReloadMapEnabled(v); }
);
GlobalEventManager().addAdvancedToggle(
"GameConnectionToggleHotReload",
[this](bool v) { return setAlwaysUpdateMapEnabled(v); }
[this](bool v) {
bool oldEnabled = isCameraSyncEnabled();
setCameraSyncEnabled(v);
return isCameraSyncEnabled() != oldEnabled;
}
);

// Add one-shot commands and associated toolbar buttons
GlobalCommandSystem().addCommand("GameConnectionBackSyncCamera",
[this](const cmd::ArgumentList&) { backSyncCamera(); });
GlobalCommandSystem().addCommand(
"GameConnectionBackSyncCamera",
[this](const cmd::ArgumentList&) {
backSyncCamera();
}
);
_camSyncBackButton = GlobalEventManager().addCommand(
"GameConnectionBackSyncCamera", "GameConnectionBackSyncCamera", false
);
GlobalCommandSystem().addCommand("GameConnectionReloadMap",
[this](const cmd::ArgumentList&) { reloadMap(); });
GlobalCommandSystem().addCommand("GameConnectionUpdateMap",
[this](const cmd::ArgumentList&) { doUpdateMap(); });
GlobalCommandSystem().addCommand("GameConnectionPauseGame",
[this](const cmd::ArgumentList&) { togglePauseGame(); });
GlobalCommandSystem().addCommand("GameConnectionRespawnSelected",
[this](const cmd::ArgumentList&) { respawnSelectedEntities(); });
// Toolbar button(s)
GlobalMainFrame().signal_MainFrameConstructed().connect(
sigc::mem_fun(this, &GameConnection::addToolbarItems)
);

// Add menu items
ui::menu::IMenuManager& mm = GlobalMenuManager();
mm.insert("main/help", "connection", ui::menu::ItemType::Folder, _("Connection"), "", "");

// Add menu button which shows up the dialog
GlobalCommandSystem().addCommand("GameConnectionDialogToggle", gameconn::GameConnectionDialog::toggleDialog);
// Add the menu item
Expand All @@ -850,11 +840,6 @@ void GameConnection::initialiseModule(const IApplicationContext& ctx)
"stimresponse.png", // icon
"GameConnectionDialogToggle" // event name
);

// Toolbar button(s)
GlobalMainFrame().signal_MainFrameConstructed().connect(
sigc::mem_fun(this, &GameConnection::addToolbarItems)
);
}

void GameConnection::shutdownModule()
Expand Down

0 comments on commit 8782a96

Please sign in to comment.