diff --git a/engine/server/application/LogServer/src/shared/LoggingServerApi.cpp b/engine/server/application/LogServer/src/shared/LoggingServerApi.cpp index a6b9920f..c2429a76 100755 --- a/engine/server/application/LogServer/src/shared/LoggingServerApi.cpp +++ b/engine/server/application/LogServer/src/shared/LoggingServerApi.cpp @@ -9,8 +9,6 @@ #include "LoggingServerApi.h" - - LoggingServerApi::LoggingServerApi(LoggingServerHandler *handler, int queueSize) { mHandler = handler; @@ -18,6 +16,7 @@ LoggingServerApi::LoggingServerApi(LoggingServerHandler *handler, int queueSize) mQueue = new QueueEntry[mQueueSize]; mQueuePosition = 0; mQueueCount = 0; + mLoginSent = 0; mAuthenticated = false; mLoginName[0] = 0; @@ -117,22 +116,22 @@ void LoggingServerApi::Flush(int timeout) UdpMisc::Sleep(20); } -LoggingServerApi::Status LoggingServerApi::GetStatus() const +LoggingServerApi::Status LoggingServerApi::GetStatus() const { if (mConnection != nullptr) { switch (mConnection->GetStatus()) { - case UdpConnection::cStatusConnected: - if (mAuthenticated) - return(cStatusConnected); - else - return(cStatusAuthenticating); - break; - case UdpConnection::cStatusNegotiating: - return(cStatusNegotiating); - default: - break; + case UdpConnection::cStatusConnected: + if (mAuthenticated) + return(cStatusConnected); + else + return(cStatusAuthenticating); + break; + case UdpConnection::cStatusNegotiating: + return(cStatusNegotiating); + default: + break; } } return(cStatusDisconnected); @@ -140,57 +139,57 @@ LoggingServerApi::Status LoggingServerApi::GetStatus() const void LoggingServerApi::OnRoutePacket(UdpConnection *, const uchar *data, int) { - switch(data[0]) + switch (data[0]) { - case cS2CPacketLoginConfirm: + case cS2CPacketLoginConfirm: + { + mAuthenticated = data[1] ? true : false; + if (mAuthenticated) { - mAuthenticated = data[1] ? true : false; - if (mAuthenticated) - { - // flush the queue on authentication. This sends not only any data that was queued before connecting - // but also any data that was sent in the last 3 minutes, just to ensure that it didn't get lost on the - // server side of things - FlushQueue(); - } + // flush the queue on authentication. This sends not only any data that was queued before connecting + // but also any data that was sent in the last 3 minutes, just to ensure that it didn't get lost on the + // server side of things + FlushQueue(); + } - if (mHandler != nullptr) - mHandler->LshOnLoginConfirm(mAuthenticated); - break; - } - case cS2CPacketMonitor: - { - char *ptr = (char *)(data + 1); - int sessionId = UdpMisc::GetValue32(ptr); - ptr += 4; - int sequenceNumber = UdpMisc::GetValue32(ptr); - ptr += 4; - int typeCode = UdpMisc::GetValue32(ptr); - ptr += 4; - char *name = ptr; - ptr += strlen(ptr) + 1; - char *filename = ptr; - ptr += strlen(ptr) + 1; - char *message = ptr; - if (mHandler != nullptr) - mHandler->LshOnMonitor(sessionId, sequenceNumber, name, filename, typeCode, message); - break; - } - case cS2CPacketFileList: - { - if (mHandler != nullptr) - mHandler->LshOnFileList((char *)(data + 1)); - break; - } - default: - break; + if (mHandler != nullptr) + mHandler->LshOnLoginConfirm(mAuthenticated); + break; + } + case cS2CPacketMonitor: + { + char *ptr = (char *)(data + 1); + int sessionId = UdpMisc::GetValue32(ptr); + ptr += 4; + int sequenceNumber = UdpMisc::GetValue32(ptr); + ptr += 4; + int typeCode = UdpMisc::GetValue32(ptr); + ptr += 4; + char *name = ptr; + ptr += strlen(ptr) + 1; + char *filename = ptr; + ptr += strlen(ptr) + 1; + char *message = ptr; + if (mHandler != nullptr) + mHandler->LshOnMonitor(sessionId, sequenceNumber, name, filename, typeCode, message); + break; + } + case cS2CPacketFileList: + { + if (mHandler != nullptr) + mHandler->LshOnFileList((char *)(data + 1)); + break; + } + default: + break; } } void LoggingServerApi::OnTerminated(UdpConnection *con) { - if(mHandler != nullptr) + if (mHandler != nullptr) { - mHandler->LshOnTerminated( con->GetDisconnectReason() ); + mHandler->LshOnTerminated(con->GetDisconnectReason()); } } @@ -202,7 +201,7 @@ void LoggingServerApi::GiveTime() { mLoginSent = true; - // send login packet + // send login packet char buf[1024]; char *ptr = buf; *ptr++ = cC2SPacketLogin; @@ -221,8 +220,8 @@ void LoggingServerApi::GiveTime() { int spot = mQueuePosition % mQueueSize; - // if entry was actually sent and it has been sitting in the queue long enough to be deleted - if (mQueue[spot].sentTime != 0 && UdpMisc::ClockElapsed(mQueue[spot].sentTime) > cSafetyQueueTime) + // if entry was actually sent and it has been sitting in the queue long enough to be deleted + if (mQueue[spot].sentTime != 0 && UdpMisc::ClockElapsed(mQueue[spot].sentTime) > cSafetyQueueTime) { mQueue[spot].packet->Release(); mQueue[spot].packet = nullptr; @@ -259,7 +258,7 @@ void LoggingServerApi::StopTransaction() void LoggingServerApi::PacketSend(LogicalPacket *lp) { - // make room in queue + // make room in queue if (mQueueCount == mQueueSize) { int spot = mQueuePosition % mQueueSize; @@ -269,14 +268,14 @@ void LoggingServerApi::PacketSend(LogicalPacket *lp) mQueueCount--; } - // queue it + // queue it int spot = (mQueuePosition + mQueueCount) % mQueueSize; lp->AddRef(); mQueue[spot].packet = lp; mQueue[spot].sentTime = 0; mQueueCount++; - // if possible, send it + // if possible, send it if (GetStatus() == cStatusConnected) { mQueue[spot].sentTime = UdpMisc::Clock(); @@ -284,7 +283,6 @@ void LoggingServerApi::PacketSend(LogicalPacket *lp) } } - void LoggingServerApi::Log16(const char *filename, int typeCode, const unsigned short *ucs2String) { char buffer[32768]; @@ -376,7 +374,7 @@ void LoggingServerApi::LogPacket(char *data, int len) { if (mTransaction != nullptr) { - // add it to the transaction + // add it to the transaction mTransaction->AddPacket(data, len); } else @@ -437,12 +435,12 @@ void LoggingServerApi::RequestFileList() void LoggingServerApi::GetStatistics(LoggingServerApiStatistics *stats) { - memset( stats, 0, sizeof( *stats) ); + memset(stats, 0, sizeof(*stats)); UdpConnectionStatistics udpConnectionStats; - memset( &udpConnectionStats, 0, sizeof( udpConnectionStats ) ); - if( mConnection != nullptr ) + memset(&udpConnectionStats, 0, sizeof(udpConnectionStats)); + if (mConnection != nullptr) { - mConnection->GetStats( &udpConnectionStats ); + mConnection->GetStats(&udpConnectionStats); stats->applicationPacketsReceived = udpConnectionStats.applicationPacketsReceived; stats->applicationPacketsSent = udpConnectionStats.applicationPacketsSent; stats->totalBytesReceived = udpConnectionStats.totalBytesReceived; @@ -454,25 +452,25 @@ void LoggingServerApi::GetStatistics(LoggingServerApiStatistics *stats) } UdpManagerStatistics managerStats; - if( mUdpManager != nullptr ) + if (mUdpManager != nullptr) { - mUdpManager->GetStats( &managerStats ); + mUdpManager->GetStats(&managerStats); udp_int64 iterations = managerStats.iterations; int elapseTime = managerStats.elapsedTime; - if( elapseTime != 0 ) + if (elapseTime != 0) { - stats->iterationsPerSecond = (double)((iterations * 1000 )/(double)elapseTime); + stats->iterationsPerSecond = (double)((iterations * 1000) / (double)elapseTime); } mUdpManager->ResetStats(); } } -void LoggingServerHandler::LshOnLoginConfirm(bool ) +void LoggingServerHandler::LshOnLoginConfirm(bool) { } -void LoggingServerHandler::LshOnMonitor(int , int , const char * const, const char * const, int , const char * const) +void LoggingServerHandler::LshOnMonitor(int, int, const char * const, const char * const, int, const char * const) { } @@ -482,4 +480,4 @@ void LoggingServerHandler::LshOnFileList(const char * const) void LoggingServerHandler::LshOnTerminated(UdpConnection::DisconnectReason) { -} +} \ No newline at end of file diff --git a/engine/server/application/LogServer/src/shared/LoggingServerApiObserver.cpp b/engine/server/application/LogServer/src/shared/LoggingServerApiObserver.cpp index 209b2b0d..bd8c4753 100755 --- a/engine/server/application/LogServer/src/shared/LoggingServerApiObserver.cpp +++ b/engine/server/application/LogServer/src/shared/LoggingServerApiObserver.cpp @@ -1,5 +1,5 @@ // LoggingServerApiObserver.cpp -// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. // Author: Justin Randall //----------------------------------------------------------------------- @@ -15,7 +15,7 @@ //----------------------------------------------------------------------- LoggingServerApiObserver::LoggingServerApiObserver() : -m_loggingServerApi(new LoggingServerApi(0, ConfigLogServer::getLoggingServerApiQueueSize())) + m_loggingServerApi(new LoggingServerApi(0, ConfigLogServer::getLoggingServerApiQueueSize())) { m_loggingServerApi->Connect(ConfigLogServer::getLoggingServerApiAddress(), LoggingServerApi::cDefaultPort, ConfigLogServer::getLoggingServerApiLoginName(), ConfigLogServer::getLoggingServerApiPassword(), ConfigLogServer::getLoggingServerApiDefaultDirectory()); } @@ -47,30 +47,30 @@ LogObserver * LoggingServerApiObserver::create(const std::string &) void LoggingServerApiObserver::log(const LogMessage & msg) { std::string fileName = "misc.txt"; - + std::string msgText; - if(! msg.getText().empty()) + if (!msg.getText().empty()) { time_t now; tm t; - IGNORE_RETURN( time(&now) ); - IGNORE_RETURN( gmtime_r(&now, &t) ); - char dirBuf[128] = {"\0"}; + IGNORE_RETURN(time(&now)); + IGNORE_RETURN(gmtime_r(&now, &t)); + char dirBuf[128] = { "\0" }; snprintf(dirBuf, sizeof(dirBuf), "%d/%d/%d/", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday); fileName = ConfigLogServer::getClusterName(); fileName += "/"; fileName += dirBuf; - + std::string splittext = msg.getText(); - if(splittext.find(":") != splittext.npos) + if (splittext.find(":") != splittext.npos) { fileName += splittext.substr(0, splittext.find(":")) + ".txt"; } msgText = splittext.substr(splittext.find(":") + 1); - + // If there is ANY Unicode, send the whole log as Unicode. If there is ONLY non-Unicode, then send the log non-Unicode. if (!msg.getUnicodeAttach().empty()) @@ -106,7 +106,7 @@ void LoggingServerApiObserver::flush() void LoggingServerApiObserver::update() { - if(m_loggingServerApi->GetStatus() == LoggingServerApi::cStatusDisconnected) + if (m_loggingServerApi->GetStatus() == LoggingServerApi::cStatusDisconnected) { m_loggingServerApi->Connect(ConfigLogServer::getLoggingServerApiAddress(), LoggingServerApi::cDefaultPort, ConfigLogServer::getLoggingServerApiLoginName(), ConfigLogServer::getLoggingServerApiPassword(), ConfigLogServer::getLoggingServerApiDefaultDirectory()); } @@ -114,5 +114,4 @@ void LoggingServerApiObserver::update() m_loggingServerApi->GiveTime(); } -//----------------------------------------------------------------------- - +//----------------------------------------------------------------------- \ No newline at end of file diff --git a/engine/server/application/LoginServer/src/shared/CSToolConnection.cpp b/engine/server/application/LoginServer/src/shared/CSToolConnection.cpp index 7e10c623..9163a15a 100755 --- a/engine/server/application/LoginServer/src/shared/CSToolConnection.cpp +++ b/engine/server/application/LoginServer/src/shared/CSToolConnection.cpp @@ -14,9 +14,9 @@ #include "sharedLog/Log.h" #if defined(WIN32) - #include +#include #else // for non-windows platforms (linux) - #include +#include #endif namespace CSToolConnectionNamespace @@ -28,9 +28,9 @@ uint32 CSToolConnection::m_curToolID = 0; // statics -CSToolConnection * CSToolConnection::getCSToolConnectionByToolId( uint32 id ) +CSToolConnection * CSToolConnection::getCSToolConnectionByToolId(uint32 id) { - std::map< uint32, CSToolConnection * >::iterator it = CSToolConnectionNamespace::toolsByID.find( id ); + std::map< uint32, CSToolConnection * >::iterator it = CSToolConnectionNamespace::toolsByID.find(id); return it == CSToolConnectionNamespace::toolsByID.end() ? 0 : it->second; } @@ -40,9 +40,9 @@ void CSToolConnection::validateCSTool(uint32 toolId, apiResult result, const api CSToolConnection * p_connection = getCSToolConnectionByToolId(toolId); if (!p_connection) return; // no connection, they must have bailed. - + // check the result - if(result == RESULT_SUCCESS) + if (result == RESULT_SUCCESS) { // if we're valid, set to logged in p_connection->m_bLoggedIn = true; @@ -50,24 +50,23 @@ void CSToolConnection::validateCSTool(uint32 toolId, apiResult result, const api { p_connection->m_bSecure = true; } - + // if we have a nullptr session type, then we aren't connected to the // Session Server and are in debug mode. // // if we *do* have a good session, then check the admin table for access level. int accessLevel = 100; - + bool sessionNull = (session.GetType() == SESSION_TYPE_NULL); bool isAdmin = AdminAccountManager::isAdminAccount(p_connection->m_sUserName, accessLevel); bool needSecure = ConfigLoginServer::getRequireSecureLoginForCsTool(); bool isInternal = AdminAccountManager::isInternalIp(p_connection->getRemoteAddress()); - DEBUG_REPORT_LOG( true, ("CS Tool login for %s, admin=%s, access=%d, internal=%s\n", - p_connection->m_sUserName.c_str(), - isAdmin ? "true" : "false", - accessLevel, - isInternal ? "true" : "false")); + DEBUG_REPORT_LOG(true, ("CS Tool login for %s, admin=%s, access=%d, internal=%s\n", + p_connection->m_sUserName.c_str(), + isAdmin ? "true" : "false", + accessLevel, + isInternal ? "true" : "false")); - bool canLogin = isInternal; // we always have to be internal. if (sessionNull) { @@ -78,10 +77,10 @@ void CSToolConnection::validateCSTool(uint32 toolId, apiResult result, const api else { // if we don't have a session, we need to be on the admin table - if(isAdmin) + if (isAdmin) { // allow login if we either don't need to be secure, or if we are. - if((!needSecure) || p_connection->m_bSecure) + if ((!needSecure) || p_connection->m_bSecure) { canLogin = canLogin && true; } @@ -94,58 +93,57 @@ void CSToolConnection::validateCSTool(uint32 toolId, apiResult result, const api { canLogin = false; } - } - - if(canLogin) + } + + if (canLogin) { // and inform std::string response = "Logged in successfully."; response += "\r\n"; p_connection->sendToTool(response); - + p_connection->m_ui32PrivilegeLevel = (uint32)accessLevel; } else { p_connection->sendToTool("Invalid name/password.\r\n"); } - } - // otherwise, give the appropriate response - else if( result == RESULT_INVALID_NAME_OR_PASSWORD ) + // otherwise, give the appropriate response + else if (result == RESULT_INVALID_NAME_OR_PASSWORD) { p_connection->sendToTool("Invalid name/password.\r\n"); } else { - DEBUG_REPORT_LOG(true,("Could not log in CS Tool for user %s, reason %d\n", p_connection->m_sUserName.c_str(), result)); + DEBUG_REPORT_LOG(true, ("Could not log in CS Tool for user %s, reason %d\n", p_connection->m_sUserName.c_str(), result)); p_connection->sendToTool("Invalid name/password.\r\n"); } - } // members -CSToolConnection::CSToolConnection( UdpConnectionMT * pUdpConn, TcpClient * pTcpConn ) : - Connection( pUdpConn, pTcpConn ), - m_ui32StationID( 0 ), - m_bSecure( false ), - m_bLoggedIn( false ), - m_ui32PrivilegeLevel( 0 ) +CSToolConnection::CSToolConnection(UdpConnectionMT * pUdpConn, TcpClient * pTcpConn) : + Connection(pUdpConn, pTcpConn), + m_ui32StationID(0), + m_bSecure(false), + m_bLoggedIn(false), + m_ui32PrivilegeLevel(0), + m_toolID(0) { - if( pTcpConn ) // it'd better be! - setRawTCP( true ); + if (pTcpConn) // it'd better be! + setRawTCP(true); } CSToolConnection::~CSToolConnection() { } -void CSToolConnection::onReceive( const Archive::ByteStream & message ) +void CSToolConnection::onReceive(const Archive::ByteStream & message) { // for testing purposes, just echo back to the user. - + // add to buffer std::string input; const unsigned char * uc = message.getBuffer(); @@ -156,242 +154,234 @@ void CSToolConnection::onReceive( const Archive::ByteStream & message ) ++uc; } m_sInputBuffer += input; - - + // while we've got an EOL signifier std::string::size_type pos; - while( ( pos = m_sInputBuffer.find( '\r' ) ) != std::string::npos ) + while ((pos = m_sInputBuffer.find('\r')) != std::string::npos) { // rebuild message buffer properly. - std::string command = m_sInputBuffer.substr( 0, pos ); + std::string command = m_sInputBuffer.substr(0, pos); // should dispatch here, for now we're echoing back for debug. - + //command = command + "\r\n"; //sendToTool( command ); - this->parse( command ); + this->parse(command); // then we have additional data. Otherwise, we don't. - if( m_sInputBuffer.size() >= pos + 2 ) + if (m_sInputBuffer.size() >= pos + 2) { - m_sInputBuffer = m_sInputBuffer.substr( pos + 2, m_sInputBuffer.length() - ( pos + 2 ) ); + m_sInputBuffer = m_sInputBuffer.substr(pos + 2, m_sInputBuffer.length() - (pos + 2)); } else { m_sInputBuffer.clear(); } - } } -void CSToolConnection::parse( const std::string command ) +void CSToolConnection::parse(const std::string command) { // grab the first word of the command. std::string first; std::string args; std::string::size_type pos; - if( ( pos = command.find( ' ' ) ) == std::string::npos ) + if ((pos = command.find(' ')) == std::string::npos) { first = command; } else { - first = command.substr( 0, pos ); - args = command.substr( pos + 1, command.size() - ( pos + 1 ) ); + first = command.substr(0, pos); + args = command.substr(pos + 1, command.size() - (pos + 1)); } // test for empty commands. - if( first.length() == 0 || first[ 0 ] == ' ' ) + if (first.length() == 0 || first[0] == ' ') { return; } - + std::string response = "ls:"; - - - if( first == "clusters" ) + + if (first == "clusters") { response += "Active clusters:\r\n"; - std::map< std::string, uint32 > data; - LoginServer::getInstance().getAllClusterNamesAndIDs( data ); - for( std::map< std::string, uint32 >::iterator it = data.begin(); - it != data.end(); - ++it ) + std::map< std::string, uint32 > data; + LoginServer::getInstance().getAllClusterNamesAndIDs(data); + for (std::map< std::string, uint32 >::iterator it = data.begin(); + it != data.end(); + ++it) { response += it->first + "\r\n"; } - sendToTool( response ); + sendToTool(response); } - else if ( first == "select" ) + else if (first == "select") { // see if we're adding, removing, or exclusive-adding. - if( args[ 0 ] == '+' ) + if (args[0] == '+') { - if( args.size() > 1 ) + if (args.size() > 1) { - if( args[ 1 ] == '+' ) + if (args[1] == '+') { m_selectedClusters.clear(); - sendToTool( "ls:deselected all servers\r\n" ); + sendToTool("ls:deselected all servers\r\n"); } - pos = args.find_first_not_of( "+" ); - if( pos == std::string::npos ) + pos = args.find_first_not_of("+"); + if (pos == std::string::npos) { } else { - std::string cluster = args.substr( pos, args.size() - pos ); - response += selectCluster( cluster ); - sendToTool( response ); + std::string cluster = args.substr(pos, args.size() - pos); + response += selectCluster(cluster); + sendToTool(response); } } } - else if( args[ 0 ] == '-' ) + else if (args[0] == '-') { - if( args.size() > 1 ) + if (args.size() > 1) { - std::string cluster = args.substr( 1, args.size() - 1 ); - if( m_selectedClusters.find( cluster ) != m_selectedClusters.end() ) + std::string cluster = args.substr(1, args.size() - 1); + if (m_selectedClusters.find(cluster) != m_selectedClusters.end()) { - response += deselectCluster( cluster ); - sendToTool( response ); + response += deselectCluster(cluster); + sendToTool(response); } } } else { - sendToTool( "Error! Bad select format!\r\n" ); + sendToTool("Error! Bad select format!\r\n"); } } - else if ( first == "showselected" ) + else if (first == "showselected") { response += "Currently selected clusters:\r\n"; - for( std::set< std::string >::iterator it = m_selectedClusters.begin(); - it != m_selectedClusters.end(); - ++it ) + for (std::set< std::string >::iterator it = m_selectedClusters.begin(); + it != m_selectedClusters.end(); + ++it) { response += *it + "\r\n"; } - sendToTool( response ); - + sendToTool(response); } - else if( first == "login" ) + else if (first == "login") { // assume name/pw do not have spaces. std::string name; std::string pw; - + // split apart - unsigned pos = args.find( " " ); - if( pos != std::string::npos ) + unsigned pos = args.find(" "); + if (pos != std::string::npos) { - name = args.substr( 0, pos ); - pw = args.substr( pos + 1, args.length() - pos - 1 ); + name = args.substr(0, pos); + pw = args.substr(pos + 1, args.length() - pos - 1); m_sUserName = name; - if( !LoginServer::getInstance().getSessionApiClient() ) + if (!LoginServer::getInstance().getSessionApiClient()) { apiSession session; - validateCSTool( m_toolID, RESULT_SUCCESS, session ); + validateCSTool(m_toolID, RESULT_SUCCESS, session); return; } LoginServer::getInstance().getSessionApiClient()-> - SessionLogin(name.c_str(), - pw.c_str(), + SessionLogin(name.c_str(), + pw.c_str(), SESSION_TYPE_STARWARS, - inet_addr( getRemoteAddress().c_str() ), + inet_addr(getRemoteAddress().c_str()), 0, - _defaultNamespace, - ( void * )m_toolID ); + _defaultNamespace, + (void *)m_toolID); } - + // pass to session. } // default command handler. else { - if( m_bLoggedIn ) + if (m_bLoggedIn) { - sendToClusters( first, command ); + sendToClusters(first, command); } else { - sendToTool( "Not logged in.\r\n" ); + sendToTool("Not logged in.\r\n"); } } - } -void CSToolConnection::sendToClusters( const std::string & sCommand, const std::string & sCommandLine ) +void CSToolConnection::sendToClusters(const std::string & sCommand, const std::string & sCommandLine) { // build the message - CSToolRequest msg( m_ui32StationID, m_ui32PrivilegeLevel, sCommandLine, sCommand, m_toolID, m_sUserName ); - + CSToolRequest msg(m_ui32StationID, m_ui32PrivilegeLevel, sCommandLine, sCommand, m_toolID, m_sUserName); + // send to all currently selected clusters. - for( std::set< std::string >::iterator it = m_selectedClusters.begin(); - it != m_selectedClusters.end(); - ++it ) + for (std::set< std::string >::iterator it = m_selectedClusters.begin(); + it != m_selectedClusters.end(); + ++it) { - LoginServer::getInstance().sendToCluster( LoginServer::getInstance().getClusterIDByName( *it ), msg ); + LoginServer::getInstance().sendToCluster(LoginServer::getInstance().getClusterIDByName(*it), msg); } } -std::string CSToolConnection::selectCluster( const std::string & cluster ) +std::string CSToolConnection::selectCluster(const std::string & cluster) { std::string response; // see if we have a valid cluster. - uint32 cluster_id = LoginServer::getInstance().getClusterIDByName( cluster ); - if( cluster_id == 0 ) + uint32 cluster_id = LoginServer::getInstance().getClusterIDByName(cluster); + if (cluster_id == 0) { response += "Cluster " + cluster + " does not exist.\r\n"; } else { - m_selectedClusters.insert( cluster ); + m_selectedClusters.insert(cluster); response += "Cluster " + cluster + " added to active list\r\n"; } return response; } -std::string CSToolConnection::deselectCluster( const std::string & cluster ) +std::string CSToolConnection::deselectCluster(const std::string & cluster) { std::string response; - + // see if we are currently talking to that cluster. - std::set< std::string >::iterator it = m_selectedClusters.find( cluster ); - if( it == m_selectedClusters.end() ) + std::set< std::string >::iterator it = m_selectedClusters.find(cluster); + if (it == m_selectedClusters.end()) { response += "Cluster " + cluster + " is not currently selected.\r\n"; } else { - m_selectedClusters.erase( it ); + m_selectedClusters.erase(it); response += "Cluster " + cluster + " removed from active list.\r\n"; } return response; - } -void CSToolConnection::sendToTool( const std::string & message ) +void CSToolConnection::sendToTool(const std::string & message) { // convert to ByteStream std::string temp = message; temp += "\r\n*\r\n"; Archive::ByteStream bs; - bs.put( temp.c_str(), temp.size() ); + bs.put(temp.c_str(), temp.size()); // send. - this->send( bs, true ); -} + this->send(bs, true); +} void CSToolConnection::onConnectionOpened() { - LOG( "CSTool", ("Connection opened") ); + LOG("CSTool", ("Connection opened")); // assign an ID, and stick it in our map. m_curToolID++; m_toolID = m_curToolID; - CSToolConnectionNamespace::toolsByID[ m_toolID ] = this; - + CSToolConnectionNamespace::toolsByID[m_toolID] = this; } void CSToolConnection::onConnectionClosed() { - LOG( "CSTool", ("Connection closed") ); - CSToolConnectionNamespace::toolsByID.erase( m_toolID ); - -} + LOG("CSTool", ("Connection closed")); + CSToolConnectionNamespace::toolsByID.erase(m_toolID); +} \ No newline at end of file diff --git a/engine/server/application/LoginServer/src/shared/LoginServer.cpp b/engine/server/application/LoginServer/src/shared/LoginServer.cpp index a3a213a8..8393f5a9 100755 --- a/engine/server/application/LoginServer/src/shared/LoginServer.cpp +++ b/engine/server/application/LoginServer/src/shared/LoginServer.cpp @@ -2,7 +2,6 @@ // copyright 2000 Verant Interactive // Author: Justin Randall - //----------------------------------------------------------------------- #include "FirstLoginServer.h" @@ -123,23 +122,22 @@ bool ConnectionServerEntryLessThan::operator()(const LoginServer::ConnectionServ return x.numClients < y.numClients; } - //----------------------------------------------------------------------- LoginServer::LoginServer() : -Singleton(), -MessageDispatch::Receiver(), -done(false), -m_centralService(nullptr), -clientService(0), -pingService(0), -keyServer(0), -m_clientMap(), -m_clusterList(), -m_sessionApiClient(0), -m_validatedClientMap(), -m_clusterStatusChanged(false), -m_soeMonitor(0) + Singleton(), + MessageDispatch::Receiver(), + done(false), + m_centralService(nullptr), + clientService(0), + pingService(0), + keyServer(0), + m_clientMap(), + m_clusterList(), + m_sessionApiClient(0), + m_validatedClientMap(), + m_clusterStatusChanged(false), + m_soeMonitor(0) { NetworkSetupData setup; setup.port = ConfigLoginServer::getClientServicePort(); @@ -161,9 +159,9 @@ m_soeMonitor(0) setup.maxConnections = 1000; m_centralService = new Service(ConnectionAllocator(), setup); } - + setup.port = ConfigLoginServer::getCSToolPort(); - m_CSService = new Service(ConnectionAllocator(), setup ); + m_CSService = new Service(ConnectionAllocator(), setup); // set up message connections connectToMessage("ClaimRewardsMessage"); @@ -209,7 +207,7 @@ LoginServer::~LoginServer() //----------------------------------------------------------------------- -int LoginServer::addClient (ClientConnection & client) +int LoginServer::addClient(ClientConnection & client) { DEBUG_FATAL(client.getIsValidated(), ("Tried to add an already validated client?!")); //Perhaps add a debug only check to make sure a client connection isn't in twice...I'm not sure how that could happen. @@ -221,18 +219,17 @@ int LoginServer::addClient (ClientConnection & client) //----------------------------------------------------------------------- -ClientConnection* LoginServer::getValidatedClient (const StationId& clientId) +ClientConnection* LoginServer::getValidatedClient(const StationId& clientId) { std::map::iterator i = m_validatedClientMap.find(clientId); if (i == m_validatedClientMap.end()) return 0; return i->second; - } //----------------------------------------------------------------------- -ClientConnection* LoginServer::getUnvalidatedClient (int clientId) +ClientConnection* LoginServer::getUnvalidatedClient(int clientId) { WARNING_STRICT_FATAL(clientId == 0, ("Tried to get an unvalidated client with client id == 0")); std::map::iterator i = m_clientMap.find(clientId); @@ -243,7 +240,7 @@ ClientConnection* LoginServer::getUnvalidatedClient (int clientId) } //----------------------------------------------------------------------- -void LoginServer::removeClient (int clientId) +void LoginServer::removeClient(int clientId) { WARNING_STRICT_FATAL(clientId == 0, ("Tried to remove a client with client id == 0")); std::map::iterator i = m_clientMap.find(clientId); @@ -268,7 +265,7 @@ void LoginServer::installSessionValidation() for (i = 0; i < numberOfSessionServers; ++i) { char const * const p = ConfigLoginServer::getSessionServer(i); - if(p) + if (p) { REPORT_LOG(true, ("Using session server %s\n", p)); sessionServers.push_back(p); @@ -291,7 +288,7 @@ bool LoginServer::deleteCharacter(uint32 clusterId, NetworkId const & characterI if (cle->m_centralServerConnection) { ServerDeleteCharacterMessage smsg(suid, characterId, 0); - cle->m_centralServerConnection->send(smsg,true); + cle->m_centralServerConnection->send(smsg, true); ClientConnection* target = getValidatedClient(suid); if (target) @@ -304,18 +301,17 @@ bool LoginServer::deleteCharacter(uint32 clusterId, NetworkId const & characterI } else { - DEBUG_REPORT_LOG(true,("User %lu requested deleting character %s on cluster %lu, but the cluster is not currently connected.\n",suid , characterId.getValueString().c_str(), clusterId)); + DEBUG_REPORT_LOG(true, ("User %lu requested deleting character %s on cluster %lu, but the cluster is not currently connected.\n", suid, characterId.getValueString().c_str(), clusterId)); return false; } } else { - DEBUG_REPORT_LOG(true,("User %lu requested deleting character %s on cluster %lu, but we have no cluster with that number.\n", suid, characterId.getValueString().c_str(), clusterId)); + DEBUG_REPORT_LOG(true, ("User %lu requested deleting character %s on cluster %lu, but we have no cluster with that number.\n", suid, characterId.getValueString().c_str(), clusterId)); return false; } } - //----------------------------------------------------------------------- const KeyShare::Key & LoginServer::getCurrentKey(void) const @@ -330,7 +326,6 @@ SessionApiClient * LoginServer::getSessionApiClient() return m_sessionApiClient; } - //----------------------------------------------------------------------- KeyShare::Token LoginServer::makeToken(const unsigned char * const data, const uint32 dataLen) const @@ -342,7 +337,7 @@ KeyShare::Token LoginServer::makeToken(const unsigned char * const data, const u void LoginServer::pushAllKeys(CentralServerConnection * targetGameServer) const { - for(int i = static_cast(keyServer->getKeyCount()) - 1; i >=0 ; i --) + for (int i = static_cast(keyServer->getKeyCount()) - 1; i >= 0; i--) { LoginKeyPush pk(keyServer->getKey(static_cast(i))); targetGameServer->send(pk, true); @@ -353,24 +348,24 @@ void LoginServer::pushAllKeys(CentralServerConnection * targetGameServer) const void LoginServer::pushKeyToAllServers(void) { - KeyShare::Key k = keyServer->getKey(0); - CentralServerConnection * c; + KeyShare::Key k = keyServer->getKey(0); + CentralServerConnection * c; - LoginKeyPush msg(k); + LoginKeyPush msg(k); - unsigned char s[128]; - memcpy(s, k.value, 16); //lint !e64 !e119 !e534 // not sure where lint is finding a memcpy(void *, int) prototype - DEBUG_REPORT_LOG(true, ("Key Exchange ->: ")); - for(int x = 0; x < 16; x++) - { - DEBUG_REPORT_LOG(true, ("[%3i]", s[x])); - } - DEBUG_REPORT_LOG(true, ("\n")); + unsigned char s[128]; + memcpy(s, k.value, 16); //lint !e64 !e119 !e534 // not sure where lint is finding a memcpy(void *, int) prototype + DEBUG_REPORT_LOG(true, ("Key Exchange ->: ")); + for (int x = 0; x < 16; x++) + { + DEBUG_REPORT_LOG(true, ("[%3i]", s[x])); + } + DEBUG_REPORT_LOG(true, ("\n")); - for (ClusterListType::const_iterator i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (ClusterListType::const_iterator i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { c = (*i)->m_centralServerConnection; - if(c) + if (c) { c->send(msg, true); } @@ -382,16 +377,16 @@ void LoginServer::pushKeyToAllServers(void) void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const MessageDispatch::MessageBase & message) { // determine message type - - if(message.isType("LoginClusterName") || message.isType( "LoginClusterName2" ) ) - { + + if (message.isType("LoginClusterName") || message.isType("LoginClusterName2")) + { Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const LoginClusterName msg(ri); - if(msg.getClusterName().length() > 0) - { + const LoginClusterName msg(ri); + if (msg.getClusterName().length() > 0) + { CentralServerConnection * connection = const_cast(safe_cast(&source)); DEBUG_REPORT_LOG(true, ("Cluster connection %s opened\n", msg.getClusterName().c_str())); - ClusterListEntry *cle=nullptr; + ClusterListEntry *cle = nullptr; if (ConfigLoginServer::getDevelopmentMode()) { // in this mode, we trust the name sent by the cluster and we dynamically add clusters we don't know about @@ -404,13 +399,13 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const // in this mode, the cluster name has to match what we were expecting cle = findClusterByConnection(connection); if (!cle) - DEBUG_FATAL(true,("PROGRAMMER BUG: Got a connection from %s:%hu, which we weren't expecting. Cluster name is \"%s\".\n",connection->getRemoteAddress().c_str(), connection->getRemotePort(), msg.getClusterName().c_str())); + DEBUG_FATAL(true, ("PROGRAMMER BUG: Got a connection from %s:%hu, which we weren't expecting. Cluster name is \"%s\".\n", connection->getRemoteAddress().c_str(), connection->getRemotePort(), msg.getClusterName().c_str())); else if (msg.getClusterName() != cle->m_clusterName) { - WARNING(true,("Server %i is named \"%s\" in the database. The server at the specified address (%s:%hu) reports its name as \"%s\". It will not be allowed in the service. Either the name in the database or the name in Central's config file should be corrected.\n",cle->m_clusterId, cle->m_clusterName.c_str(), connection->getRemoteAddress().c_str(), connection->getRemotePort(), msg.getClusterName().c_str())); - disconnectCluster(*cle,true,false); - cle=nullptr; + WARNING(true, ("Server %i is named \"%s\" in the database. The server at the specified address (%s:%hu) reports its name as \"%s\". It will not be allowed in the service. Either the name in the database or the name in Central's config file should be corrected.\n", cle->m_clusterId, cle->m_clusterName.c_str(), connection->getRemoteAddress().c_str(), connection->getRemotePort(), msg.getClusterName().c_str())); + disconnectCluster(*cle, true, false); + cle = nullptr; } } @@ -423,8 +418,8 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const if (cle->m_clusterId == 0) { - DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(),("Programmer bug: cle->m_clusterId was 0 in non-development mode. The code before this line should have prevented this.\n")); - DEBUG_REPORT_LOG(true,("Cluster was not on the list. Adding it to the database.\n")); + DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(), ("Programmer bug: cle->m_clusterId was 0 in non-development mode. The code before this line should have prevented this.\n")); + DEBUG_REPORT_LOG(true, ("Cluster was not on the list. Adding it to the database.\n")); DatabaseConnection::getInstance().registerNewCluster(msg.getClusterName(), connection->getRemoteAddress()); } else @@ -441,30 +436,30 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const // tell the cluster about its locked and secret state GenericValueTypeMessage > const msgState("UpdateClusterLockedAndSecretState", std::make_pair(cle->m_locked, cle->m_secret)); - cle->m_centralServerConnection->send(msgState,true); + cle->m_centralServerConnection->send(msgState, true); } } - } + } else if (message.isType("LoginConnectionServerAddress")) { const CentralServerConnection * cs = safe_cast(&source); Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoginConnectionServerAddress m(ri); //lint !e1774 !e826onServerEntry entry; + LoginConnectionServerAddress m(ri); //lint !e1774 !e826onServerEntry entry; ConnectionServerEntry entry; - entry.clientServiceAddress = Address(Address(m.getClientServiceAddress(), 0).getSockAddr4()).getHostAddress(); - entry.clientServicePortPrivate = m.getClientServicePortPrivate(); - entry.clientServicePortPublic = m.getClientServicePortPublic(); - entry.id = m.getId(); - entry.numClients = m.getNumClients(); - entry.pingPort = m.getPingPort (); + entry.clientServiceAddress = Address(Address(m.getClientServiceAddress(), 0).getSockAddr4()).getHostAddress(); + entry.clientServicePortPrivate = m.getClientServicePortPrivate(); + entry.clientServicePortPublic = m.getClientServicePortPublic(); + entry.id = m.getId(); + entry.numClients = m.getNumClients(); + entry.pingPort = m.getPingPort(); DEBUG_REPORT_LOG(true, ("ConnectionServer Reconnect - address from connection server (%s), address after conversion (%s)\n", m.getClientServiceAddress().c_str(), entry.clientServiceAddress.c_str())); ClusterListEntry *cle = findClusterByConnection(cs); if (cle) { - WARNING_STRICT_FATAL(!cle->m_centralServerConnection, ("Got reconnect for connection server with no central! Cluster %s\n",cs->getClusterName().c_str())); + WARNING_STRICT_FATAL(!cle->m_centralServerConnection, ("Got reconnect for connection server with no central! Cluster %s\n", cs->getClusterName().c_str())); std::vector::iterator i = std::find(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), entry); if (i == cle->m_connectionServers.end()) { @@ -479,7 +474,7 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const std::sort(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), ConnectionServerEntryLessThan()); } else - WARNING_STRICT_FATAL(true,("Programmer bug: Got LoginConnectionServerAddress from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); + WARNING_STRICT_FATAL(true, ("Programmer bug: Got LoginConnectionServerAddress from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); } else if (message.isType("PreloadFinishedMessage")) { @@ -492,7 +487,7 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const { if (msg.getFinished()) { - REPORT_LOG(true, ("Cluster %s is ready for players.\n",cle->m_clusterName.c_str())); + REPORT_LOG(true, ("Cluster %s is ready for players.\n", cle->m_clusterName.c_str())); if (!cle->m_readyForPlayers) { cle->m_readyForPlayers = true; @@ -501,7 +496,7 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const } else { - REPORT_LOG(true, ("Cluster %s is not ready for players.\n",cle->m_clusterName.c_str())); + REPORT_LOG(true, ("Cluster %s is not ready for players.\n", cle->m_clusterName.c_str())); if (cle->m_readyForPlayers) { cle->m_readyForPlayers = false; @@ -511,11 +506,10 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const } } else - WARNING_STRICT_FATAL(true,("Programmer bug: Got PreloadFinishedMessage from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); + WARNING_STRICT_FATAL(true, ("Programmer bug: Got PreloadFinishedMessage from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); } - else if(message.isType("ConnectionServerDown")) + else if (message.isType("ConnectionServerDown")) { - const CentralServerConnection * centralConnection = safe_cast(&source); Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); ConnectionServerDown c(ri); //lint !e1774 !e826 @@ -540,9 +534,9 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const m_clusterStatusChanged = true; } else - WARNING_STRICT_FATAL(true,("Programmer bug: Got ConnectionServerDown from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); + WARNING_STRICT_FATAL(true, ("Programmer bug: Got ConnectionServerDown from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); } - else if(message.isType("ConnectionClosed")) + else if (message.isType("ConnectionClosed")) { const CentralServerConnection *c = dynamic_cast(&source); if (c) @@ -551,22 +545,22 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const if (cle) { DEBUG_REPORT_LOG(true, ("Cluster connection %s closed.\n", c->getClusterName().c_str())); - disconnectCluster(*cle,false,true); + disconnectCluster(*cle, false, true); } else - WARNING_STRICT_FATAL(true,("Programmer bug: Cluster disconnected but it wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); + WARNING_STRICT_FATAL(true, ("Programmer bug: Cluster disconnected but it wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); } } else if (message.isType("ValidateAccountMessage")) { Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ValidateAccountMessage msg(ri); + ValidateAccountMessage msg(ri); const CentralServerConnection *conn = dynamic_cast(&source); if (conn) - DatabaseConnection::getInstance().getAccountValidationData(msg.getStationId(), conn->getClusterId(), msg.getTrack(), msg.getSubscriptionBits()); + DatabaseConnection::getInstance().getAccountValidationData(msg.getStationId(), conn->getClusterId(), msg.getTrack(), msg.getSubscriptionBits()); else - WARNING_STRICT_FATAL(true,("Expect ValidateAccountMessage's to only come from CentralServers.\n")); + WARNING_STRICT_FATAL(true, ("Expect ValidateAccountMessage's to only come from CentralServers.\n")); } else if (message.isType("CntrlSrvDropDupeConns")) { @@ -621,9 +615,9 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const if (nonSessionTestingAccountFeatureIds && !msg.getTargetPlayerDescription().empty() && msg.getTargetItem().isValid() && !msg.getTargetItemDescription().empty()) { if (msg.getGameCode() == PlatformGameCode::SWGTCG) - LOG("CustomerService",("TcgRedemption: %s redeemed %s for SWGTCG account feature Id %lu (%d -> %d)", msg.getTargetPlayerDescription().c_str(), msg.getTargetItemDescription().c_str(), msg.getFeatureId(), currentFeatureIdCount, updatedFeatureIdCount)); + LOG("CustomerService", ("TcgRedemption: %s redeemed %s for SWGTCG account feature Id %lu (%d -> %d)", msg.getTargetPlayerDescription().c_str(), msg.getTargetItemDescription().c_str(), msg.getFeatureId(), currentFeatureIdCount, updatedFeatureIdCount)); else if (msg.getGameCode() == PlatformGameCode::SWG) - LOG("CustomerService",("VeteranRewards: %s traded in %s for SWG account feature Id %lu (%d -> %d)", msg.getTargetPlayerDescription().c_str(), msg.getTargetItemDescription().c_str(), msg.getFeatureId(), currentFeatureIdCount, updatedFeatureIdCount)); + LOG("CustomerService", ("VeteranRewards: %s traded in %s for SWG account feature Id %lu (%d -> %d)", msg.getTargetPlayerDescription().c_str(), msg.getTargetItemDescription().c_str(), msg.getFeatureId(), currentFeatureIdCount, updatedFeatureIdCount)); } const CentralServerConnection * conn = dynamic_cast(&source); @@ -723,10 +717,10 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const // send failure back to originating server TransferReplyMoveValidation reply(request.getTransferRequestSource(), request.getTrack(), request.getSourceStationId(), request.getDestinationStationId(), request.getSourceGalaxy(), request.getDestinationGalaxy(), request.getSourceCharacter(), request.getSourceCharacterId(), request.getSourceCharacterTemplateId(), request.getDestinationCharacter(), request.getCustomerLocalizedLanguage(), result); const CentralServerConnection * conn = dynamic_cast(&source); - if(conn) + if (conn) { ClusterListEntry * sourceEntry = findClusterById(conn->getClusterId()); - if(sourceEntry && sourceEntry->m_centralServerConnection) + if (sourceEntry && sourceEntry->m_centralServerConnection) { sourceEntry->m_centralServerConnection->send(reply, true); } @@ -776,7 +770,7 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const if (cle) { std::vector::iterator i = cle->m_connectionServers.begin(); - for (; i!= cle->m_connectionServers.end(); ++i) + for (; i != cle->m_connectionServers.end(); ++i) { if (i->id == msg.getId()) { @@ -789,7 +783,6 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const std::sort(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), ConnectionServerEntryLessThan()); } } - } else if (message.isType("UpdatePlayerCountMessage")) { @@ -805,9 +798,9 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const // We only want to update the clients if some "threshold" has been crossed if ((cle->m_notRecommendedCentral != msg.getLoadedRecently()) - || hasCrossedThreshold(cle->m_onlineTutorialLimit, cle->m_numTutorialPlayers, tutorialPlayerCount) - || hasCrossedThreshold(cle->m_onlineFreeTrialLimit, cle->m_numFreeTrialPlayers, msg.getFreeTrialCount()) - || hasCrossedThreshold(cle->m_onlinePlayerLimit, cle->m_numPlayers, msg.getCount())) + || hasCrossedThreshold(cle->m_onlineTutorialLimit, cle->m_numTutorialPlayers, tutorialPlayerCount) + || hasCrossedThreshold(cle->m_onlineFreeTrialLimit, cle->m_numFreeTrialPlayers, msg.getFreeTrialCount()) + || hasCrossedThreshold(cle->m_onlinePlayerLimit, cle->m_numPlayers, msg.getCount())) { m_clusterStatusChanged = true; } @@ -828,7 +821,7 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const if (conn) DatabaseConnection::getInstance().renameCharacter(conn->getClusterId(), msg.getCharacterId(), msg.getNewName(), nullptr); else - WARNING_STRICT_FATAL(true,("Got RenameCharacterMessage from something other than CentralServerConnection.\n")); + WARNING_STRICT_FATAL(true, ("Got RenameCharacterMessage from something other than CentralServerConnection.\n")); } else if (message.isType("LoginCreateCharacterMessage")) { @@ -836,7 +829,7 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const LoginCreateCharacterMessage msg(ri); const CentralServerConnection *conn = dynamic_cast(&source); if (conn) - DatabaseConnection::getInstance().createCharacter(conn->getClusterId(),msg.getStationId(),msg.getCharacterName(),msg.getCharacterObjectId(),msg.getTemplateId(), msg.getJedi()); + DatabaseConnection::getInstance().createCharacter(conn->getClusterId(), msg.getStationId(), msg.getCharacterName(), msg.getCharacterObjectId(), msg.getTemplateId(), msg.getJedi()); } else if (message.isType("LoginRestoreCharacterMessage")) { @@ -844,7 +837,7 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const LoginRestoreCharacterMessage msg(ri); const CentralServerConnection *conn = dynamic_cast(&source); if (conn) - DatabaseConnection::getInstance().restoreCharacter(conn->getClusterId(),msg.getWhoRequested(),msg.getAccount(),msg.getCharacterName(),msg.getCharacterId(),msg.getTemplateId(), msg.getJedi()); + DatabaseConnection::getInstance().restoreCharacter(conn->getClusterId(), msg.getWhoRequested(), msg.getAccount(), msg.getCharacterName(), msg.getCharacterId(), msg.getTemplateId(), msg.getJedi()); } else if (message.isType("LoginUpgradeAccountMessage")) { @@ -852,7 +845,7 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const LoginUpgradeAccountMessage *msg = new LoginUpgradeAccountMessage(ri); const CentralServerConnection *conn = dynamic_cast(&source); if (conn) - DatabaseConnection::getInstance().upgradeAccount(msg,conn->getClusterId()); + DatabaseConnection::getInstance().upgradeAccount(msg, conn->getClusterId()); } else if (message.isType("ClaimRewardsMessage")) { @@ -960,7 +953,7 @@ void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const if (conn) PurgeManager::handlePurgeCompleteOnCluster(msg.getValue(), conn->getClusterId()); else - WARNING_STRICT_FATAL(true,("Programmer bug: got PurgeCompleteMessage from something that couldn't be cast to a CentralServerConnection")); + WARNING_STRICT_FATAL(true, ("Programmer bug: got PurgeCompleteMessage from something that couldn't be cast to a CentralServerConnection")); } else if (message.isType("OccupyUnlockedSlotReq")) { @@ -1010,11 +1003,11 @@ void LoginServer::validateAccount(const StationId& stationId, uint32 clusterId, // allow logins unless the cluster is full bool clientIsInternal = false; ClientConnection *conn = getValidatedClient(stationId); - if (conn) + if (conn) { clientIsInternal = AdminAccountManager::isInternalIp(conn->getRemoteAddress()); } - + if (clientIsInternal && ConfigLoginServer::getInternalBypassOnlineLimit()) { canLogin = true; @@ -1022,17 +1015,17 @@ void LoginServer::validateAccount(const StationId& stationId, uint32 clusterId, else if (cle->m_numPlayers <= cle->m_onlinePlayerLimit) { canLogin = true; - + // Check cluster npe user limit if (cle->m_numTutorialPlayers > cle->m_onlineTutorialLimit) { - canCreateRegular=false; - canCreateJedi=false; + canCreateRegular = false; + canCreateJedi = false; } - + // limit login/character creation based on subscription feature bits - if ( ((subscriptionBits & ClientSubscriptionFeature::FreeTrial) != 0) - && ((subscriptionBits & ClientSubscriptionFeature::Base) == 0)) + if (((subscriptionBits & ClientSubscriptionFeature::FreeTrial) != 0) + && ((subscriptionBits & ClientSubscriptionFeature::Base) == 0)) { // Check cluster free trial user limit if (cle->m_numFreeTrialPlayers > cle->m_onlineFreeTrialLimit) @@ -1042,25 +1035,25 @@ void LoginServer::validateAccount(const StationId& stationId, uint32 clusterId, // Check cluster free trial character creation if (!cle->m_freeTrialCanCreateChar) { - canCreateRegular=false; - canCreateJedi=false; + canCreateRegular = false; + canCreateJedi = false; } } } if (!canLogin) { - canCreateRegular=false; - canCreateJedi=false; - canSkipTutorial=false; + canCreateRegular = false; + canCreateJedi = false; + canSkipTutorial = false; } // check if we want to allow skip tutorial to all if (ConfigLoginServer::getAllowSkipTutorialToAll()) - canSkipTutorial=true; + canSkipTutorial = true; ValidateAccountReplyMessage msg(stationId, canLogin, canCreateRegular, canCreateJedi, canSkipTutorial, track, consumedRewardEvents, claimedRewardItems); - cle->m_centralServerConnection->send(msg,true); + cle->m_centralServerConnection->send(msg, true); } } @@ -1095,7 +1088,7 @@ void LoginServer::validateAccountForTransfer(const TransferRequestMoveValidation } ClusterListEntry * cle = findClusterById(clusterId); - if(cle && cle->m_centralServerConnection) + if (cle && cle->m_centralServerConnection) { TransferReplyMoveValidation response(request.getTransferRequestSource(), request.getTrack(), request.getSourceStationId(), request.getDestinationStationId(), request.getSourceGalaxy(), request.getDestinationGalaxy(), request.getSourceCharacter(), request.getSourceCharacterId(), sourceCharacterTemplateId, request.getDestinationCharacter(), request.getCustomerLocalizedLanguage(), (canCreateRegular ? TransferReplyMoveValidation::TRMVR_can_create_regular_character : TransferReplyMoveValidation::TRMVR_cannot_create_regular_character)); cle->m_centralServerConnection->send(response, true); @@ -1126,7 +1119,7 @@ void LoginServer::run(void) mon->add(masterChannel, WORLD_COUNT_CHANNEL); std::string host = NetworkHandler::getHostName().c_str(); size_t dotPos = host.find("."); - if(dotPos != host.npos) + if (dotPos != host.npos) { host = host.substr(0, dotPos - 1); } @@ -1136,11 +1129,11 @@ void LoginServer::run(void) mon->add("Galaxies", CLUSTER_COUNT_CHANNEL); - while(!getInstance().done) + while (!getInstance().done) { startTime = Clock::timeMs(); IGNORE_RETURN(Os::update()); - if(getInstance().keyServer->update()) + if (getInstance().keyServer->update()) { getInstance().pushKeyToAllServers(); } @@ -1149,10 +1142,10 @@ void LoginServer::run(void) { Os::sleep(1); NetworkHandler::update(); - } while(Clock::timeMs() - startTime < limit); + } while (Clock::timeMs() - startTime < limit); DatabaseConnection::getInstance().update(); - PurgeManager::update(static_cast(limit)/ 1000.0f); + PurgeManager::update(static_cast(limit) / 1000.0f); if (getInstance().m_clusterStatusChanged) { getInstance().sendClusterStatusToAll(); @@ -1175,9 +1168,9 @@ void LoginServer::run(void) mon->set(WORLD_COUNT_CHANNEL, static_cast(getInstance().m_clientMap.size())); int count = 0; ClusterListType::const_iterator i; - for(i = getInstance().m_clusterList.begin(); i != getInstance().m_clusterList.end(); ++i) + for (i = getInstance().m_clusterList.begin(); i != getInstance().m_clusterList.end(); ++i) { - if((*i)->m_connected) + if ((*i)->m_connected) ++count; } mon->set(CLUSTER_COUNT_CHANNEL, count); @@ -1194,7 +1187,6 @@ void LoginServer::run(void) NetworkHandler::remove(); } - //----------------------------------------------------------------------- void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumberJediSlot, const AvatarList &avatars, TransferCharacterData * const transferData) @@ -1203,7 +1195,7 @@ void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumber chardata.reserve(avatars.size()); EnumerateCharacterId::Chardata temp; - for (AvatarList::const_iterator i=avatars.begin(); i!=avatars.end(); ++i) + for (AvatarList::const_iterator i = avatars.begin(); i != avatars.end(); ++i) { temp.m_name = (*i).m_name; temp.m_objectTemplateId = (*i).m_objectTemplateId; @@ -1216,15 +1208,15 @@ void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumber EnumerateCharacterId msg(chardata); - if(transferData) + if (transferData) { // send this to the appropriate CentralServer - if(transferData->getSourceCharacterName().empty()) + if (transferData->getSourceCharacterName().empty()) { // CTS API character list request bool result = CentralServerConnection::sendCharacterListResponse(transferData->getSourceStationId(), avatars, *transferData); UNREF(result); - DEBUG_REPORT_LOG(! result,("Could not send avatar list to StationId %lu because connection has been closed.\n",stationId)); + DEBUG_REPORT_LOG(!result, ("Could not send avatar list to StationId %lu because connection has been closed.\n", stationId)); } else { @@ -1234,11 +1226,11 @@ void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumber if (cle) { // find associated character ID - for (AvatarList::const_iterator i=avatars.begin(); i!=avatars.end(); ++i) + for (AvatarList::const_iterator i = avatars.begin(); i != avatars.end(); ++i) { REPORT_LOG(true, ("checking %s == %s\n", Unicode::wideToNarrow(i->m_name).c_str(), transferData->getSourceCharacterName().c_str())); - if(Unicode::wideToNarrow(i->m_name) == transferData->getSourceCharacterName() - && i->m_clusterId == cle->m_clusterId) + if (Unicode::wideToNarrow(i->m_name) == transferData->getSourceCharacterName() + && i->m_clusterId == cle->m_clusterId) { characterTemplateId = static_cast(i->m_objectTemplateId); characterId = i->m_networkId; @@ -1267,13 +1259,13 @@ void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumber // this message ***MUST*** be sent first, as the client expects to // receive this information before receiving the avatar list information GenericValueTypeMessage const msgStationIdHasJediSlot("StationIdHasJediSlot", stationIdNumberJediSlot); - conn->send(msgStationIdHasJediSlot,true); + conn->send(msgStationIdHasJediSlot, true); - conn->send(msg,true); + conn->send(msg, true); } else { - DEBUG_REPORT_LOG(true,("Could not send avatar list to StationId %lu.\n",stationId)); + DEBUG_REPORT_LOG(true, ("Could not send avatar list to StationId %lu.\n", stationId)); LOG("LoginClientConnection", ("sendAvatarList() for stationId (%lu), cannot find connection to client for sending avatar list", stationId)); } } @@ -1281,7 +1273,7 @@ void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumber // ---------------------------------------------------------------------- -void LoginServer::performAccountTransfer (const AvatarList &avatars, TransferAccountData * transferAccountData) +void LoginServer::performAccountTransfer(const AvatarList &avatars, TransferAccountData * transferAccountData) { // grab the station ids StationId sourceStationId = transferAccountData->getSourceStationId(); @@ -1297,14 +1289,14 @@ void LoginServer::performAccountTransfer (const AvatarList &avatars, TransferAcc if (cluster) { - std::string clusterName = cluster->m_clusterName; + std::string clusterName = cluster->m_clusterName; std::string avatarName = Unicode::wideToNarrow(i->m_name); avatarData.push_back(AvatarData(clusterName, avatarName)); - + LOG("CustomerService", ("CharacterTransfer: Sending request to update game db (via cluster: %s) for account transfer from %lu to %lu (avatar: %s)", clusterName.c_str(), sourceStationId, destinationStationId, avatarName.c_str())); const GenericValueTypeMessage message("TransferAccountRequestCentralDatabase", *transferAccountData); - sendToCluster (i->m_clusterId, message); + sendToCluster(i->m_clusterId, message); } else { @@ -1331,38 +1323,38 @@ void LoginServer::onValidateClient(StationId suid, const std::string & username, NOT_NULL(conn); WARNING_STRICT_FATAL(getValidatedClient(suid), ("Validating an already valid client in onValidateClient(). StationId: %d UserName: %s", suid, username.c_str())); - int adminLevel=0; + int adminLevel = 0; const bool isAdminAccount = AdminAccountManager::isAdminAccount(Unicode::toLower(username), adminLevel); if (conn->getRequestedAdminSuid() != 0) { //verify internal, secure, is on the god list - bool loginOK=false; - if(!isSecure) - LOG("CustomerService",("AdminLogin: User %s (account %li) attempted to log into account %li, but was not using a SecureID token", username.c_str(),suid, conn->getRequestedAdminSuid())); + bool loginOK = false; + if (!isSecure) + LOG("CustomerService", ("AdminLogin: User %s (account %li) attempted to log into account %li, but was not using a SecureID token", username.c_str(), suid, conn->getRequestedAdminSuid())); else { if (!AdminAccountManager::isInternalIp(conn->getRemoteAddress())) - LOG("CustomerService",("AdminLogin: User %s (account %li) attempted to log into account %li, but was not logging in from an internal IP", username.c_str(),suid, conn->getRequestedAdminSuid())); + LOG("CustomerService", ("AdminLogin: User %s (account %li) attempted to log into account %li, but was not logging in from an internal IP", username.c_str(), suid, conn->getRequestedAdminSuid())); else { if (!isAdminAccount || adminLevel < 10) - LOG("CustomerService",("AdminLogin: User %s (account %li) attempted to log into account %li, but did not have sufficient permissions", username.c_str(),suid, conn->getRequestedAdminSuid())); + LOG("CustomerService", ("AdminLogin: User %s (account %li) attempted to log into account %li, but did not have sufficient permissions", username.c_str(), suid, conn->getRequestedAdminSuid())); else { suid = conn->getRequestedAdminSuid(); - loginOK=true; + loginOK = true; } } } - + if (!loginOK) { conn->disconnect(); return; } } - + // encrypt the clients credentials with the key, return // the cipher text to the client for use as a connection // token with the central server @@ -1408,35 +1400,35 @@ void LoginServer::onValidateClient(StationId suid, const std::string & username, const LoginClientToken k(a.getBuffer(), static_cast(a.getSize()), static_cast(suid), username); conn->send(k, true); - delete [] keyBuffer; + delete[] keyBuffer; // send cluster enum bool clientInternal = AdminAccountManager::isInternalIp(conn->getRemoteAddress()); - + std::vector data; - for(ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) + for (ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) { ClusterListEntry *cle = *j; - if (cle && cle->m_clusterId!=0 && cle->m_clusterName.size()!=0 && (clientInternal || !cle->m_secret)) + if (cle && cle->m_clusterId != 0 && cle->m_clusterName.size() != 0 && (clientInternal || !cle->m_secret)) { LoginEnumCluster::ClusterData item; - item.m_clusterId = cle->m_clusterId; + item.m_clusterId = cle->m_clusterId; item.m_clusterName = cle->m_clusterName; - item.m_timeZone = cle->m_timeZone; + item.m_timeZone = cle->m_timeZone; data.push_back(item); } } - - LoginEnumCluster e( data, ConfigLoginServer::getMaxCharactersPerAccount() ); - - conn->send(e,true); + + LoginEnumCluster e(data, ConfigLoginServer::getMaxCharactersPerAccount()); + + conn->send(e, true); //Send off list of cluster that has character //creation disabled, even if the list is empty //***MUST*** be done after sending LoginEnumCluster GenericValueTypeMessage > const msgCharacterCreationDisabledClusterList("CharacterCreationDisabled", ConfigLoginServer::getCharacterCreationDisabledClusterList()); - conn->send(msgCharacterCreationDisabledClusterList,true); + conn->send(msgCharacterCreationDisabledClusterList, true); //Send off request for the avatar list from the database. DatabaseConnection::getInstance().requestAvatarListForAccount(suid, 0); @@ -1459,7 +1451,7 @@ void LoginServer::onValidateClient(StationId suid, const std::string & username, LoginServer::ClusterListEntry *LoginServer::findClusterByName(const std::string &clusterName) { ClusterListType::iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { NOT_NULL(*i); // not legal to push nullptr pointers on the vector if ((*i)->m_clusterName == clusterName) @@ -1470,15 +1462,15 @@ LoginServer::ClusterListEntry *LoginServer::findClusterByName(const std::string // ---------------------------------------------------------------------- -uint32 LoginServer::getClusterIDByName( const std::string &sName ) +uint32 LoginServer::getClusterIDByName(const std::string &sName) { - ClusterListEntry const * const p_cluster = findClusterByName( sName ); + ClusterListEntry const * const p_cluster = findClusterByName(sName); return p_cluster ? p_cluster->m_clusterId : 0; } // ---------------------------------------------------------------------- -const std::string & LoginServer::getClusterNameById( uint32 clusterId ) +const std::string & LoginServer::getClusterNameById(uint32 clusterId) { static std::string const empty; @@ -1493,7 +1485,7 @@ const std::string & LoginServer::getClusterNameById( uint32 clusterId ) LoginServer::ClusterListEntry *LoginServer::addCluster(const std::string &clusterName) { - DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(),("Programmer bug: addCluster(std::string&) can only be used in development mode.\n")); + DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(), ("Programmer bug: addCluster(std::string&) can only be used in development mode.\n")); ClusterListEntry *e = new ClusterListEntry; e->m_clusterName = clusterName; @@ -1503,27 +1495,26 @@ LoginServer::ClusterListEntry *LoginServer::addCluster(const std::string &cluste // ---------------------------------------------------------------------- -void LoginServer::sendExtendedClusterInfo( ClientConnection &client ) const +void LoginServer::sendExtendedClusterInfo(ClientConnection &client) const { std::vector data; - - for(ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) + + for (ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) { ClusterListEntry *cle = *j; - if ( cle ) + if (cle) { LoginClusterStatusEx::ClusterData item; - item.m_clusterId = cle->m_clusterId; - item.m_branch = cle->m_branch; - item.m_version = cle->m_changelist; + item.m_clusterId = cle->m_clusterId; + item.m_branch = cle->m_branch; + item.m_version = cle->m_changelist; item.m_networkVersion = cle->m_networkVersion; - data.push_back( item ); + data.push_back(item); } - } - - client.send( LoginClusterStatusEx( data ), true ); + + client.send(LoginClusterStatusEx(data), true); } // ---------------------------------------------------------------------- @@ -1536,15 +1527,15 @@ void LoginServer::sendExtendedClusterInfo( ClientConnection &client ) const */ void LoginServer::sendClusterStatus(ClientConnection &conn) const { - const bool clientIsPrivate = AdminAccountManager::isInternalIp(conn.getRemoteAddress()); - const unsigned int subscriptionBits = conn.getSubscriptionBits(); - const bool isFreeTrialAccount = ( ((subscriptionBits & ClientSubscriptionFeature::FreeTrial) != 0) - && ((subscriptionBits & ClientSubscriptionFeature::Base) == 0)); + const bool clientIsPrivate = AdminAccountManager::isInternalIp(conn.getRemoteAddress()); + const unsigned int subscriptionBits = conn.getSubscriptionBits(); + const bool isFreeTrialAccount = (((subscriptionBits & ClientSubscriptionFeature::FreeTrial) != 0) + && ((subscriptionBits & ClientSubscriptionFeature::Base) == 0)); std::vector data; std::vector dataEx; - - for(ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) + + for (ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) { ClusterListEntry *cle = *j; // Cluster is OK for login if @@ -1553,26 +1544,26 @@ void LoginServer::sendClusterStatus(ClientConnection &conn) const // 3) We have at least one Connection Server // 4) Client is internal or the cluster is not secret // 5) Cluster has told us its ready for players - if (cle && cle->m_clusterId!=0 && cle->m_connected && !cle->m_connectionServers.empty() && (clientIsPrivate || !cle->m_secret)) + if (cle && cle->m_clusterId != 0 && cle->m_connected && !cle->m_connectionServers.empty() && (clientIsPrivate || !cle->m_secret)) { - DEBUG_FATAL(!cle->m_centralServerConnection,("Programmer bug: m_connected was true but m_centralServerConnection was nullptr\n")); + DEBUG_FATAL(!cle->m_centralServerConnection, ("Programmer bug: m_connected was true but m_centralServerConnection was nullptr\n")); LoginClusterStatus::ClusterData item; item.m_clusterId = cle->m_clusterId; item.m_timeZone = cle->m_timeZone; -// size_t connectionServerChoice = Random::random(cle->m_connectionServers.size() - 1); //lint !e713 !e732 // loss of precision (arg no 1) + // size_t connectionServerChoice = Random::random(cle->m_connectionServers.size() - 1); //lint !e713 !e732 // loss of precision (arg no 1) ConnectionServerEntry &connServer = cle->m_connectionServers[0]; - item.m_connectionServerAddress = connServer.clientServiceAddress; - if(clientIsPrivate) + item.m_connectionServerAddress = connServer.clientServiceAddress; + if (clientIsPrivate) { - item.m_connectionServerPort = connServer.clientServicePortPrivate; + item.m_connectionServerPort = connServer.clientServicePortPrivate; } else { - item.m_connectionServerPort = connServer.clientServicePortPublic; + item.m_connectionServerPort = connServer.clientServicePortPublic; } - if(item.m_connectionServerPort) + if (item.m_connectionServerPort) { item.m_connectionServerPingPort = connServer.pingPort; @@ -1580,27 +1571,27 @@ void LoginServer::sendClusterStatus(ClientConnection &conn) const // population count to secured internal connections with // admin privilege >= 10 if (clientIsPrivate && conn.getIsSecure() && (conn.getAdminLevel() >= 10)) - item.m_populationOnline = cle->m_numPlayers; + item.m_populationOnline = cle->m_numPlayers; else - item.m_populationOnline = -1; + item.m_populationOnline = -1; const int percentFull = cle->m_numPlayers * 100 / cle->m_onlinePlayerLimit; if (percentFull >= 100) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_full; else if (percentFull >= ConfigLoginServer::getPopulationExtremelyHeavyThresholdPercent()) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_extremely_heavy; - else if (percentFull >= ConfigLoginServer::getPopulationVeryHeavyThresholdPercent()) + else if (percentFull >= ConfigLoginServer::getPopulationVeryHeavyThresholdPercent()) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_very_heavy; - else if (percentFull >= ConfigLoginServer::getPopulationHeavyThresholdPercent()) + else if (percentFull >= ConfigLoginServer::getPopulationHeavyThresholdPercent()) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_heavy; - else if (percentFull >= ConfigLoginServer::getPopulationMediumThresholdPercent()) + else if (percentFull >= ConfigLoginServer::getPopulationMediumThresholdPercent()) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_medium; - else if (percentFull >= ConfigLoginServer::getPopulationLightThresholdPercent()) + else if (percentFull >= ConfigLoginServer::getPopulationLightThresholdPercent()) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_light; - else + else item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_very_light; - item.m_maxCharactersPerAccount = cle->m_maxCharactersPerAccount; + item.m_maxCharactersPerAccount = cle->m_maxCharactersPerAccount; if (cle->m_readyForPlayers) { item.m_status = LoginClusterStatus::ClusterData::S_up; @@ -1611,7 +1602,7 @@ void LoginServer::sendClusterStatus(ClientConnection &conn) const item.m_status = LoginClusterStatus::ClusterData::S_restricted; } if ((cle->m_numPlayers >= cle->m_onlinePlayerLimit) - || (isFreeTrialAccount && (cle->m_numFreeTrialPlayers >= cle->m_onlineFreeTrialLimit))) + || (isFreeTrialAccount && (cle->m_numFreeTrialPlayers >= cle->m_onlineFreeTrialLimit))) { item.m_status = LoginClusterStatus::ClusterData::S_full; } @@ -1620,31 +1611,30 @@ void LoginServer::sendClusterStatus(ClientConnection &conn) const item.m_status = LoginClusterStatus::ClusterData::S_loading; if (cle->m_locked && !clientIsPrivate) item.m_status = LoginClusterStatus::ClusterData::S_locked; // locked takes precedence over up or loading - + item.m_dontRecommend = (cle->m_notRecommendedDatabase || cle->m_notRecommendedCentral); - item.m_onlinePlayerLimit = cle->m_onlinePlayerLimit; - item.m_onlineFreeTrialLimit = cle->m_onlineFreeTrialLimit; - + item.m_onlinePlayerLimit = cle->m_onlinePlayerLimit; + item.m_onlineFreeTrialLimit = cle->m_onlineFreeTrialLimit; + data.push_back(item); } ++connServer.numClients; std::sort(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), ConnectionServerEntryLessThan()); - } - - if ( cle ) + + if (cle) { LoginClusterStatusEx::ClusterData itemEx; itemEx.m_clusterId = cle->m_clusterId; - itemEx.m_branch = cle->m_branch; - itemEx.m_version = cle->m_changelist; - dataEx.push_back( itemEx ); + itemEx.m_branch = cle->m_branch; + itemEx.m_version = cle->m_changelist; + dataEx.push_back(itemEx); } } LoginClusterStatus msg(data); - conn.send(msg,true); + conn.send(msg, true); } // ---------------------------------------------------------------------- @@ -1654,7 +1644,7 @@ void LoginServer::sendClusterStatus(ClientConnection &conn) const */ void LoginServer::sendClusterStatusToAll() const { - for (std::map::const_iterator i=m_validatedClientMap.begin(); i!=m_validatedClientMap.end(); ++i) + for (std::map::const_iterator i = m_validatedClientMap.begin(); i != m_validatedClientMap.end(); ++i) { if (i->second) sendClusterStatus(*(i->second)); @@ -1664,29 +1654,30 @@ void LoginServer::sendClusterStatusToAll() const // ---------------------------------------------------------------------- LoginServer::ClusterListEntry::ClusterListEntry() : - m_clusterId(0), - m_clusterName(), - m_centralServerConnection(0), - m_connectionServers(), - m_numPlayers(0), - m_numFreeTrialPlayers(0), - m_numTutorialPlayers(0), - m_maxCharacters(ConfigLoginServer::getMaxCharactersPerCluster()), - m_maxCharactersPerAccount(0), - m_onlinePlayerLimit(0), - m_onlineFreeTrialLimit(0), - m_onlineTutorialLimit(0), - m_freeTrialCanCreateChar(false), - m_timeZone(0), - m_connected(false), - m_address(""), - m_port(0), - m_allowReconnect(true), - m_secret(false), - m_readyForPlayers(false), - m_locked(false), - m_notRecommendedDatabase(false), - m_notRecommendedCentral(false) + m_clusterId(0), + m_clusterName(), + m_centralServerConnection(0), + m_connectionServers(), + m_numPlayers(0), + m_numFreeTrialPlayers(0), + m_numTutorialPlayers(0), + m_maxCharacters(ConfigLoginServer::getMaxCharactersPerCluster()), + m_maxCharactersPerAccount(0), + m_onlinePlayerLimit(0), + m_onlineFreeTrialLimit(0), + m_onlineTutorialLimit(0), + m_freeTrialCanCreateChar(false), + m_timeZone(0), + m_connected(false), + m_address(""), + m_port(0), + m_allowReconnect(true), + m_secret(false), + m_readyForPlayers(false), + m_locked(false), + m_notRecommendedDatabase(false), + m_notRecommendedCentral(false), + m_changelist(0) { } @@ -1713,26 +1704,26 @@ void LoginServer::updateClusterData(uint32 clusterId, const std::string &cluster // refreshing data on a cluster we already know about if ((cle->m_clusterName != clusterName) || (cle->m_address != address) || (cle->m_port != port)) { - DEBUG_REPORT_LOG(true,("Disconnecting from cluster %lu because its data has changed in the database.\n",clusterId)); - disconnectCluster(*cle,true,true); + DEBUG_REPORT_LOG(true, ("Disconnecting from cluster %lu because its data has changed in the database.\n", clusterId)); + disconnectCluster(*cle, true, true); } } } if (!cle) { - DEBUG_REPORT_LOG(true,("Cluster %lu: %s\n", clusterId, clusterName.c_str())); + DEBUG_REPORT_LOG(true, ("Cluster %lu: %s\n", clusterId, clusterName.c_str())); cle = new ClusterListEntry; m_clusterList.push_back(cle); } if ((cle->m_secret != secret) - || (cle->m_locked != locked) - || (cle->m_onlinePlayerLimit != onlinePlayerLimit) - || (cle->m_onlineFreeTrialLimit != onlineFreeTrialLimit) - || (cle->m_freeTrialCanCreateChar != freeTrialCanCreateChar) - || (cle->m_onlineTutorialLimit != onlineTutorialLimit)) + || (cle->m_locked != locked) + || (cle->m_onlinePlayerLimit != onlinePlayerLimit) + || (cle->m_onlineFreeTrialLimit != onlineFreeTrialLimit) + || (cle->m_freeTrialCanCreateChar != freeTrialCanCreateChar) + || (cle->m_onlineTutorialLimit != onlineTutorialLimit)) { // The cluster may now be locked/unlocked to some players, so let them know m_clusterStatusChanged = true; @@ -1742,7 +1733,7 @@ void LoginServer::updateClusterData(uint32 clusterId, const std::string &cluster if (((cle->m_locked != locked) || (cle->m_secret != secret)) && cle->m_connected && cle->m_centralServerConnection) { GenericValueTypeMessage > const msgState("UpdateClusterLockedAndSecretState", std::make_pair(locked, secret)); - cle->m_centralServerConnection->send(msgState,true); + cle->m_centralServerConnection->send(msgState, true); } bool const clusterIdSet = ((cle->m_clusterId == 0) && (clusterId > 0)); @@ -1806,7 +1797,7 @@ void LoginServer::disconnectCluster(ClusterListEntry &cle, bool const forceDisco // started, and the LoginServer will connect to it if (!ConfigLoginServer::getDevelopmentMode() && reconnect) { - for (ClusterListType::iterator i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (ClusterListType::iterator i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { NOT_NULL(*i); if (!(*i)->m_centralServerConnection && !(*i)->m_allowReconnect && ((*i)->m_address == cle.m_address)) @@ -1824,7 +1815,7 @@ void LoginServer::disconnectCluster(ClusterListEntry &cle, bool const forceDisco */ void LoginServer::onClusterRegistered(uint32 clusterId, const std::string &clusterName) { - DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(),("Programmer bug: should not be registering new clusters automatically unless running in development mode.\n")); + DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(), ("Programmer bug: should not be registering new clusters automatically unless running in development mode.\n")); static std::string noAddress(""); updateClusterData(clusterId, clusterName, noAddress, 0, false, false, false, 8, 100, 100, true, 350); } @@ -1838,7 +1829,7 @@ void LoginServer::onClusterRegistered(uint32 clusterId, const std::string &clust LoginServer::ClusterListEntry * LoginServer::findClusterById(uint32 clusterId) { ClusterListType::const_iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { NOT_NULL(*i); // not legal to push nullptr pointers on the vector if ((*i)->m_clusterId == clusterId) @@ -1857,7 +1848,7 @@ LoginServer::ClusterListEntry * LoginServer::findClusterById(uint32 clusterId) LoginServer::ClusterListEntry * LoginServer::findClusterByConnection(const CentralServerConnection *connection) { ClusterListType::const_iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { NOT_NULL(*i); // not legal to push nullptr pointers on the vector if ((*i)->m_centralServerConnection == connection) @@ -1874,7 +1865,7 @@ void LoginServer::refreshConnections() if (ConfigLoginServer::getDevelopmentMode()) return; // in development mode, we don't establish any connections ClusterListType::iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { NOT_NULL(*i); if (!(*i)->m_centralServerConnection && (*i)->m_allowReconnect) @@ -1890,13 +1881,13 @@ void LoginServer::refreshConnections() // ---------------------------------------------------------------------- -void LoginServer::sendToCluster (uint32 clusterId, const GameNetworkMessage &message) +void LoginServer::sendToCluster(uint32 clusterId, const GameNetworkMessage &message) { ClusterListEntry *cle = findClusterById(clusterId); if (cle && cle->m_connected && cle->m_centralServerConnection) - cle->m_centralServerConnection->send(message,true); + cle->m_centralServerConnection->send(message, true); else - DEBUG_REPORT_LOG(true,("Could not send message to cluster %lu because it was not connected.\n",clusterId)); + DEBUG_REPORT_LOG(true, ("Could not send message to cluster %lu because it was not connected.\n", clusterId)); } //----------------------------------------------------------------------- @@ -1911,10 +1902,10 @@ void LoginServer::setDone(const bool isDone) void LoginServer::sendToAllClusters(GameNetworkMessage const & message, Connection const * excludeCentralConnection /*= nullptr*/, uint32 excludeClusterId /*= 0*/, char const * excludeClusterName /*= nullptr*/) { ClusterListType::const_iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { if (NON_NULL(*i)->m_connected && (*i)->m_centralServerConnection && ((*i)->m_centralServerConnection != excludeCentralConnection) && ((*i)->m_clusterId != excludeClusterId) && ((excludeClusterName == nullptr) || _stricmp(excludeClusterName, (*i)->m_centralServerConnection->getClusterName().c_str()))) - (*i)->m_centralServerConnection->send(message,true); + (*i)->m_centralServerConnection->send(message, true); } } @@ -1924,9 +1915,9 @@ bool LoginServer::areAllClustersUp() const { if (m_clusterList.empty()) return false; - + ClusterListType::const_iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { if (!(NON_NULL(*i)->m_readyForPlayers)) return false; @@ -1936,16 +1927,15 @@ bool LoginServer::areAllClustersUp() const // ---------------------------------------------------------------------- -void LoginServer::getAllClusterNamesAndIDs( std::map< std::string, uint32 > &results ) const +void LoginServer::getAllClusterNamesAndIDs(std::map< std::string, uint32 > &results) const { results.clear(); - for (ClusterListType::const_iterator i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (ClusterListType::const_iterator i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { - if( !*i ) + if (!*i) continue; - results[ (*i)->m_clusterName ] = (*i)->m_clusterId; + results[(*i)->m_clusterName] = (*i)->m_clusterId; } - } // ---------------------------------------------------------------------- @@ -1953,22 +1943,22 @@ void LoginServer::getAllClusterNamesAndIDs( std::map< std::string, uint32 > &res void LoginServer::getClusterIds(std::vector result) { result.reserve(m_clusterList.size()); - for (ClusterListType::const_iterator i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (ClusterListType::const_iterator i = m_clusterList.begin(); i != m_clusterList.end(); ++i) result.push_back(NON_NULL(*i)->m_clusterId); } // ---------------------------------------------------------------------- -void LoginServer::setClusterInfoByName( const std::string &name, const std::string &branch, int changelist, const std::string &networkVersion ) +void LoginServer::setClusterInfoByName(const std::string &name, const std::string &branch, int changelist, const std::string &networkVersion) { - ClusterListEntry *entry = findClusterByName( name ); - - if ( entry ) + ClusterListEntry *entry = findClusterByName(name); + + if (entry) { - entry->m_branch = branch; - entry->m_changelist = changelist; + entry->m_branch = branch; + entry->m_changelist = changelist; entry->m_networkVersion = networkVersion; } } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/application/LoginServer/src/shared/TaskEnableCharacter.cpp b/engine/server/application/LoginServer/src/shared/TaskEnableCharacter.cpp index b72adbe3..209d613d 100755 --- a/engine/server/application/LoginServer/src/shared/TaskEnableCharacter.cpp +++ b/engine/server/application/LoginServer/src/shared/TaskEnableCharacter.cpp @@ -18,12 +18,13 @@ // ====================================================================== TaskEnableCharacter::TaskEnableCharacter(StationId &stationId, const NetworkId &characterId, const std::string &whoRequested, bool enabled, uint32 clusterId) : - TaskRequest(), - m_stationId(stationId), - m_characterId(characterId), - m_whoRequested(whoRequested), - m_enabled(enabled), - m_clusterId(clusterId) + TaskRequest(), + m_stationId(stationId), + m_characterId(characterId), + m_whoRequested(whoRequested), + m_enabled(enabled), + m_clusterId(clusterId), + m_result(0) { } @@ -32,16 +33,15 @@ TaskEnableCharacter::TaskEnableCharacter(StationId &stationId, const NetworkId & bool TaskEnableCharacter::process(DB::Session *session) { EnableCharacterQuery qry; - qry.station_id=static_cast(m_stationId); - qry.character_id=m_characterId; + qry.station_id = static_cast(m_stationId); + qry.character_id = m_characterId; qry.enabled.setValue(m_enabled); bool rval = session->exec(&qry); - + qry.done(); m_result = qry.result.getValue(); return rval; - } // ---------------------------------------------------------------------- @@ -51,34 +51,34 @@ void TaskEnableCharacter::onComplete() std::string message; switch (m_result) { - case 1: - if (m_enabled) - message = "Character enabled."; - else - message = "Character disabled."; - break; + case 1: + if (m_enabled) + message = "Character enabled."; + else + message = "Character disabled."; + break; - case 2: - message = "Could not find Character"; - break; + case 2: + message = "Could not find Character"; + break; - default: - message = "The database returned an unknown error code"; - break; + default: + message = "The database returned an unknown error code"; + break; } - + GenericValueTypeMessage > reply("EnableCharacterReplyMessage", - std::make_pair(m_whoRequested, message)); + std::make_pair(m_whoRequested, message)); LoginServer::getInstance().sendToCluster(m_clusterId, reply); } // ---------------------------------------------------------------------- TaskEnableCharacter::EnableCharacterQuery::EnableCharacterQuery() : - Query(), - station_id(), - character_id(), - enabled() + Query(), + station_id(), + character_id(), + enabled() { } @@ -87,7 +87,6 @@ TaskEnableCharacter::EnableCharacterQuery::EnableCharacterQuery() : void TaskEnableCharacter::EnableCharacterQuery::getSQL(std::string &sql) { sql = std::string("begin :result := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.enable_disable_character(:station_id, :character_id, :enabled); end;"; - } // ---------------------------------------------------------------------- @@ -116,4 +115,4 @@ DB::Query::QueryMode TaskEnableCharacter::EnableCharacterQuery::getExecutionMode return MODE_PROCEXEC; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/application/LoginServer/src/shared/TaskGetAccountForPurge.cpp b/engine/server/application/LoginServer/src/shared/TaskGetAccountForPurge.cpp index bc755e82..061b1c4d 100755 --- a/engine/server/application/LoginServer/src/shared/TaskGetAccountForPurge.cpp +++ b/engine/server/application/LoginServer/src/shared/TaskGetAccountForPurge.cpp @@ -30,7 +30,7 @@ namespace TaskGetAccountForPurgeNamespace virtual QueryMode getExecutionMode() const; StationId getAccount() const; - + private: DB::BindableLong m_account; DB::BindableLong m_min_age; @@ -46,8 +46,9 @@ using namespace TaskGetAccountForPurgeNamespace; // ====================================================================== TaskGetAccountForPurge::TaskGetAccountForPurge(int purgePhase) : - DB::TaskRequest(), - m_purgePhase(purgePhase) + DB::TaskRequest(), + m_purgePhase(purgePhase), + m_account(0) { } @@ -71,12 +72,11 @@ void TaskGetAccountForPurge::onComplete() // ====================================================================== - GetAccountForPurgeQuery::GetAccountForPurgeQuery(int purgePhase, int minAge) : - Query(), - m_account(), - m_min_age(minAge), - m_purge_phase(purgePhase) + Query(), + m_account(), + m_min_age(minAge), + m_purge_phase(purgePhase) { } @@ -84,7 +84,7 @@ GetAccountForPurgeQuery::GetAccountForPurgeQuery(int purgePhase, int minAge) : void GetAccountForPurgeQuery::getSQL(std::string &sql) { - sql=std::string("begin :account := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"purge_process.get_account_for_purge(:purge_phase, :min_age); end;"; + sql = std::string("begin :account := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "purge_process.get_account_for_purge(:purge_phase, :min_age); end;"; } // ---------------------------------------------------------------------- @@ -121,4 +121,4 @@ StationId GetAccountForPurgeQuery::getAccount() const return 0; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/application/LoginServer/src/shared/TaskGetValidationData.cpp b/engine/server/application/LoginServer/src/shared/TaskGetValidationData.cpp index d646b57c..735e9e7a 100755 --- a/engine/server/application/LoginServer/src/shared/TaskGetValidationData.cpp +++ b/engine/server/application/LoginServer/src/shared/TaskGetValidationData.cpp @@ -46,8 +46,8 @@ namespace TaskGetValidationDataNamespace public: GetCompletedTutorialQuery(StationId stationId); - DB::BindableLong station_id; - DB::BindableBool completed_tutorial; + DB::BindableLong station_id; + DB::BindableBool completed_tutorial; virtual void getSQL(std::string &sql); virtual bool bindParameters(); @@ -72,13 +72,13 @@ namespace TaskGetValidationDataNamespace std::string getEventId() const; uint32 getClusterId() const; NetworkId const getCharacterId() const; - + private: DB::BindableLong station_id; DB::BindableString<100> event_id; DB::BindableLong cluster_id; DB::BindableNetworkId character_id; - + private: //disable GetConsumedRewardEventsQuery(); GetConsumedRewardEventsQuery(const GetConsumedRewardEventsQuery&); @@ -119,13 +119,13 @@ namespace TaskGetValidationDataNamespace DB::BindableLong cluster_id; //lint !e1925 // public data member DB::BindableLong result; //lint !e1925 // public data member - virtual void getSQL (std::string &sql); - virtual bool bindParameters (); - virtual bool bindColumns (); - virtual QueryMode getExecutionMode () const; + virtual void getSQL(std::string &sql); + virtual bool bindParameters(); + virtual bool bindColumns(); + virtual QueryMode getExecutionMode() const; private: //disable - IsClusterAtLimitQuery (const IsClusterAtLimitQuery&); + IsClusterAtLimitQuery(const IsClusterAtLimitQuery&); IsClusterAtLimitQuery &operator= (const IsClusterAtLimitQuery&); }; } @@ -134,36 +134,37 @@ using namespace TaskGetValidationDataNamespace; // ====================================================================== -TaskGetValidationData::TaskGetValidationData (StationId stationId, int clusterGroupId, uint32 clusterId, unsigned int track, uint32 subscriptionBits) : - TaskRequest(), - m_stationId(stationId), - m_clusterGroupId(clusterGroupId), - m_clusterId(clusterId), - m_openCharacterSlots(4,0), - m_canSkipTutorial(false), - m_track(track), - m_subscriptionBits(subscriptionBits), - m_transferRequest(0), - m_transferRequestSourceCharacterTemplateId(0), - m_consumedRewardEvents(), - m_claimedRewardItems() +TaskGetValidationData::TaskGetValidationData(StationId stationId, int clusterGroupId, uint32 clusterId, unsigned int track, uint32 subscriptionBits) : + TaskRequest(), + m_stationId(stationId), + m_clusterGroupId(clusterGroupId), + m_clusterId(clusterId), + m_openCharacterSlots(4, 0), + m_canSkipTutorial(false), + m_track(track), + m_subscriptionBits(subscriptionBits), + m_transferRequest(0), + m_transferRequestSourceCharacterTemplateId(0), + m_consumedRewardEvents(), + m_claimedRewardItems() { } // ---------------------------------------------------------------------- TaskGetValidationData::TaskGetValidationData(const TransferRequestMoveValidation & request, int clusterGroupId, uint32 clusterId) : - TaskRequest(), - m_stationId(request.getDestinationStationId()), - m_clusterGroupId(clusterGroupId), - m_clusterId(clusterId), - m_openCharacterSlots(4,0), - m_canSkipTutorial(true), - m_track(request.getTrack()), - m_transferRequest(0), - m_transferRequestSourceCharacterTemplateId(request.getSourceCharacterTemplateId()), - m_consumedRewardEvents(), - m_claimedRewardItems() + TaskRequest(), + m_stationId(request.getDestinationStationId()), + m_clusterGroupId(clusterGroupId), + m_clusterId(clusterId), + m_openCharacterSlots(4, 0), + m_canSkipTutorial(true), + m_track(request.getTrack()), + m_transferRequest(0), + m_transferRequestSourceCharacterTemplateId(request.getSourceCharacterTemplateId()), + m_consumedRewardEvents(), + m_claimedRewardItems(), + m_subscriptionBits(0) { Archive::ByteStream bs; request.pack(bs); @@ -205,10 +206,10 @@ bool TaskGetValidationData::process(DB::Session *session) qry.cluster_id = static_cast(m_clusterId); int rowsFetched; - if (! (session->exec(&qry))) + if (!(session->exec(&qry))) return false; while ((rowsFetched = qry.fetch()) > 0) - m_openCharacterSlots[static_cast(qry.character_type_id.getValue())]=qry.num_open_slots.getValue(); + m_openCharacterSlots[static_cast(qry.character_type_id.getValue())] = qry.num_open_slots.getValue(); qry.done(); if (rowsFetched < 0) return false; @@ -219,12 +220,12 @@ bool TaskGetValidationData::process(DB::Session *session) GetValidationDataQuery qry; qry.station_id = static_cast(m_stationId); qry.cluster_id = static_cast(m_clusterId); - + int rowsFetched; - if (! (session->exec(&qry))) + if (!(session->exec(&qry))) return false; while ((rowsFetched = qry.fetch()) > 0) - m_openCharacterSlots[static_cast(qry.character_type_id.getValue())]=qry.num_open_slots.getValue(); + m_openCharacterSlots[static_cast(qry.character_type_id.getValue())] = qry.num_open_slots.getValue(); qry.done(); if (rowsFetched < 0) return false; @@ -254,7 +255,7 @@ bool TaskGetValidationData::process(DB::Session *session) qryGetCharacters.character_name.getValue(characterName); if (characterName == m_transferRequest->getSourceCharacter()) { - qryGetCharacters.object_template_id.getValue(m_transferRequestSourceCharacterTemplateId); + qryGetCharacters.object_template_id.getValue(m_transferRequestSourceCharacterTemplateId); break; } } @@ -267,13 +268,13 @@ bool TaskGetValidationData::process(DB::Session *session) { GetConsumedRewardEventsQuery eventQuery(m_stationId); int rowsFetched; - if (! (session->exec(&eventQuery))) + if (!(session->exec(&eventQuery))) return false; while ((rowsFetched = eventQuery.fetch()) > 0) { // If the event was claimed on this cluster, tell the cluster the network ID of the character that claimed it. - // If claimed on another cluster, hide the network ID because it's not meaningful - NetworkId const characterId = eventQuery.getClusterId()==m_clusterId ? eventQuery.getCharacterId() : NetworkId::cms_invalid; + // If claimed on another cluster, hide the network ID because it's not meaningful + NetworkId const characterId = eventQuery.getClusterId() == m_clusterId ? eventQuery.getCharacterId() : NetworkId::cms_invalid; m_consumedRewardEvents.push_back(std::make_pair(characterId, eventQuery.getEventId())); } eventQuery.done(); @@ -281,11 +282,11 @@ bool TaskGetValidationData::process(DB::Session *session) return false; GetClaimedRewardItemsQuery itemQuery(m_stationId); - if (! (session->exec(&itemQuery))) + if (!(session->exec(&itemQuery))) return false; while ((rowsFetched = itemQuery.fetch()) > 0) { - NetworkId const characterId = itemQuery.getClusterId()==m_clusterId ? itemQuery.getCharacterId() : NetworkId::cms_invalid; + NetworkId const characterId = itemQuery.getClusterId() == m_clusterId ? itemQuery.getCharacterId() : NetworkId::cms_invalid; m_claimedRewardItems.push_back(std::make_pair(characterId, itemQuery.getItemId())); } itemQuery.done(); @@ -294,12 +295,12 @@ bool TaskGetValidationData::process(DB::Session *session) // check to see if the account can skip the tutorial or not GetCompletedTutorialQuery tutorialQuery(m_stationId); - if (! (session->exec(&tutorialQuery))) + if (!(session->exec(&tutorialQuery))) return false; while ((rowsFetched = tutorialQuery.fetch()) > 0) { tutorialQuery.completed_tutorial.getValue(m_canSkipTutorial); - } + } tutorialQuery.done(); if (rowsFetched < 0) return false; @@ -311,21 +312,21 @@ bool TaskGetValidationData::process(DB::Session *session) void TaskGetValidationData::onComplete() { - bool canCreateNormal=false; - bool canCreateJedi=false; + bool canCreateNormal = false; + bool canCreateJedi = false; if (m_openCharacterSlots[1] > 0) - canCreateNormal=true; + canCreateNormal = true; if (m_openCharacterSlots[2] > 0 && m_openCharacterSlots[3] > 0) - canCreateJedi=true; + canCreateJedi = true; // check to see if character creation has been disabled for the cluster if (ConfigLoginServer::isCharacterCreationDisabled(LoginServer::getInstance().getClusterNameById(m_clusterId))) { - canCreateNormal=false; - canCreateJedi=false; + canCreateNormal = false; + canCreateJedi = false; } - if(m_transferRequest) + if (m_transferRequest) { LoginServer::getInstance().validateAccountForTransfer(*m_transferRequest, m_clusterId, m_transferRequestSourceCharacterTemplateId, canCreateNormal, false); } @@ -339,7 +340,7 @@ void TaskGetValidationData::onComplete() void GetValidationDataQuery::getSQL(std::string &sql) { - sql = std::string("begin :rc := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"login.get_open_character_slots(:station_id,:cluster_id); end;"; + sql = std::string("begin :rc := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.get_open_character_slots(:station_id,:cluster_id); end;"; } // ---------------------------------------------------------------------- @@ -347,9 +348,9 @@ void GetValidationDataQuery::getSQL(std::string &sql) bool GetValidationDataQuery::bindParameters() { if (!bindParameter(station_id)) return false; - if (!bindParameter(cluster_id)) return false; + if (!bindParameter(cluster_id)) return false; - return true; + return true; } // ---------------------------------------------------------------------- @@ -372,11 +373,11 @@ DB::Query::QueryMode GetValidationDataQuery::getExecutionMode() const // ---------------------------------------------------------------------- GetValidationDataQuery::GetValidationDataQuery() : - Query(), - station_id(), - cluster_id(), - character_type_id(), - num_open_slots() + Query(), + station_id(), + cluster_id(), + character_type_id(), + num_open_slots() { } @@ -384,7 +385,7 @@ GetValidationDataQuery::GetValidationDataQuery() : void GetCompletedTutorialQuery::getSQL(std::string &sql) { - sql = std::string("begin :rc := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"login.get_completed_tutorial(:station_id); end;"; + sql = std::string("begin :rc := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.get_completed_tutorial(:station_id); end;"; } // ---------------------------------------------------------------------- @@ -393,7 +394,7 @@ bool GetCompletedTutorialQuery::bindParameters() { if (!bindParameter(station_id)) return false; - return true; + return true; } // ---------------------------------------------------------------------- @@ -415,20 +416,20 @@ DB::Query::QueryMode GetCompletedTutorialQuery::getExecutionMode() const // ---------------------------------------------------------------------- GetCompletedTutorialQuery::GetCompletedTutorialQuery(StationId stationId) : - DB::Query(), - station_id(stationId), - completed_tutorial(false) + DB::Query(), + station_id(stationId), + completed_tutorial(false) { } // ====================================================================== GetConsumedRewardEventsQuery::GetConsumedRewardEventsQuery(StationId stationId) : - DB::Query(), - station_id(static_cast(stationId)), - event_id(), - cluster_id(), - character_id() + DB::Query(), + station_id(static_cast(stationId)), + event_id(), + cluster_id(), + character_id() { } @@ -436,7 +437,7 @@ GetConsumedRewardEventsQuery::GetConsumedRewardEventsQuery(StationId stationId) void GetConsumedRewardEventsQuery::getSQL(std::string &sql) { - sql = std::string("begin :result := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"login.get_consumed_reward_events(:station_id); end;"; + sql = std::string("begin :result := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.get_consumed_reward_events(:station_id); end;"; } // ---------------------------------------------------------------------- @@ -488,11 +489,11 @@ NetworkId const GetConsumedRewardEventsQuery::getCharacterId() const // ====================================================================== GetClaimedRewardItemsQuery::GetClaimedRewardItemsQuery(StationId stationId) : - DB::Query(), - station_id(static_cast(stationId)), - item_id(), - cluster_id(), - character_id() + DB::Query(), + station_id(static_cast(stationId)), + item_id(), + cluster_id(), + character_id() { } @@ -500,7 +501,7 @@ GetClaimedRewardItemsQuery::GetClaimedRewardItemsQuery(StationId stationId) : void GetClaimedRewardItemsQuery::getSQL(std::string &sql) { - sql = std::string("begin :result := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"login.get_claimed_reward_items(:station_id); end;"; + sql = std::string("begin :result := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.get_claimed_reward_items(:station_id); end;"; } // ---------------------------------------------------------------------- @@ -552,9 +553,9 @@ NetworkId const GetClaimedRewardItemsQuery::getCharacterId() const // ====================================================================== IsClusterAtLimitQuery::IsClusterAtLimitQuery() : -Query(), -cluster_id(), -result() + Query(), + cluster_id(), + result() { } @@ -562,7 +563,7 @@ result() void IsClusterAtLimitQuery::getSQL(std::string &sql) { - sql = std::string("begin :result := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"login.is_cluster_at_limit(:cluster_id); end;"; + sql = std::string("begin :result := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.is_cluster_at_limit(:cluster_id); end;"; } // ---------------------------------------------------------------------- @@ -588,4 +589,4 @@ DB::Query::QueryMode IsClusterAtLimitQuery::getExecutionMode() const return MODE_PROCEXEC; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/application/PlanetServer/src/shared/PlanetProxyObject.cpp b/engine/server/application/PlanetServer/src/shared/PlanetProxyObject.cpp index 648debd0..5e6a0338 100755 --- a/engine/server/application/PlanetServer/src/shared/PlanetProxyObject.cpp +++ b/engine/server/application/PlanetServer/src/shared/PlanetProxyObject.cpp @@ -32,42 +32,43 @@ MemoryBlockManager* PlanetProxyObject::memoryBlockManager; // ====================================================================== -PlanetProxyObject::PlanetProxyObject (const NetworkId &objectId) : - m_objectId(objectId), - m_containedBy(NetworkId::cms_invalid), - m_x(0), - m_y(0), - m_z(0), - m_authoritativeServer(0), - m_lastReportedServer(0), - m_interestRadius(0), - m_quadtreeNode(nullptr), - m_authTransferTimeMs(Clock::timeMs()), - m_contents(nullptr), - m_level(0), - m_hibernating(false), - m_templateCrc(0), - m_aiActivity(-1), - m_creationType(-1) +PlanetProxyObject::PlanetProxyObject(const NetworkId &objectId) : + m_objectId(objectId), + m_containedBy(NetworkId::cms_invalid), + m_x(0), + m_y(0), + m_z(0), + m_authoritativeServer(0), + m_lastReportedServer(0), + m_interestRadius(0), + m_quadtreeNode(nullptr), + m_authTransferTimeMs(Clock::timeMs()), + m_contents(nullptr), + m_level(0), + m_hibernating(false), + m_templateCrc(0), + m_aiActivity(-1), + m_creationType(-1), + m_objectTypeTag(0) { } // ---------------------------------------------------------------------- -PlanetProxyObject::~PlanetProxyObject () +PlanetProxyObject::~PlanetProxyObject() { if (PlanetServer::getInstance().isWatcherPresent()) { outputStatusToAll(true); } - m_quadtreeNode=0; + m_quadtreeNode = 0; if (m_contents) { - for (std::vector::const_iterator i=m_contents->begin(); i!=m_contents->end(); ++i) - WARNING(true,("Object %s was deleted without removing contained object %s first",m_objectId.getValueString().c_str(), i->getValueString().c_str())); + for (std::vector::const_iterator i = m_contents->begin(); i != m_contents->end(); ++i) + WARNING(true, ("Object %s was deleted without removing contained object %s first", m_objectId.getValueString().c_str(), i->getValueString().c_str())); delete m_contents; - m_contents=0; + m_contents = 0; } } @@ -79,7 +80,7 @@ PlanetProxyObject::~PlanetProxyObject () */ void PlanetProxyObject::update(int x, int y, int z, NetworkId containedBy, uint32 authoritativeServer, int interestRadius, int objectTypeTag, int const level, bool const hibernating, uint32 const templateCrc, int const aiActivity, int const creationType) { - WARNING_DEBUG_FATAL(m_objectId==NetworkId::cms_invalid,("Object ID was 0.")); + WARNING_DEBUG_FATAL(m_objectId == NetworkId::cms_invalid, ("Object ID was 0.")); bool watcherUpdateNeeded = false; m_level = level; @@ -88,64 +89,64 @@ void PlanetProxyObject::update(int x, int y, int z, NetworkId containedBy, uint3 m_aiActivity = aiActivity; m_creationType = creationType; - if ((m_authoritativeServer != 0 ) && (authoritativeServer != m_authoritativeServer) && (containedBy == NetworkId::cms_invalid)) + if ((m_authoritativeServer != 0) && (authoritativeServer != m_authoritativeServer) && (containedBy == NetworkId::cms_invalid)) { static unsigned long authTransferSanityCheckTimeMs = ConfigPlanetServer::getAuthTransferSanityCheckTimeMs(); - if (Clock::timeMs()-m_authTransferTimeMs > authTransferSanityCheckTimeMs) + if (Clock::timeMs() - m_authTransferTimeMs > authTransferSanityCheckTimeMs) { DEBUG_WARNING(true, ("Resending auth transfer for %s to %lu due to receiving a stale position update.", m_objectId.getValueString().c_str(), authoritativeServer)); sendAuthorityChange(authoritativeServer, m_authoritativeServer, false); return; } if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading",("Ignoring update for %s from %lu because server was not authoritative.",m_objectId.getValueString().c_str(),authoritativeServer)); + LOG("ObjectLoading", ("Ignoring update for %s from %lu because server was not authoritative.", m_objectId.getValueString().c_str(), authoritativeServer)); return; } - - if (interestRadius>ConfigPlanetServer::getMaxInterestRadius()) + + if (interestRadius > ConfigPlanetServer::getMaxInterestRadius()) interestRadius = ConfigPlanetServer::getMaxInterestRadius(); - - if (interestRadius>0 && PlanetServer::getInstance().isInTutorialMode()) + + if (interestRadius > 0 && PlanetServer::getInstance().isInTutorialMode()) interestRadius = 1; - if (containedBy!=NetworkId::cms_invalid) + if (containedBy != NetworkId::cms_invalid) { // get coordinates from container PlanetProxyObject *container = Scene::getInstance().findObjectByID(containedBy); if (container) { - x=container->getX(); - y=container->getY(); - z=container->getZ(); + x = container->getX(); + y = container->getY(); + z = container->getZ(); } else { - LOG("PlanetUpdate",("Game server said object %s was contained by object %s, but we could not find the container.",m_objectId.getValueString().c_str(),containedBy.getValueString().c_str())); + LOG("PlanetUpdate", ("Game server said object %s was contained by object %s, but we could not find the container.", m_objectId.getValueString().c_str(), containedBy.getValueString().c_str())); containedBy = NetworkId::cms_invalid; // so that we'll try again when the object moves again, in case we just got objects out-of-order from the game server } } - + std::vector oldProxyList; - Node *newNode=Scene::getInstance().findNodeByPosition(x,z); + Node *newNode = Scene::getInstance().findNodeByPosition(x, z); NOT_NULL(newNode); - if (newNode!=m_quadtreeNode || m_interestRadius != interestRadius || m_authoritativeServer != authoritativeServer || m_containedBy != containedBy) + if (newNode != m_quadtreeNode || m_interestRadius != interestRadius || m_authoritativeServer != authoritativeServer || m_containedBy != containedBy) { watcherUpdateNeeded = true; // For debugging, update the contents of the containers - if (ConfigPlanetServer::getEnableContentsChecking() && (m_containedBy!=containedBy)) + if (ConfigPlanetServer::getEnableContentsChecking() && (m_containedBy != containedBy)) updateContentsTracking(containedBy); - + bool const firstUpdate = (m_quadtreeNode == nullptr); - if (m_quadtreeNode!=nullptr) // if this is the first update for this object, m_quadtreeNode will be nullptr because it hasn't been placed anywhere yet + if (m_quadtreeNode != nullptr) // if this is the first update for this object, m_quadtreeNode will be nullptr because it hasn't been placed anywhere yet { removeServerStatistics(); // remember old list of proxies getServers(oldProxyList); - + // remove from the old location m_quadtreeNode->removeObject(this); @@ -153,34 +154,34 @@ void PlanetProxyObject::update(int x, int y, int z, NetworkId containedBy, uint3 LOG("ObjectLoading", ("unsubscribing nodes for object id=[%s]", m_objectId.getValueString().c_str())); unsubscribeSurroundingNodes(false); } - + // update data - m_quadtreeNode=newNode; - m_x=x; - m_y=y; - m_z=z; - m_interestRadius=interestRadius; + m_quadtreeNode = newNode; + m_x = x; + m_y = y; + m_z = z; + m_interestRadius = interestRadius; m_objectTypeTag = objectTypeTag; - m_authoritativeServer=authoritativeServer; - m_containedBy=containedBy; + m_authoritativeServer = authoritativeServer; + m_containedBy = containedBy; // make sure the destination is loaded if (!newNode->isLoaded()) { if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading",("Loading node %s because object %s entered it.",newNode->getDebugNodeString().c_str(), m_objectId.getValueString().c_str())); + LOG("ObjectLoading", ("Loading node %s because object %s entered it.", newNode->getDebugNodeString().c_str(), m_objectId.getValueString().c_str())); newNode->load(); } - + // check if we're on the right server if (!isAuthorityOk()) { uint32 preferredServer = m_quadtreeNode->getPreferredServer(); - if (m_containedBy==NetworkId::cms_invalid) + if (m_containedBy == NetworkId::cms_invalid) { if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading",("Changing authority for object %s from %lu to %lu because node %s is authoritative on that server.", - m_objectId.getValueString().c_str(),m_authoritativeServer,preferredServer,m_quadtreeNode->getDebugNodeString().c_str())); + LOG("ObjectLoading", ("Changing authority for object %s from %lu to %lu because node %s is authoritative on that server.", + m_objectId.getValueString().c_str(), m_authoritativeServer, preferredServer, m_quadtreeNode->getDebugNodeString().c_str())); changeAuthority(preferredServer, false, false); // changes m_authoritativeServer and sends message // we received the object for the first time, and we had to @@ -192,8 +193,8 @@ void PlanetProxyObject::update(int x, int y, int z, NetworkId containedBy, uint3 } else { - WARNING(true,("Programmer bug: Object %s is in container %s, which is node %s. The object should be authoritative on server %i but it is authoritative on server %i.", - m_objectId.getValueString().c_str(),m_containedBy.getValueString().c_str(),m_quadtreeNode->getDebugNodeString().c_str(), m_authoritativeServer, preferredServer)); + WARNING(true, ("Programmer bug: Object %s is in container %s, which is node %s. The object should be authoritative on server %i but it is authoritative on server %i.", + m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str(), m_quadtreeNode->getDebugNodeString().c_str(), m_authoritativeServer, preferredServer)); } } @@ -204,30 +205,30 @@ void PlanetProxyObject::update(int x, int y, int z, NetworkId containedBy, uint3 { if (ConfigPlanetServer::getLogObjectLoading()) LOG("ObjectLoading", ("subscribing nodes for object id=[%s]", m_objectId.getValueString().c_str())); - subscribeSurroundingNodes(); + subscribeSurroundingNodes(); } - + // check against new interested servers, and send proxy/unproxy as needed - if (m_containedBy==NetworkId::cms_invalid) // we don't manage proxies for containers + if (m_containedBy == NetworkId::cms_invalid) // we don't manage proxies for containers { std::vector newProxyList; getServers(newProxyList); - changeProxies(oldProxyList,newProxyList); + changeProxies(oldProxyList, newProxyList); } - + addServerStatistics(); - } + } else { if (m_interestRadius > 0 || (abs(m_x - x) > 25) || (abs(m_z - z) > 25)) watcherUpdateNeeded = true; } - + if (PlanetServer::getInstance().isWatcherPresent() && watcherUpdateNeeded) { - m_x=x; - m_y=y; - m_z=z; + m_x = x; + m_y = y; + m_z = z; m_objectTypeTag = objectTypeTag; outputStatusToAll(false); @@ -240,11 +241,11 @@ void PlanetProxyObject::unsubscribeSurroundingNodes(bool clearZeroSubscriptions) { if (m_interestRadius <= 0) return; - + Scene::NodeListType nodelist; - Scene::getInstance().findIntersection(nodelist,m_x,m_z,m_interestRadius); - - for (Scene::NodeListType::iterator i=nodelist.begin(); i!=nodelist.end(); ++i) + Scene::getInstance().findIntersection(nodelist, m_x, m_z, m_interestRadius); + + for (Scene::NodeListType::iterator i = nodelist.begin(); i != nodelist.end(); ++i) { (*i)->unsubscribeServer(m_authoritativeServer, 1, clearZeroSubscriptions); } @@ -253,20 +254,20 @@ void PlanetProxyObject::unsubscribeSurroundingNodes(bool clearZeroSubscriptions) // ---------------------------------------------------------------------- void PlanetProxyObject::subscribeSurroundingNodes() -{ +{ if (m_interestRadius <= 0) return; NOT_NULL(m_quadtreeNode); Scene::NodeListType nodelist; - Scene::getInstance().findIntersection(nodelist,m_x,m_z,m_interestRadius); - - for (Scene::NodeListType::iterator i=nodelist.begin(); i!=nodelist.end(); ++i) + Scene::getInstance().findIntersection(nodelist, m_x, m_z, m_interestRadius); + + for (Scene::NodeListType::iterator i = nodelist.begin(); i != nodelist.end(); ++i) { (*i)->subscribeServer(m_authoritativeServer, 1); uint32 serverId = (*i)->getPreferredServer(); if (serverId != m_authoritativeServer) - m_quadtreeNode->subscribeServer(serverId,0); // make sure if we can see them, they can see us + m_quadtreeNode->subscribeServer(serverId, 0); // make sure if we can see them, they can see us } } @@ -332,22 +333,22 @@ void PlanetProxyObject::unload(bool tellGameServer) if (m_quadtreeNode) m_quadtreeNode->removeObject(this); - Scene::getInstance().removeObjectFromMap(m_objectId,tellGameServer); + Scene::getInstance().removeObjectFromMap(m_objectId, tellGameServer); if (tellGameServer) { - PlanetServer::getInstance().unloadObject(m_objectId,m_authoritativeServer); + PlanetServer::getInstance().unloadObject(m_objectId, m_authoritativeServer); } removeServerStatistics(); - if (ConfigPlanetServer::getEnableContentsChecking() && m_containedBy!=NetworkId::cms_invalid) + if (ConfigPlanetServer::getEnableContentsChecking() && m_containedBy != NetworkId::cms_invalid) { PlanetProxyObject *container = Scene::getInstance().findObjectByID(m_containedBy); if (container) container->removeContainedObject(m_objectId); else - WARNING(true,("Unloading object %s in container %s, but the container could not be found.",m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str())); + WARNING(true, ("Unloading object %s in container %s, but the container could not be found.", m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str())); } } @@ -368,7 +369,7 @@ void PlanetProxyObject::outputStatus(WatcherConnection &conn, bool deleteObject) void PlanetProxyObject::outputStatusToAll(bool deleteObject) const { const PlanetServer::WatcherList &connections = PlanetServer::getInstance().getWatchers(); - for (PlanetServer::WatcherList::const_iterator i= connections.begin(); i!=connections.end(); ++i) + for (PlanetServer::WatcherList::const_iterator i = connections.begin(); i != connections.end(); ++i) { outputStatus(**i, deleteObject); } @@ -376,21 +377,21 @@ void PlanetProxyObject::outputStatusToAll(bool deleteObject) const // ---------------------------------------------------------------------- -/** +/** * Update the GameServerData with statistics about this object. */ void PlanetProxyObject::addServerStatistics() const { - GameServerData *data=PlanetServer::getInstance().getGameServerData(m_authoritativeServer); + GameServerData *data = PlanetServer::getInstance().getGameServerData(m_authoritativeServer); if (data) { data->adjustObjectCount(1); - if (m_interestRadius!=0) + if (m_interestRadius != 0) { data->adjustInterestObjectCount(1); if (isCreature()) data->adjustInterestCreatureObjectCount(1); - } + } } } @@ -402,15 +403,15 @@ void PlanetProxyObject::addServerStatistics() const */ void PlanetProxyObject::removeServerStatistics() const { - GameServerData *data=PlanetServer::getInstance().getGameServerData(m_authoritativeServer); + GameServerData *data = PlanetServer::getInstance().getGameServerData(m_authoritativeServer); if (data) { data->adjustObjectCount(-1); - if (m_interestRadius!=0) + if (m_interestRadius != 0) { data->adjustInterestObjectCount(-1); if (isCreature()) - data->adjustInterestCreatureObjectCount(-1); + data->adjustInterestCreatureObjectCount(-1); } } } @@ -423,7 +424,7 @@ void PlanetProxyObject::removeServerStatistics() const void PlanetProxyObject::install() { memoryBlockManager = new MemoryBlockManager("PlanetProxyObject::memoryBlockManager", true, sizeof(PlanetProxyObject), 0, 0, 0); - ExitChain::add(&remove, "PlanetProxyObject::remove"); + ExitChain::add(&remove, "PlanetProxyObject::remove"); } // ---------------------------------------------------------------------- @@ -461,7 +462,7 @@ void PlanetProxyObject::operator delete(void* pointer) void PlanetProxyObject::sendAuthorityChange(uint32 currentAuthServer, uint32 newAuthServer, bool handlingCrash) { - DEBUG_WARNING(!isAuthorityClean(), ("Object %s attempted to change authority before previous authority change was complete.",getObjectId().getValueString().c_str())); + DEBUG_WARNING(!isAuthorityClean(), ("Object %s attempted to change authority before previous authority change was complete.", getObjectId().getValueString().c_str())); SetAuthoritativeMessage const auth(getObjectId(), newAuthServer, false, handlingCrash, NetworkId::cms_invalid, Transform::identity, false); PlanetServer::getInstance().sendToGameServer(currentAuthServer, auth); @@ -473,7 +474,7 @@ void PlanetProxyObject::sendAuthorityChange(uint32 currentAuthServer, uint32 new void PlanetProxyObject::sendAddProxy(uint32 proxyServer) { if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading",("Gameserver %lu needs a proxy of object %s",proxyServer,m_objectId.getValueString().c_str())); + LOG("ObjectLoading", ("Gameserver %lu needs a proxy of object %s", proxyServer, m_objectId.getValueString().c_str())); if (isAuthorityClean()) { LoadObjectMessage const loadMsg(getObjectId(), proxyServer); @@ -491,15 +492,15 @@ void PlanetProxyObject::sendAddProxy(uint32 proxyServer) void PlanetProxyObject::sendRemoveProxy(uint32 proxyServer) { if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading",("Gameserver %lu no longer needs a proxy of object %s",proxyServer,m_objectId.getValueString().c_str())); + LOG("ObjectLoading", ("Gameserver %lu no longer needs a proxy of object %s", proxyServer, m_objectId.getValueString().c_str())); if (isAuthorityClean()) { - UnloadProxyMessage msg(getObjectId(),proxyServer); + UnloadProxyMessage msg(getObjectId(), proxyServer); PlanetServer::getInstance().sendToGameServer(m_authoritativeServer, msg); } else { - UnloadProxyMessage *msg = new UnloadProxyMessage(getObjectId(),proxyServer); + UnloadProxyMessage *msg = new UnloadProxyMessage(getObjectId(), proxyServer); PlanetServer::getInstance().queueMessageForObject(getObjectId(), msg); } } @@ -516,7 +517,7 @@ void PlanetProxyObject::onReceivedMessageFromServer(uint32 server) if (m_lastReportedServer != m_authoritativeServer && server == m_authoritativeServer) // we've received a message from the new authoritative server. Send queued messages: PlanetServer::getInstance().sendQueuedMessagesForObject(*this); - + m_lastReportedServer = server; } @@ -534,8 +535,8 @@ void PlanetProxyObject::getServers(std::vector &serverList) const } else { - PlanetProxyObject *container=Scene::getInstance().findObjectByID(m_containedBy); - WARNING_STRICT_FATAL(!container,("Object %s is in container %s, which couldn't be found",m_objectId.getValueString().c_str(),m_containedBy.getValueString().c_str())); + PlanetProxyObject *container = Scene::getInstance().findObjectByID(m_containedBy); + WARNING_STRICT_FATAL(!container, ("Object %s is in container %s, which couldn't be found", m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str())); if (container) effectiveNode = container->getNode(); else @@ -557,12 +558,12 @@ void PlanetProxyObject::getServers(std::vector &serverList) const void PlanetProxyObject::changeProxies(const std::vector &oldServers, const std::vector &newServers) { { - for (std::vector::const_iterator i=oldServers.begin(); i!=oldServers.end(); ++i) + for (std::vector::const_iterator i = oldServers.begin(); i != oldServers.end(); ++i) { if (*i != m_authoritativeServer) { bool removeNeeded = true; - for (std::vector::const_iterator j=newServers.begin(); j!=newServers.end(); ++j) + for (std::vector::const_iterator j = newServers.begin(); j != newServers.end(); ++j) { if (*i == *j) { @@ -576,12 +577,12 @@ void PlanetProxyObject::changeProxies(const std::vector &oldServers, con } } { - for (std::vector::const_iterator i=newServers.begin(); i!=newServers.end(); ++i) + for (std::vector::const_iterator i = newServers.begin(); i != newServers.end(); ++i) { if (*i != m_authoritativeServer) { bool addNeeded = true; - for (std::vector::const_iterator j=oldServers.begin(); j!=oldServers.end(); ++j) + for (std::vector::const_iterator j = oldServers.begin(); j != oldServers.end(); ++j) { if (*i == *j) { @@ -638,10 +639,10 @@ void PlanetProxyObject::addContainedObject(const NetworkId &theObject) { m_contents = new std::vector; } - for (std::vector::const_iterator i=m_contents->begin(); i!=m_contents->end(); ++i) + for (std::vector::const_iterator i = m_contents->begin(); i != m_contents->end(); ++i) { - if (*i==theObject) - WARNING(true,("Object %s was placed in container %s twice.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); + if (*i == theObject) + WARNING(true, ("Object %s was placed in container %s twice.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); } m_contents->push_back(theObject); } @@ -652,13 +653,13 @@ void PlanetProxyObject::removeContainedObject(const NetworkId &theObject) { if (!m_contents) { - WARNING(true,("Attempted to remove object %s from object %s, but that object has no contents.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); + WARNING(true, ("Attempted to remove object %s from object %s, but that object has no contents.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); return; } - std::vector::iterator newEnd=std::remove(m_contents->begin(), m_contents->end(), theObject); - if (newEnd==m_contents->end()) + std::vector::iterator newEnd = std::remove(m_contents->begin(), m_contents->end(), theObject); + if (newEnd == m_contents->end()) { - WARNING(true,("Attempted to remove object %s from object %s, but it was not in the container.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); + WARNING(true, ("Attempted to remove object %s from object %s, but it was not in the container.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); return; } m_contents->erase(newEnd, m_contents->end()); @@ -672,22 +673,22 @@ void PlanetProxyObject::removeContainedObject(const NetworkId &theObject) */ void PlanetProxyObject::updateContentsTracking(const NetworkId &newContainedBy) { - if (m_containedBy!=NetworkId::cms_invalid) + if (m_containedBy != NetworkId::cms_invalid) { PlanetProxyObject *container = Scene::getInstance().findObjectByID(m_containedBy); if (container) container->removeContainedObject(m_objectId); else - WARNING(true,("Removing object %s from container %s, but the container could not be found.",m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str())); + WARNING(true, ("Removing object %s from container %s, but the container could not be found.", m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str())); } - if (newContainedBy!=NetworkId::cms_invalid) + if (newContainedBy != NetworkId::cms_invalid) { PlanetProxyObject *container = Scene::getInstance().findObjectByID(newContainedBy); if (container) container->addContainedObject(m_objectId); else - WARNING(true,("Adding object %s to container %s, but the container could not be found.",m_objectId.getValueString().c_str(), newContainedBy.getValueString().c_str())); + WARNING(true, ("Adding object %s to container %s, but the container could not be found.", m_objectId.getValueString().c_str(), newContainedBy.getValueString().c_str())); } } @@ -695,7 +696,7 @@ void PlanetProxyObject::updateContentsTracking(const NetworkId &newContainedBy) bool PlanetProxyObject::isCreature() const { - return m_objectTypeTag==TAG(C,R,E,O); + return m_objectTypeTag == TAG(C, R, E, O); } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverDatabase/src/shared/DeleteCharacterCustomPersistStep.cpp b/engine/server/library/serverDatabase/src/shared/DeleteCharacterCustomPersistStep.cpp index 67ec7bd2..3463861b 100755 --- a/engine/server/library/serverDatabase/src/shared/DeleteCharacterCustomPersistStep.cpp +++ b/engine/server/library/serverDatabase/src/shared/DeleteCharacterCustomPersistStep.cpp @@ -16,8 +16,9 @@ // ====================================================================== DeleteCharacterCustomPersistStep::DeleteCharacterCustomPersistStep(uint32 stationId, const NetworkId &characterId) : - m_characterId(characterId), - m_stationId(stationId) + m_characterId(characterId), + m_stationId(stationId), + m_resultCode(0) { } @@ -33,12 +34,12 @@ bool DeleteCharacterCustomPersistStep::beforePersist(DB::Session *) bool DeleteCharacterCustomPersistStep::afterPersist(DB::Session *session) { DeleteCharacterQuery qry(m_stationId, m_characterId); - - if (! (session->exec(&qry))) + + if (!(session->exec(&qry))) return false; qry.done(); - m_resultCode=qry.result.getValue(); + m_resultCode = qry.result.getValue(); return true; } @@ -48,18 +49,18 @@ void DeleteCharacterCustomPersistStep::onComplete() { if (m_resultCode == 2) { - GenericValueTypeMessage msg("ReleaseCharacterNameByIdMessage",m_characterId); - DatabaseProcess::getInstance().sendToAllGameServers(msg,true); + GenericValueTypeMessage msg("ReleaseCharacterNameByIdMessage", m_characterId); + DatabaseProcess::getInstance().sendToAllGameServers(msg, true); } } // ====================================================================== DeleteCharacterCustomPersistStep::DeleteCharacterQuery::DeleteCharacterQuery(uint32 stationId, const NetworkId &characterId) : - station_id(stationId), - character_id(characterId), - delete_minutes(ConfigServerDatabase::getCharacterImmediateDeleteMinutes()), - result() + station_id(stationId), + character_id(characterId), + delete_minutes(ConfigServerDatabase::getCharacterImmediateDeleteMinutes()), + result() { } @@ -67,7 +68,7 @@ DeleteCharacterCustomPersistStep::DeleteCharacterQuery::DeleteCharacterQuery(uin void DeleteCharacterCustomPersistStep::DeleteCharacterQuery::getSQL(std::string &sql) { - sql="begin :result := " + DatabaseProcess::getInstance().getSchemaQualifier() + "persister.delete_character (:station_id, :character_id, :delete_minutes); end;"; + sql = "begin :result := " + DatabaseProcess::getInstance().getSchemaQualifier() + "persister.delete_character (:station_id, :character_id, :delete_minutes); end;"; } // ---------------------------------------------------------------------- @@ -95,4 +96,4 @@ DB::Query::QueryMode DeleteCharacterCustomPersistStep::DeleteCharacterQuery::get return DB::Query::MODE_PROCEXEC; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverDatabase/src/shared/TaskCheckCharacterName.cpp b/engine/server/library/serverDatabase/src/shared/TaskCheckCharacterName.cpp index fbb863ff..a7e3f5fb 100755 --- a/engine/server/library/serverDatabase/src/shared/TaskCheckCharacterName.cpp +++ b/engine/server/library/serverDatabase/src/shared/TaskCheckCharacterName.cpp @@ -16,8 +16,9 @@ // ====================================================================== TaskCheckCharacterName::TaskCheckCharacterName(uint32 stationId, const Unicode::String &name) : - m_name(name), - m_stationId(stationId) + m_name(name), + m_stationId(stationId), + m_resultCode(0) { } @@ -26,11 +27,11 @@ TaskCheckCharacterName::TaskCheckCharacterName(uint32 stationId, const Unicode:: bool TaskCheckCharacterName::process(DB::Session *session) { CheckCharacterNameQuery qry(Unicode::wideToNarrow(m_name)); - + bool rval = session->exec(&qry); qry.done(); - m_resultCode=qry.result.getValue(); + m_resultCode = qry.result.getValue(); return rval; } @@ -38,14 +39,14 @@ bool TaskCheckCharacterName::process(DB::Session *session) void TaskCheckCharacterName::onComplete() { - DataLookup::getInstance().onCharacterNameChecked(m_stationId, m_name,m_resultCode); + DataLookup::getInstance().onCharacterNameChecked(m_stationId, m_name, m_resultCode); LOG("TraceCharacterCreation", ("%d TaskCheckCharacterName(%s) complete with result code %d", m_stationId, Unicode::wideToNarrow(m_name).c_str(), m_resultCode)); } // ====================================================================== TaskCheckCharacterName::CheckCharacterNameQuery::CheckCharacterNameQuery(const std::string &name) : - character_name(name) + character_name(name) { } @@ -53,7 +54,7 @@ TaskCheckCharacterName::CheckCharacterNameQuery::CheckCharacterNameQuery(const s void TaskCheckCharacterName::CheckCharacterNameQuery::getSQL(std::string &sql) { - sql="begin :result := " + DatabaseProcess::getInstance().getSchemaQualifier() + "datalookup.check_character_name (:name); end;"; + sql = "begin :result := " + DatabaseProcess::getInstance().getSchemaQualifier() + "datalookup.check_character_name (:name); end;"; } // ---------------------------------------------------------------------- @@ -79,4 +80,4 @@ DB::Query::QueryMode TaskCheckCharacterName::CheckCharacterNameQuery::getExecuti return DB::Query::MODE_PROCEXEC; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/command/CommandCppFuncs.cpp b/engine/server/library/serverGame/src/shared/command/CommandCppFuncs.cpp index 0478a3d6..54e165fb 100755 --- a/engine/server/library/serverGame/src/shared/command/CommandCppFuncs.cpp +++ b/engine/server/library/serverGame/src/shared/command/CommandCppFuncs.cpp @@ -146,20 +146,20 @@ namespace CommandCppFuncsNamespace { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; - + if (actorCreature == nullptr) return; - + ShipObject * const shipObject = actorCreature->getPilotedShip(); if (shipObject == nullptr) return; - + if (!shipObject->isSlotInstalled(ShipChassisSlotType::SCST_booster)) { Chat::sendSystemMessage(*actorCreature, SharedStringIds::no_booster, Unicode::emptyString); return; } - + if (!shipObject->isComponentFunctional(ShipChassisSlotType::SCST_booster)) { Chat::sendSystemMessage(*actorCreature, SharedStringIds::booster_disabled, Unicode::emptyString); @@ -167,7 +167,7 @@ namespace CommandCppFuncsNamespace } if (onOff && shipObject->getBoosterEnergyCurrent() < shipObject->getBoosterEnergyRechargeRate()) - { + { Chat::sendSystemMessage(*actorCreature, SharedStringIds::booster_low_energy, Unicode::emptyString); return; } @@ -196,16 +196,15 @@ namespace CommandCppFuncsNamespace return o; } - ShipObject *getAttachedShip(CreatureObject *creature) { // The "attached" ship is the ship which must move along with the creature. // This means if the creature is piloting, the ship is is piloting, // or the containing ship if the creature is the ship's owner. ShipObject * const ship = ShipObject::getContainingShipObject(creature); - if ( ship - && ( ship->getOwnerId() == creature->getNetworkId() - || creature->getPilotedShip() == ship)) + if (ship + && (ship->getOwnerId() == creature->getNetworkId() + || creature->getPilotedShip() == ship)) return ship; return 0; } @@ -263,9 +262,9 @@ namespace CommandCppFuncsNamespace for (ContainerConstIterator i = container->begin(); i != container->end(); ++i) { ServerObject const * const content = safe_cast((*i).getObject()); - if ( content - && content->getGameObjectType() == SharedObjectTemplate::GOT_data_ship_control_device - && !content->isBeingDestroyed()) + if (content + && content->getGameObjectType() == SharedObjectTemplate::GOT_data_ship_control_device + && !content->isBeingDestroyed()) { Container const * const scdContainer = ContainerInterface::getContainer(*content); if (scdContainer) @@ -310,20 +309,20 @@ namespace CommandCppFuncsNamespace { bool creatureIsContainedInPOBShip(CreatureObject const * creatureObject); void removeFromGroupAndCreatePOBGroup(GroupObject * groupToRemoveFrom, - GroupMemberParam const & leader, - GroupObject::GroupMemberParamVector & membersInsidePOB); + GroupMemberParam const & leader, + GroupObject::GroupMemberParamVector & membersInsidePOB); // The owner of the POB ship is not included in the inside POB member lists void separateGroupBasedOffofPOBShip(GroupObject * groupObj, - NetworkId const & ownerOfThePOBShipId, - NetworkId const & POBShipId, - GroupObject::GroupMemberParamVector & membersInsidePOB, - GroupObject::GroupMemberParamVector & membersOutsidePOB); + NetworkId const & ownerOfThePOBShipId, + NetworkId const & POBShipId, + GroupObject::GroupMemberParamVector & membersInsidePOB, + GroupObject::GroupMemberParamVector & membersOutsidePOB); TravelPoint const * getNearestTravelPoint(std::string const & planetName, Vector const & location, std::vector const & cityBanList, uint32 faction, bool starPortAndShuttleportOnly); } void triggerSpaceEjectPlayerFromShip(CreatureObject * creatureObject); - + int const cs_spaceSpeechMultiple = 10; } @@ -340,8 +339,8 @@ bool CommandCppFuncsNamespace::GroupHelpers::creatureIsContainedInPOBShip(Creatu // ---------------------------------------------------------------------- void CommandCppFuncsNamespace::GroupHelpers::removeFromGroupAndCreatePOBGroup(GroupObject * const groupToRemoveFrom, - GroupMemberParam const & leader, - GroupObject::GroupMemberParamVector & membersInsidePOB) + GroupMemberParam const & leader, + GroupObject::GroupMemberParamVector & membersInsidePOB) { if (groupToRemoveFrom != 0) { @@ -372,10 +371,10 @@ void CommandCppFuncsNamespace::GroupHelpers::removeFromGroupAndCreatePOBGroup(Gr // The owner of the POB ship is not included in the inside POB member lists void CommandCppFuncsNamespace::GroupHelpers::separateGroupBasedOffofPOBShip(GroupObject * const groupObj, - NetworkId const & ownerOfThePOBShipId, - NetworkId const & POBShipId, - GroupObject::GroupMemberParamVector & membersInsidePOB, - GroupObject::GroupMemberParamVector & membersOutsidePOB) + NetworkId const & ownerOfThePOBShipId, + NetworkId const & POBShipId, + GroupObject::GroupMemberParamVector & membersInsidePOB, + GroupObject::GroupMemberParamVector & membersOutsidePOB) { NOT_NULL(groupObj); @@ -417,7 +416,7 @@ void CommandCppFuncsNamespace::triggerSpaceEjectPlayerFromShip(CreatureObject * GameScriptObject * gameScriptObject = creatureObject->getScriptObject(); - if(gameScriptObject != 0) + if (gameScriptObject != 0) { ScriptParams scriptParams; IGNORE_RETURN(gameScriptObject->trigAllScripts(Scripting::TRIG_SPACE_EJECT_PLAYER_FROM_SHIP, scriptParams)); @@ -484,7 +483,7 @@ static const std::string OBJVAR_PLAYERS_CAN_ACCESS_CONTAINER("players_can_access static void sendProseMessage(const CreatureObject &actor, const ServerObject * const target, StringId const &stringId) { - Chat::sendSystemMessageSimple (actor, stringId, target); + Chat::sendSystemMessageSimple(actor, stringId, target); } // ====================================================================== @@ -504,7 +503,7 @@ static std::string nextStringParm(Unicode::String const &str, size_t &curpos) size_t endpos = 0; Unicode::String token; if (!Unicode::getFirstToken(str, curpos, endpos, token)) - return std::string (); + return std::string(); curpos = endpos; return Unicode::wideToNarrow(token); } @@ -540,7 +539,6 @@ static float nextFloatParm(Unicode::String const &str, size_t &curpos) return static_cast(strtod(nextStringParm(str, curpos).c_str(), nullptr)); } - // ---------------------------------------------------------------------- static bool nextBoolParm(Unicode::String const &str, size_t &curpos) @@ -552,11 +550,11 @@ static bool nextBoolParm(Unicode::String const &str, size_t &curpos) static Vector nextVectorParm(Unicode::String const &str, size_t &curpos) { - float x=nextFloatParm(str,curpos); - float y=nextFloatParm(str,curpos); - float z=nextFloatParm(str,curpos); + float x = nextFloatParm(str, curpos); + float y = nextFloatParm(str, curpos); + float z = nextFloatParm(str, curpos); - return Vector(x,y,z); + return Vector(x, y, z); } // ====================================================================== @@ -574,7 +572,7 @@ static void commandFuncConsoleAll(Command const &command, NetworkId const &actor Client *client = obj->getClient(); if (client && client->isGod()) { - LOG("CustomerService",("Avatar:%s executing command: %s", PlayerObject::getAccountDescription(client->getCharacterObjectId()).c_str(), Unicode::wideToNarrow(params).c_str())); + LOG("CustomerService", ("Avatar:%s executing command: %s", PlayerObject::getAccountDescription(client->getCharacterObjectId()).c_str(), Unicode::wideToNarrow(params).c_str())); ConsoleMgr::processString(Unicode::wideToNarrow(params), client, 0); } } @@ -736,7 +734,7 @@ static void commandFuncAdminSetGodMode(Command const &, NetworkId const &actor, // ---------------------------------------------------------------------- static void commandFuncResetCooldowns(Command const &, NetworkId const &actor, - NetworkId const &, Unicode::String const ¶ms) + NetworkId const &, Unicode::String const ¶ms) { CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (actorObj) @@ -748,7 +746,7 @@ static void commandFuncResetCooldowns(Command const &, NetworkId const &actor, // ---------------------------------------------------------------------- static void commandFuncSpewCommandQueue(Command const &, NetworkId const &actor, - NetworkId const &, Unicode::String const ¶ms) + NetworkId const &, Unicode::String const ¶ms) { CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (actorObj) @@ -780,14 +778,14 @@ static void commandFuncAdminKick(Command const &, NetworkId const &actor, // If the target is a ship, kick all the people in the ship std::vector passengers; shipObject->findAllPassengers(passengers, true); - for (std::vector::const_iterator i=passengers.begin(); i!=passengers.end(); ++i) + for (std::vector::const_iterator i = passengers.begin(); i != passengers.end(); ++i) { KickPlayer const kickMessage((*i)->getNetworkId(), "Admin Kick"); GameServer::getInstance().sendToConnectionServers(kickMessage); } } else - { + { KickPlayer const kickMessage(who, "Admin Kick"); GameServer::getInstance().sendToConnectionServers(kickMessage); } @@ -998,7 +996,7 @@ static void commandFuncShowCtsHistory(Command const &, NetworkId const &actor, N if (orderedCtsHistory.empty()) { - ConsoleMgr::broadcastString("No CTS history found.", clientObj); + ConsoleMgr::broadcastString("No CTS history found.", clientObj); } else { @@ -1086,10 +1084,10 @@ static void commandFuncAdminTeleport(Command const &, NetworkId const &actor, Ne if (actorClient) { char buffer[512]; - snprintf(buffer, sizeof(buffer)-1, "specified coordinate (%.2f,%.2f,%.2f) (%.2f,%.2f,%.2f) is out of range", + snprintf(buffer, sizeof(buffer) - 1, "specified coordinate (%.2f,%.2f,%.2f) (%.2f,%.2f,%.2f) is out of range", position_w.x, position_w.y, position_w.z, position_p.x, position_p.y, position_p.z); - buffer[sizeof(buffer)-1] = '\0'; + buffer[sizeof(buffer) - 1] = '\0'; ConsoleMgr::broadcastString(buffer, actorClient); } @@ -1192,7 +1190,7 @@ static void commandFuncAdminListGuilds(Command const &, NetworkId const &actor, static void commandFuncAdminEditBank(Command const &cmd, NetworkId const &actor, NetworkId const &target, Unicode::String const ¶ms) { - CreatureObject * actorCreature = safe_cast(ServerWorld::findObjectByNetworkId(actor)); + CreatureObject * actorCreature = safe_cast(ServerWorld::findObjectByNetworkId(actor)); CreatureObject * targetCreature = safe_cast(ServerWorld::findObjectByNetworkId(target)); if (!targetCreature || !actorCreature) { @@ -1201,7 +1199,7 @@ static void commandFuncAdminEditBank(Command const &cmd, NetworkId const &actor, } ServerObject * targetBank = targetCreature->getBankContainer(); - if(!targetBank) + if (!targetBank) { DEBUG_REPORT_LOG(true, ("Couldn't get bank for player %s.\n", target.getValueString().c_str())); return; @@ -1238,17 +1236,17 @@ static void commandFuncAdminEditBank(Command const &cmd, NetworkId const &actor, static void commandFuncAdminEditStats(Command const &, NetworkId const &actor, NetworkId const &target, Unicode::String const &) { - CreatureObject* const creatureActor = dynamic_cast(NetworkIdManager::getObjectById (actor)); + CreatureObject* const creatureActor = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (!creatureActor) { - WARNING (true, ("commandFuncAdminEditStats: nullptr actor")); + WARNING(true, ("commandFuncAdminEditStats: nullptr actor")); return; } - CreatureObject* const creatureTarget = dynamic_cast(NetworkIdManager::getObjectById (target)); + CreatureObject* const creatureTarget = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!creatureTarget) { - WARNING (true, ("commandFuncAdminEditStats: nullptr target")); + WARNING(true, ("commandFuncAdminEditStats: nullptr target")); return; } @@ -1262,17 +1260,17 @@ static void commandFuncAdminEditStats(Command const &, NetworkId const &actor, N static void commandFuncAdminEditAppearance(Command const &, NetworkId const &actor, NetworkId const &target, Unicode::String const &) { - CreatureObject* const creatureActor = dynamic_cast(NetworkIdManager::getObjectById (actor)); + CreatureObject* const creatureActor = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (!creatureActor) { - WARNING (true, ("commandFuncAdminEditAppearance: nullptr actor")); + WARNING(true, ("commandFuncAdminEditAppearance: nullptr actor")); return; } - CreatureObject* const creatureTarget = dynamic_cast(NetworkIdManager::getObjectById (target)); + CreatureObject* const creatureTarget = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!creatureTarget) { - WARNING (true, ("commandFuncAdminEditAppearance: nullptr target")); + WARNING(true, ("commandFuncAdminEditAppearance: nullptr target")); return; } @@ -1296,7 +1294,7 @@ static void commandFuncAdminCredits(Command const &, NetworkId const &, NetworkI // ---------------------------------------------------------------------- -static void commandFuncAdminGetStationName(Command const &, NetworkId const & actor, NetworkId const & target , Unicode::String const & params) +static void commandFuncAdminGetStationName(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) { const Object * const actorObj = NetworkIdManager::getObjectById(actor); if (actorObj && actorObj->asServerObject()) @@ -1304,25 +1302,25 @@ static void commandFuncAdminGetStationName(Command const &, NetworkId const & ac Client * const actorClient = actorObj->asServerObject()->getClient(); if (actorClient) { - const CreatureObject* creatureTarget = dynamic_cast(NetworkIdManager::getObjectById (target)); + const CreatureObject* creatureTarget = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!creatureTarget) { size_t pos = 0; NetworkId targetId(nextOidParm(params, pos)); - creatureTarget = dynamic_cast(NetworkIdManager::getObjectById (targetId)); + creatureTarget = dynamic_cast(NetworkIdManager::getObjectById(targetId)); } - if(!creatureTarget) + if (!creatureTarget) { ConsoleMgr::broadcastString("Could not resolve target passed to getStationName", actorClient); return; } const Client * const clientTarget = creatureTarget->getClient(); - if(clientTarget) + if (clientTarget) { const std::string & stationName = clientTarget->getAccountName(); - char buf [512]; + char buf[512]; snprintf(buf, 511, "Station name is: %s.", stationName.c_str()); ConsoleMgr::broadcastString(buf, actorClient); } @@ -1340,7 +1338,6 @@ static void commandFuncAdminGetStationName(Command const &, NetworkId const & ac static void commandFuncAuctionCreate(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { - /*printf("!!!!AUCTION: process = %i\n", (int)GameServer::getInstance().getProcessId()); printf("!!!!PID = %i\n", (int)getpid()); @@ -1385,8 +1382,6 @@ static void commandFuncAuctionCreateImmediate(Command const &, NetworkId const & CreatureObject *actorCreature = dynamic_cast(NetworkIdManager::getObjectById(actor)); - - TangibleObject *itemTangible = dynamic_cast(NetworkIdManager::getObjectById(itemId)); ServerObject *auctionContainer = dynamic_cast(NetworkIdManager::getObjectById(auctionContainerId)); @@ -1413,10 +1408,10 @@ static void commandFuncAuctionBid(Command const &, NetworkId const &actor, Netwo int maxProxyBid = nextIntParm(params, pos); CreatureObject *actorCreature = dynamic_cast(NetworkIdManager::getObjectById(actor)); - CommoditiesMarket::getAuctionDetails(*actorCreature, auctionId); - if (actorCreature) { + CommoditiesMarket::getAuctionDetails(*actorCreature, auctionId); + CommoditiesMarket::auctionBid( *actorCreature, auctionId.getValue(), @@ -1498,29 +1493,29 @@ static void commandFuncSocial(Command const &command, NetworkId const &actor, Ne if (obj) { Unicode::UnicodeStringVector sv; - Unicode::tokenize (params, sv); + Unicode::tokenize(params, sv); - if (sv.empty ()) + if (sv.empty()) { - WARNING (true, ("commandFuncSocial no params")); + WARNING(true, ("commandFuncSocial no params")); return; } - const std::string & socialName = Unicode::wideToNarrow (sv [0]); - const uint32 socialType = SocialsManager::getSocialTypeByName (socialName); + const std::string & socialName = Unicode::wideToNarrow(sv[0]); + const uint32 socialType = SocialsManager::getSocialTypeByName(socialName); if (!socialType) - WARNING (true, ("commandFuncSocial Bad social type specified: [%s]", socialName.c_str ())); + WARNING(true, ("commandFuncSocial Bad social type specified: [%s]", socialName.c_str())); else { bool animationOk = true; - bool textOk = true; - if (sv.size () > 1) - animationOk = !sv [1].empty () && sv [1][0] == '1'; - if (sv.size () > 2) - textOk = !sv [2].empty () && sv [2][0] == '1'; + bool textOk = true; + if (sv.size() > 1) + animationOk = !sv[1].empty() && sv[1][0] == '1'; + if (sv.size() > 2) + textOk = !sv[2].empty() && sv[2][0] == '1'; - obj->performSocial (target, socialType, animationOk, textOk); + obj->performSocial(target, socialType, animationOk, textOk); } } } @@ -1528,7 +1523,7 @@ static void commandFuncSocial(Command const &command, NetworkId const &actor, Ne // ---------------------------------------------------------------------- -static void commandFuncSocialInternal (Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) +static void commandFuncSocialInternal(Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { UNREF(command); if (actor != NetworkId::cms_invalid) @@ -1537,29 +1532,29 @@ static void commandFuncSocialInternal (Command const &command, NetworkId const & if (obj) { Unicode::UnicodeStringVector sv; - Unicode::tokenize (params, sv); + Unicode::tokenize(params, sv); - if (sv.size () < 2) + if (sv.size() < 2) { - WARNING (true, ("commandFuncSocial not enough params")); + WARNING(true, ("commandFuncSocial not enough params")); return; } - const NetworkId targetId (Unicode::wideToNarrow (sv [0])); - const uint32 socialType = atoi (Unicode::wideToNarrow (sv [1]).c_str()); + const NetworkId targetId(Unicode::wideToNarrow(sv[0])); + const uint32 socialType = atoi(Unicode::wideToNarrow(sv[1]).c_str()); if (!socialType) - WARNING (true, ("commandFuncSocialInternal Bad social type specified: '%d'", socialType)); + WARNING(true, ("commandFuncSocialInternal Bad social type specified: '%d'", socialType)); else { bool animationOk = true; - bool textOk = true; - if (sv.size () > 3) + bool textOk = true; + if (sv.size() > 3) { - animationOk = !sv [2].empty () && sv [2][0] == '1'; - textOk = !sv [3].empty () && sv [3][0] == '1'; + animationOk = !sv[2].empty() && sv[2][0] == '1'; + textOk = !sv[3].empty() && sv[3][0] == '1'; } - obj->performSocial (targetId, socialType, animationOk, textOk); + obj->performSocial(targetId, socialType, animationOk, textOk); } } } @@ -1567,7 +1562,7 @@ static void commandFuncSocialInternal (Command const &command, NetworkId const & //---------------------------------------------------------------------- -static void commandFuncSetMood (Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const & params) +static void commandFuncSetMood(Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const & params) { UNREF(command); if (actor != NetworkId::cms_invalid) @@ -1575,17 +1570,17 @@ static void commandFuncSetMood (Command const &command, NetworkId const &actor, CreatureObject * const obj = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (obj) { - const std::string moodName = Unicode::wideToNarrow (params); + const std::string moodName = Unicode::wideToNarrow(params); if (moodName == "none") { - obj->setMood (0); + obj->setMood(0); } else { - const uint32 moodType = MoodManager::getMoodByCanonicalName (moodName); + const uint32 moodType = MoodManager::getMoodByCanonicalName(moodName); if (moodType) - obj->setMood (moodType); + obj->setMood(moodType); } } } @@ -1593,7 +1588,7 @@ static void commandFuncSetMood (Command const &command, NetworkId const &actor, // ---------------------------------------------------------------------- -static void commandFuncSetMoodInternal (Command const &command, NetworkId const &actor, +static void commandFuncSetMoodInternal(Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { UNREF(command); @@ -1603,14 +1598,14 @@ static void commandFuncSetMoodInternal (Command const &command, NetworkId const if (obj) { const uint32 moodType = atoi(Unicode::wideToNarrow(params).c_str()); - obj->setMood (moodType); + obj->setMood(moodType); } } } //---------------------------------------------------------------------- -static void commandFuncRequestWaypointAtPosition (Command const &command, NetworkId const &actor, +static void commandFuncRequestWaypointAtPosition(Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { UNREF(command); @@ -1619,15 +1614,15 @@ static void commandFuncRequestWaypointAtPosition (Command const &command, Networ CreatureObject * const obj = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (obj) { - if(obj->isPlayerControlled()) + if (obj->isPlayerControlled()) { PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(obj); - if(playerObject) + if (playerObject) { size_t curpos = 0; uint8 color = static_cast(Waypoint::Blue); - std::string planet = nextStringParm (params, curpos); + std::string planet = nextStringParm(params, curpos); // the first parameter may be the name of the planet or an unsigned // int specifying the color of the waypoint, in which case the @@ -1636,8 +1631,8 @@ static void commandFuncRequestWaypointAtPosition (Command const &command, Networ // obfuscation to prevent player from manually entering the // requestWaypointAtPosition command and specifying the waypoint color char buffer[256]; - snprintf(buffer, sizeof(buffer)-1, "(^-,=+_)color_%s(,+-=_^)=", actor.getValueString().c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "(^-,=+_)color_%s(,+-=_^)=", actor.getValueString().c_str()); + buffer[sizeof(buffer) - 1] = '\0'; if (planet.find(buffer) == 0) { @@ -1654,18 +1649,18 @@ static void commandFuncRequestWaypointAtPosition (Command const &command, Networ planet = nextStringParm(params, curpos); } - const float x = nextFloatParm (params, curpos); - const float y = nextFloatParm (params, curpos); - const float z = nextFloatParm (params, curpos); - curpos = Unicode::skipWhitespace (params, curpos); + const float x = nextFloatParm(params, curpos); + const float y = nextFloatParm(params, curpos); + const float z = nextFloatParm(params, curpos); + curpos = Unicode::skipWhitespace(params, curpos); const std::string& sceneId = ServerWorld::getSceneId(); StringId s("planet_n", sceneId); - const Unicode::String & name = ((curpos != Unicode::String::npos) ? (params.substr (curpos)) : (Unicode::narrowToWide("@" + s.getCanonicalRepresentation()))); + const Unicode::String & name = ((curpos != Unicode::String::npos) ? (params.substr(curpos)) : (Unicode::narrowToWide("@" + s.getCanonicalRepresentation()))); // get player object - Waypoint waypoint(playerObject->createWaypoint(Location(Vector(x, y, z), NetworkId::cms_invalid, Location::getCrcBySceneName(planet)),false)); + Waypoint waypoint(playerObject->createWaypoint(Location(Vector(x, y, z), NetworkId::cms_invalid, Location::getCrcBySceneName(planet)), false)); if (waypoint.isValid()) { waypoint.setName(name); // Waypoints are a bit like smart pointers, so this is changing the data on the PlayerObject, not just on a local variable @@ -1695,14 +1690,13 @@ static void commandFuncSpatialChatInternal(Command const &, NetworkId const &act ServerObject * const obj = safe_cast(NetworkIdManager::getObjectById(actor)); if (obj) { - size_t curpos = 0; - const NetworkId targetId (nextStringParm (params, curpos)); - const int chatType = nextIntParm (params, curpos); - const int mood = nextIntParm (params, curpos); - int flags = nextIntParm (params, curpos); - int language = nextIntParm (params, curpos); + const NetworkId targetId(nextStringParm(params, curpos)); + const int chatType = nextIntParm(params, curpos); + const int mood = nextIntParm(params, curpos); + int flags = nextIntParm(params, curpos); + int language = nextIntParm(params, curpos); // Verify the language parameter @@ -1711,29 +1705,29 @@ static void commandFuncSpatialChatInternal(Command const &, NetworkId const &act language = GameLanguageManager::getBasicLanguageId(); } - curpos = Unicode::skipWhitespace (params, curpos); + curpos = Unicode::skipWhitespace(params, curpos); if (curpos == Unicode::String::npos) { - DEBUG_WARNING (true, ("empty string in spatial chat")); + DEBUG_WARNING(true, ("empty string in spatial chat")); return; } - const size_t nullpos = params.find (static_cast(0), curpos); + const size_t nullpos = params.find(static_cast(0), curpos); Unicode::String text; Unicode::String oob; if (nullpos != Unicode::String::npos) { - text = params.substr (curpos, nullpos - curpos); - oob = params.substr (nullpos + 1); + text = params.substr(curpos, nullpos - curpos); + oob = params.substr(nullpos + 1); } else { // Strip any color codes the user may have entered - text = TextIterator(params.substr (curpos)).getPrintableText(); + text = TextIterator(params.substr(curpos)).getPrintableText(); } if (text.empty()) @@ -1741,19 +1735,19 @@ static void commandFuncSpatialChatInternal(Command const &, NetworkId const &act return; } - const bool isPrivate = SpatialChatManager::isPrivate (chatType); + const bool isPrivate = SpatialChatManager::isPrivate(chatType); if (isPrivate) flags |= MessageQueueSpatialChat::F_isPrivate; if (chatType != -1 && mood != -1 && flags != -1 && curpos != Unicode::String::npos) { - uint16 volume = SpatialChatManager::getVolume (chatType); + uint16 volume = SpatialChatManager::getVolume(chatType); CreatureObject * const creatureActor = obj->asCreatureObject(); //speak cs_spaceSpeechMultiple times when piloting a ship - if(creatureActor && creatureActor->getPilotedShip()) + if (creatureActor && creatureActor->getPilotedShip()) volume *= cs_spaceSpeechMultiple; // track amount of spatial chat for the character @@ -1786,15 +1780,15 @@ static void commandFuncSpatialChatInternal(Command const &, NetworkId const &act // character allowed to talk obj->speakText( MessageQueueSpatialChat( - CachedNetworkId(actor), - CachedNetworkId(targetId), - text, - volume, - static_cast(chatType), - static_cast(mood), - flags, - language, - oob)); + CachedNetworkId(actor), + CachedNetworkId(targetId), + text, + volume, + static_cast(chatType), + static_cast(mood), + flags, + language, + oob)); } else if (!squelched && (ConfigServerGame::getChatSpamNotifyPlayerWhenLimitedIntervalSeconds() > 0) && obj->getClient()) { @@ -1834,65 +1828,64 @@ static void commandFuncSpatialChat(Command const &, NetworkId const &actor, Netw Unicode::String moodTypeName; Unicode::String flagsString; - if (!Unicode::getFirstToken (params, curpos, curpos, chatTypeName) || curpos == Unicode::String::npos) + if (!Unicode::getFirstToken(params, curpos, curpos, chatTypeName) || curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSpatialChat (no chat type)")); + WARNING(true, ("Not enough arguments to commandFuncSpatialChat (no chat type)")); return; } - if (!Unicode::getFirstToken (params, ++curpos, curpos, moodTypeName) || curpos == Unicode::String::npos) + if (!Unicode::getFirstToken(params, ++curpos, curpos, moodTypeName) || curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSpatialChat (no mood type)")); + WARNING(true, ("Not enough arguments to commandFuncSpatialChat (no mood type)")); return; } - if (!Unicode::getFirstToken (params, ++curpos, curpos, flagsString) || curpos == Unicode::String::npos) + if (!Unicode::getFirstToken(params, ++curpos, curpos, flagsString) || curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSpatialChat (no flags)")); + WARNING(true, ("Not enough arguments to commandFuncSpatialChat (no flags)")); return; } curpos = Unicode::skipWhitespace(params, ++curpos); - const std::string & narrow_chatTypeName = Unicode::wideToNarrow (chatTypeName); - const std::string & narrow_moodTypeName = Unicode::wideToNarrow (moodTypeName); + const std::string & narrow_chatTypeName = Unicode::wideToNarrow(chatTypeName); + const std::string & narrow_moodTypeName = Unicode::wideToNarrow(moodTypeName); - const uint32 chatType = SpatialChatManager::getChatTypeByName (narrow_chatTypeName); + const uint32 chatType = SpatialChatManager::getChatTypeByName(narrow_chatTypeName); - curpos = Unicode::skipWhitespace (params, curpos); + curpos = Unicode::skipWhitespace(params, curpos); if (curpos == Unicode::String::npos) { - DEBUG_WARNING (true, ("empty string in spatial chat")); + DEBUG_WARNING(true, ("empty string in spatial chat")); return; } - size_t nullpos = params.find (static_cast(0), curpos); + size_t nullpos = params.find(static_cast(0), curpos); Unicode::String text; Unicode::String oob; if (nullpos != Unicode::String::npos) { - text = params.substr (curpos, nullpos - curpos); - oob = params.substr (nullpos + 1); + text = params.substr(curpos, nullpos - curpos); + oob = params.substr(nullpos + 1); } else { - text = params.substr (curpos); - + text = params.substr(curpos); } if (curpos != Unicode::String::npos) { - const uint32 moodType = MoodManager::getMoodByCanonicalName (narrow_moodTypeName); - const bool isPrivate = SpatialChatManager::isPrivate (chatType); + const uint32 moodType = MoodManager::getMoodByCanonicalName(narrow_moodTypeName); + const bool isPrivate = SpatialChatManager::isPrivate(chatType); - uint32 flags = atoi (Unicode::wideToNarrow (flagsString).c_str ()); + uint32 flags = atoi(Unicode::wideToNarrow(flagsString).c_str()); if (isPrivate) flags |= MessageQueueSpatialChat::F_isPrivate; - const uint16 volume = SpatialChatManager::getVolume (chatType); + const uint16 volume = SpatialChatManager::getVolume(chatType); // track amount of spatial chat for the character bool allowToSpeak = true; @@ -1924,15 +1917,15 @@ static void commandFuncSpatialChat(Command const &, NetworkId const &actor, Netw // character allowed to talk obj->speakText( MessageQueueSpatialChat( - CachedNetworkId(actor), - CachedNetworkId(targetId), - text, - volume, - static_cast(chatType), - static_cast(moodType), - flags, - 0, - oob)); + CachedNetworkId(actor), + CachedNetworkId(targetId), + text, + volume, + static_cast(chatType), + static_cast(moodType), + flags, + 0, + oob)); } else if (!squelched && (ConfigServerGame::getChatSpamNotifyPlayerWhenLimitedIntervalSeconds() > 0) && obj->getClient()) { @@ -1949,7 +1942,7 @@ static void commandFuncSpatialChat(Command const &, NetworkId const &actor, Netw } } else - WARNING (true, ("Invalid empty output string in commandFuncSpatialChat")); + WARNING(true, ("Invalid empty output string in commandFuncSpatialChat")); } } } @@ -2071,31 +2064,31 @@ static void commandFuncSystemMessage(Command const &, NetworkId const &, Network Unicode::String targetTypeStr; Unicode::String targetIdStr; - if (!Unicode::getFirstToken (params, curpos, curpos, targetTypeStr) || curpos == Unicode::String::npos) + if (!Unicode::getFirstToken(params, curpos, curpos, targetTypeStr) || curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing int value)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing int value)")); return; } - if (!Unicode::getFirstToken (params, ++curpos, curpos, targetIdStr) || curpos == Unicode::String::npos) + if (!Unicode::getFirstToken(params, ++curpos, curpos, targetIdStr) || curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing bitflags)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing bitflags)")); return; } if (curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing msg)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing msg)")); return; } curpos = Unicode::skipWhitespace(params, ++curpos); - Unicode::String output = params.substr (curpos); + Unicode::String output = params.substr(curpos); - if (output.empty ()) + if (output.empty()) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing msg)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing msg)")); return; } @@ -2103,11 +2096,11 @@ static void commandFuncSystemMessage(Command const &, NetworkId const &, Network std::string targetId = Unicode::wideToNarrow(targetIdStr); static const Unicode::String oob; - if(targetType == "Player") + if (targetType == "Player") { Chat::sendInstantMessage("SYSTEM", targetId, output, oob); } - else if(targetType == "ChatChannel") + else if (targetType == "ChatChannel") { Chat::sendToRoom("SYSTEM", targetId, output, oob); } @@ -2118,32 +2111,32 @@ static void commandFuncSystemMessage(Command const &, NetworkId const &, Network static void commandFuncSetWaypointActiveStatus(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const ¶ms) { CachedNetworkId actorId(actor); - WARNING(! actorId.getObject(), ("commandSetWaypointActiveStatus: Could not get an object for actor id %s\n", actor.getValueString().c_str())); - if(actorId.getObject()) + WARNING(!actorId.getObject(), ("commandSetWaypointActiveStatus: Could not get an object for actor id %s\n", actor.getValueString().c_str())); + if (actorId.getObject()) { CreatureObject * creature = dynamic_cast(actorId.getObject()); - if(creature) + if (creature) { - if(creature->isPlayerControlled()) + if (creature->isPlayerControlled()) { PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(creature); - if(playerObject) + if (playerObject) { Waypoint w = playerObject->getWaypoint(target); if (w.isValid()) { Unicode::String status; size_t curpos = 0; - if (!Unicode::getFirstToken (params, curpos, curpos, status)) + if (!Unicode::getFirstToken(params, curpos, curpos, status)) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing int value)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing int value)")); return; } - if(status == Unicode::narrowToWide("on")) + if (status == Unicode::narrowToWide("on")) { w.setActive(true); } - else if(status == Unicode::narrowToWide("off")) + else if (status == Unicode::narrowToWide("off")) { w.setActive(false); } @@ -2159,25 +2152,25 @@ static void commandFuncSetWaypointActiveStatus(Command const &, NetworkId const static void commandFuncSetWaypointName(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const ¶ms) { CachedNetworkId actorId(actor); - WARNING(! actorId.getObject(), ("commandFuncSetWaypointName: Could not get an object for actor id %s\n", actor.getValueString().c_str())); - if(actorId.getObject()) + WARNING(!actorId.getObject(), ("commandFuncSetWaypointName: Could not get an object for actor id %s\n", actor.getValueString().c_str())); + if (actorId.getObject()) { CreatureObject * creature = dynamic_cast(actorId.getObject()); - if(creature) + if (creature) { - if(creature->isPlayerControlled()) + if (creature->isPlayerControlled()) { PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(creature); - if(playerObject) + if (playerObject) { Waypoint w = playerObject->getWaypoint(target); if (w.isValid()) { Unicode::String name; size_t curpos = 0; - if (!Unicode::getFirstToken (params, curpos, curpos, name)) + if (!Unicode::getFirstToken(params, curpos, curpos, name)) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing text value)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing text value)")); return; } w.setName(params); @@ -2198,8 +2191,8 @@ static void commandSetPosture(Command const &command, NetworkId const &actor, Ne CreatureController * const controller = dynamic_cast(actorId.getObject()->getController()); if (controller != nullptr) { - CreatureObject * const creature = safe_cast(actorId.getObject()); - NOT_NULL (creature); + CreatureObject * const creature = safe_cast(actorId.getObject()); + NOT_NULL(creature); Postures::Enumerator const posture = creature->getPosture(); // send the creature's posture to it @@ -2211,7 +2204,7 @@ static void commandSetPosture(Command const &command, NetworkId const &actor, Ne GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_ALL_CLIENT - ); + ); // Ensure the chair sitting state is off if the player is not sitting. if (posture != Postures::Sitting) @@ -2239,7 +2232,7 @@ static void commandFuncJumpServer(Command const &command, NetworkId const &actor GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_ALL_CLIENT - ); + ); } } } @@ -2414,9 +2407,9 @@ static void resolveDuelParticipants(CreatureObject &actor, TangibleObject &targe // Dueling a ship // actorFlagObj is the containing ship of the actor if he owns it ShipObject * const actorShip = ShipObject::getContainingShipObject(&actor); - if ( actorShip - && actorShip->isPlayerShip() - && actor.getNetworkId() == actorShip->getOwnerId()) + if (actorShip + && actorShip->isPlayerShip() + && actor.getNetworkId() == actorShip->getOwnerId()) actorFlagObj = actorShip; // targetMessageObj is the owner of the target ship if (targetShip->isPlayerShip()) @@ -2481,7 +2474,7 @@ static void commandFuncDuel(Command const &, NetworkId const &actor, NetworkId c return; } - if(targetObj->getObjVars().hasItem("hologram_performer")) + if (targetObj->getObjVars().hasItem("hologram_performer")) { sendProseMessage(*actorObj, targetMessageObj, CommandStringId::SID_DUEL_NOT_HOLOGRAM); } @@ -2505,58 +2498,56 @@ static void commandFuncDuel(Command const &, NetworkId const &actor, NetworkId c // Call their Script Triggers ServerObject* serverActor = actorObj->asServerObject(); - if(serverActor) + if (serverActor) { ScriptParams params; params.addParam(actor); params.addParam(target); - if(serverActor->getScriptObject()) + if (serverActor->getScriptObject()) { IGNORE_RETURN(serverActor->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_START, params)); - } } ServerObject* serverTarget = targetObj->asServerObject(); - if(serverTarget) + if (serverTarget) { ScriptParams params; params.addParam(actor); params.addParam(target); - if(serverTarget->getScriptObject()) + if (serverTarget->getScriptObject()) { - IGNORE_RETURN( serverTarget->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_START, params)); + IGNORE_RETURN(serverTarget->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_START, params)); } } /// End script triggers. - } else { // Duel Request // Call their Script Triggers ServerObject* serverActor = actorObj->asServerObject(); - if(serverActor) + if (serverActor) { ScriptParams params; params.addParam(actor); params.addParam(target); - if(serverActor->getScriptObject()) + if (serverActor->getScriptObject()) { - if( serverActor->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_REQUEST, params) == SCRIPT_OVERRIDE ) + if (serverActor->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_REQUEST, params) == SCRIPT_OVERRIDE) return; } } ServerObject* serverTarget = targetObj->asServerObject(); - if(serverTarget) + if (serverTarget) { ScriptParams params; params.addParam(actor); params.addParam(target); - if(serverTarget->getScriptObject()) + if (serverTarget->getScriptObject()) { - if( serverTarget->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_REQUEST, params) == SCRIPT_OVERRIDE ) + if (serverTarget->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_REQUEST, params) == SCRIPT_OVERRIDE) return; } } @@ -2597,16 +2588,16 @@ static void commandFuncEndDuel(Command const &, NetworkId const &actor, NetworkI // notify script that the duel has ended because of the EndDuel command { - ScriptParams params; - params.addParam(targetObj->getNetworkId(), "target"); - ScriptDictionaryPtr dictionary; - GameScriptObject::makeScriptDictionary(params, dictionary); - if (dictionary.get() != nullptr) - { - dictionary->serialize(); - MessageToQueue::getInstance().sendMessageToJava(actorFlagObj->getNetworkId(), - "endDuelCommandNotification", dictionary->getSerializedData(), 0, false); - } + ScriptParams params; + params.addParam(targetObj->getNetworkId(), "target"); + ScriptDictionaryPtr dictionary; + GameScriptObject::makeScriptDictionary(params, dictionary); + if (dictionary.get() != nullptr) + { + dictionary->serialize(); + MessageToQueue::getInstance().sendMessageToJava(actorFlagObj->getNetworkId(), + "endDuelCommandNotification", dictionary->getSerializedData(), 0, false); + } } { @@ -2617,7 +2608,7 @@ static void commandFuncEndDuel(Command const &, NetworkId const &actor, NetworkI if (dictionary.get() != nullptr) { dictionary->serialize(); - MessageToQueue::getInstance().sendMessageToJava(targetObj->getNetworkId(), + MessageToQueue::getInstance().sendMessageToJava(targetObj->getNetworkId(), "endDuelCommandNotification", dictionary->getSerializedData(), 0, false); } } @@ -2650,7 +2641,7 @@ static void commandFuncHarvesterActivate(Command const &, NetworkId const &actor CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); HarvesterInstallationObject *targetObj = dynamic_cast(NetworkIdManager::getObjectById(target)); if (targetObj && actorObj && targetObj->isOnAdminList(*actorObj)) - targetObj->activate(actor); + targetObj->activate(actor); } // ---------------------------------------------------------------------- @@ -2660,8 +2651,7 @@ static void commandFuncHarvesterDeactivate(Command const &, NetworkId const &act CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); HarvesterInstallationObject *targetObj = dynamic_cast(NetworkIdManager::getObjectById(target)); if (targetObj && actorObj &&targetObj->isOnAdminList(*actorObj)) - targetObj->deactivate(); - + targetObj->deactivate(); } // ---------------------------------------------------------------------- @@ -2671,7 +2661,7 @@ static void commandFuncHarvesterHarvest(Command const &, NetworkId const &actor, CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); HarvesterInstallationObject *targetObj = dynamic_cast(NetworkIdManager::getObjectById(target)); if (targetObj && actorObj && targetObj->isOnAdminList(*actorObj)) - targetObj->harvest(); + targetObj->harvest(); } // ---------------------------------------------------------------------- @@ -2701,14 +2691,14 @@ static void commandFuncHarvesterMakeCrate(Command const &, NetworkId const &acto { CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); HarvesterInstallationObject *targetObj = dynamic_cast(NetworkIdManager::getObjectById(target)); - size_t pos=0; - const NetworkId resourceId = nextOidParm(params,pos); - const int amount = nextIntParm(params,pos); - const bool discard = nextBoolParm(params,pos); - const uint8 sequenceId = static_cast(nextIntParm(params,pos)); + size_t pos = 0; + const NetworkId resourceId = nextOidParm(params, pos); + const int amount = nextIntParm(params, pos); + const bool discard = nextBoolParm(params, pos); + const uint8 sequenceId = static_cast(nextIntParm(params, pos)); if (targetObj && actorObj && targetObj->isOnAdminList(*actorObj)) - targetObj->emptyHopper(actor,resourceId,amount,discard,sequenceId); + targetObj->emptyHopper(actor, resourceId, amount, discard, sequenceId); } // ---------------------------------------------------------------------- @@ -2727,14 +2717,13 @@ static void commandFuncResourceContainerTransfer(Command const &, NetworkId cons CreatureObject * const player = safe_cast(ServerWorld::findObjectByNetworkId(actor)); if (!player) return; - + ResourceContainerObject *sourceObj = dynamic_cast(NetworkIdManager::getObjectById(target)); size_t pos = 0; - NetworkId destId = nextOidParm(params,pos); + NetworkId destId = nextOidParm(params, pos); ResourceContainerObject *destObj = dynamic_cast(NetworkIdManager::getObjectById(destId)); - int amount = nextIntParm(params,pos); + int amount = nextIntParm(params, pos); - if (!sourceObj || !destObj || amount <= 0) return; @@ -2749,7 +2738,7 @@ static void commandFuncResourceContainerTransfer(Command const &, NetworkId cons ContainerInterface::sendContainerMessageToClient(*player, error, destObj); return; } - + sourceObj->transferTo(*destObj, amount); } @@ -2768,7 +2757,7 @@ static void commandFuncRequestSurvey(Command const &, NetworkId const &actor, Ne if (actorObj && actorObj->getClient()) { size_t curpos = 0; - Unicode::String resourceName = Unicode::narrowToWide(nextStringParm (params, curpos)); + Unicode::String resourceName = Unicode::narrowToWide(nextStringParm(params, curpos)); ScriptParams params; params.addParam(actor); @@ -2789,7 +2778,7 @@ static void commandFuncRequestCoreSample(Command const &, NetworkId const &actor if (actorObj && actorObj->getClient()) { size_t curpos = 0; - Unicode::String resourceName = Unicode::narrowToWide(nextStringParm (params, curpos)); + Unicode::String resourceName = Unicode::narrowToWide(nextStringParm(params, curpos)); ScriptParams params; params.addParam(actor); @@ -2815,19 +2804,19 @@ static void commandFuncResourceContainerSplit(Command const &, NetworkId const & return; size_t pos = 0; - const int amount = nextIntParm(params,pos); - const CachedNetworkId destContainer (nextOidParm(params,pos)); - const int arrangementId = nextIntParm(params,pos); - const Vector & newLocation = nextVectorParm(params,pos); + const int amount = nextIntParm(params, pos); + const CachedNetworkId destContainer(nextOidParm(params, pos)); + const int arrangementId = nextIntParm(params, pos); + const Vector & newLocation = nextVectorParm(params, pos); Container::ContainerErrorCode error = Container::CEC_Success; if (!player->canManipulateObject(*sourceObj, true, true, true, 10.0f, error)) { ContainerInterface::sendContainerMessageToClient(*player, error, sourceObj); } - else if (!sourceObj->splitContainer(amount,destContainer,arrangementId,newLocation, safe_cast(NetworkIdManager::getObjectById(actor)))) + else if (!sourceObj->splitContainer(amount, destContainer, arrangementId, newLocation, safe_cast(NetworkIdManager::getObjectById(actor)))) { - ContainerInterface::sendContainerMessageToClient(*player, Container::CEC_Full, safe_cast(destContainer.getObject ())); + ContainerInterface::sendContainerMessageToClient(*player, Container::CEC_Full, safe_cast(destContainer.getObject())); } } @@ -2844,8 +2833,8 @@ static void commandFuncFactoryCrateSplit(Command const &, NetworkId const &actor return; size_t pos = 0; - const int amount = nextIntParm(params,pos); - const CachedNetworkId destContainerId (nextOidParm(params,pos)); + const int amount = nextIntParm(params, pos); + const CachedNetworkId destContainerId(nextOidParm(params, pos)); ServerObject * destContainer = safe_cast(destContainerId.getObject()); if (destContainer == nullptr || ContainerInterface::getVolumeContainer(*destContainer) == nullptr) { @@ -2873,9 +2862,9 @@ static void commandFuncPermissionListModify(Command const &, NetworkId const &ac if (actorObj && actorObj->getClient()) { size_t curpos = 0; - const Unicode::String & playerName = Unicode::narrowToWide(nextStringParm (params, curpos)); - const Unicode::String & listName = Unicode::narrowToWide(nextStringParm (params, curpos)); - const Unicode::String & action = Unicode::narrowToWide(nextStringParm (params, curpos)); + const Unicode::String & playerName = Unicode::narrowToWide(nextStringParm(params, curpos)); + const Unicode::String & listName = Unicode::narrowToWide(nextStringParm(params, curpos)); + const Unicode::String & action = Unicode::narrowToWide(nextStringParm(params, curpos)); ScriptParams params; params.addParam(actor); @@ -2927,8 +2916,8 @@ static void commandFuncHarvesterGetResourceData(Command const &, NetworkId const //------------------------------------------------------------------------------------------ static void commandFuncTransferItem(Command const &, NetworkId const &actor, NetworkId const &target, Unicode::String const & params) { - ServerObject * const item = ServerWorld::findObjectByNetworkId(target); - ServerObject * const playerSo = ServerWorld::findObjectByNetworkId(actor); + ServerObject * const item = ServerWorld::findObjectByNetworkId(target); + ServerObject * const playerSo = ServerWorld::findObjectByNetworkId(actor); if (!playerSo || !item) { @@ -2945,7 +2934,7 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net size_t curpos = 0; const NetworkId & destId = nextOidParm(params, curpos); - const int arrangement = nextIntParm(params, curpos); + const int arrangement = nextIntParm(params, curpos); const Vector & pos = nextVectorParm(params, curpos); Transform t; t.setPosition_p(pos); @@ -2999,10 +2988,10 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net if (!canManipulateTarget) { - if(errorCode == Container::CEC_NoPermission) + if (errorCode == Container::CEC_NoPermission) { Object * parentObject = ContainerInterface::getContainedByObject(*item); - if(parentObject && parentObject->asServerObject() && parentObject->asServerObject()->asTangibleObject() + if (parentObject && parentObject->asServerObject() && parentObject->asServerObject()->asTangibleObject() && parentObject->asServerObject()->asTangibleObject()->isLocked()) { ContainerInterface::sendContainerMessageToClient(*player, errorCode, parentObject->asServerObject()); @@ -3015,50 +3004,48 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net //-- don't transfer from/to factory crates { - if (destination && destination->getGameObjectType () == SharedObjectTemplate::GOT_misc_factory_crate) + if (destination && destination->getGameObjectType() == SharedObjectTemplate::GOT_misc_factory_crate) return; - const ServerObject * const containedBy = safe_cast(ContainerInterface::getContainedByObject (*item)); + const ServerObject * const containedBy = safe_cast(ContainerInterface::getContainedByObject(*item)); - if (containedBy && containedBy->getGameObjectType () == SharedObjectTemplate::GOT_misc_factory_crate) + if (containedBy && containedBy->getGameObjectType() == SharedObjectTemplate::GOT_misc_factory_crate) return; } // If our destination is a locked container, make sure we can access it. bool lockedDestContainer = false; { - if(destination && destination->asTangibleObject() && destination->asTangibleObject()->isLocked()) + if (destination && destination->asTangibleObject() && destination->asTangibleObject()->isLocked()) { lockedDestContainer = true; TangibleObject * destTangible = destination->asTangibleObject(); - if(!destTangible->isUserOnAccessList(player->getNetworkId()) && !destTangible->isGuildOnAccessList(player->getGuildId()) + if (!destTangible->isUserOnAccessList(player->getNetworkId()) && !destTangible->isGuildOnAccessList(player->getGuildId()) && player->getClient() && !player->getClient()->isGod()) { ContainerInterface::sendContainerMessageToClient(*player, Container::CEC_NoPermission, destination); return; } } - } { // No Drag and Drop while using Loot rules (especially random). const ServerObject * source = getFirstCreatureContainer(item); - if(source && source->asCreatureObject() && source->asCreatureObject()->isDead() && destination) + if (source && source->asCreatureObject() && source->asCreatureObject()->isDead() && destination) { const ServerObject* dest = getFirstCreatureContainer(destination); - if(dest && dest->asCreatureObject() && dest->asCreatureObject()->getGroup()) + if (dest && dest->asCreatureObject() && dest->asCreatureObject()->getGroup()) { int lootRule = dest->asCreatureObject()->getGroup()->getLootRule(); // Random/Lotto Loot Rule, no drag and drop allowed! - if(lootRule == 3 || lootRule == 2) + if (lootRule == 3 || lootRule == 2) { return; } } } - } if (!item->isAuthoritative()) @@ -3107,8 +3094,8 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net } //Don't allow people to put things in unowned containers. Locked containers are allowed since they enforce their own list. - if (!destination->getObjVars().hasItem(OBJVAR_PLAYERS_CAN_ACCESS_CONTAINER) && !lockedDestContainer && - player->getClient() && !player->getClient()->isGod() && + if (!destination->getObjVars().hasItem(OBJVAR_PLAYERS_CAN_ACCESS_CONTAINER) && !lockedDestContainer && + player->getClient() && !player->getClient()->isGod() && destination->getOwnerId() == NetworkId::cms_invalid) { errorCode = Container::CEC_NoPermission; @@ -3143,32 +3130,31 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net { int oldCap = volContainer->debugDoNotUseSetCapacity(allowedOverload); retval = ContainerInterface::transferItemToVolumeContainer(*destination, *item, player, errorCode, true); - IGNORE_RETURN( volContainer->debugDoNotUseSetCapacity(oldCap) ); + IGNORE_RETURN(volContainer->debugDoNotUseSetCapacity(oldCap)); } } } else { const Object * destParent = ContainerInterface::getContainedByObject(*destination); - if(destParent && destParent == player->getAppearanceInventory()) + if (destParent && destParent == player->getAppearanceInventory()) { // Trying to transfer to a container currently in our Appearance inventory. Not allowed. StringId const code("container_error_message", "container34_prose"); ProsePackage pp; pp.stringId = code; - pp.actor.id = player->getNetworkId (); + pp.actor.id = player->getNetworkId(); // Send to the player. - Chat::sendSystemMessage (*player, pp); + Chat::sendSystemMessage(*player, pp); retval = false; - } else if (destination == player->getAppearanceInventory() && ContainerInterface::getContainer(*item) != nullptr) { const Container * itemContainer = ContainerInterface::getContainer(*item); - if(itemContainer && itemContainer->getNumberOfItems() == 0) + if (itemContainer && itemContainer->getNumberOfItems() == 0) { retval = ContainerInterface::transferItemToUnknownContainer(*destination, *item, arrangement, t, player, errorCode); } @@ -3178,16 +3164,16 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net ProsePackage pp; pp.stringId = code; - pp.actor.id = player->getNetworkId (); + pp.actor.id = player->getNetworkId(); // Send to the player. - Chat::sendSystemMessage (*player, pp); + Chat::sendSystemMessage(*player, pp); } } else { retval = ContainerInterface::transferItemToUnknownContainer(*destination, *item, arrangement, t, player, errorCode); - + // if we are equipping an object to a filled slot, move the equipped item(s) to our inventory if (!retval && errorCode == Container::CEC_SlotOccupied && destination->getNetworkId() == player->getNetworkId()) { @@ -3223,7 +3209,6 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net reequipItems(*destination, oldItems); retval = false; } - } else { @@ -3239,14 +3224,14 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net if (!retval && player) { - if(errorCode == Container::CEC_SlotOccupied && destination == player->getAppearanceInventory()) + if (errorCode == Container::CEC_SlotOccupied && destination == player->getAppearanceInventory()) { // Failed to place an object in our appearance inventory. Let's flush out some more information. ServerObject * appearanceInv = player->getAppearanceInventory(); const SlottedContainer * equipment = ContainerInterface::getSlottedContainer(*appearanceInv); const SlottedContainmentProperty * itemContainmentProperty = ContainerInterface::getSlottedContainmentProperty(*item); - if(!itemContainmentProperty || !equipment || arrangement < 0) + if (!itemContainmentProperty || !equipment || arrangement < 0) { // This should never happen, but if it does - just send our normal bland error message. ContainerInterface::sendContainerMessageToClient(*player, errorCode); @@ -3262,16 +3247,16 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net ServerObject * oldItem = safe_cast(currentWeaponId.getObject()); if (oldItem != nullptr) { - if( std::find(objectsToSend.begin(), objectsToSend.end(), oldItem) == objectsToSend.end() ) + if (std::find(objectsToSend.begin(), objectsToSend.end(), oldItem) == objectsToSend.end()) objectsToSend.push_back(oldItem); } } - + std::vector::iterator iter = objectsToSend.begin(); - for(; iter != objectsToSend.end(); ++iter) + for (; iter != objectsToSend.end(); ++iter) { // No idea how this could happen, but just incase. - if((*iter) == nullptr) + if ((*iter) == nullptr) continue; StringId const code("container_error_message", "container32_prose"); @@ -3280,22 +3265,22 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net ProsePackage pp; pp.stringId = code; - pp.target.id = (*iter)->getNetworkId (); - pp.target.str = (*iter)->getAssignedObjectName (); - if (pp.target.str.empty ()) - pp.target.stringId = (*iter)->getObjectNameStringId (); + pp.target.id = (*iter)->getNetworkId(); + pp.target.str = (*iter)->getAssignedObjectName(); + if (pp.target.str.empty()) + pp.target.stringId = (*iter)->getObjectNameStringId(); - pp.other.id = item->getNetworkId(); - pp.other.str = item->getAssignedObjectName(); + pp.other.id = item->getNetworkId(); + pp.other.str = item->getAssignedObjectName(); if (pp.other.str.empty()) pp.other.stringId = item->getObjectNameStringId(); - pp.actor.id = player->getNetworkId (); + pp.actor.id = player->getNetworkId(); // Send to the player. - Chat::sendSystemMessage (*player, pp); + Chat::sendSystemMessage(*player, pp); } - + return; } @@ -3340,14 +3325,13 @@ static void commandFuncTransferWeapon(Command const & c, NetworkId const &actor, size_t curpos = 0; const NetworkId & destId = nextOidParm(params, curpos); - const int arrangement = nextIntParm(params, curpos); + const int arrangement = nextIntParm(params, curpos); UNREF(destId); - + if (item && actorObject && isGoingInWeaponSlot(*item, arrangement)) { commandFuncTransferItem(c, actor, target, params); } - } //------------------------------------------------------------------------------------------ @@ -3367,14 +3351,14 @@ void CommandCppFuncs::commandFuncTransferMisc(Command const & c, NetworkId const { ServerObject * item = ServerWorld::findObjectByNetworkId(target); CreatureObject * actorObject = safe_cast(ServerWorld::findObjectByNetworkId(actor)); - + size_t curpos = 0; const NetworkId & destId = nextOidParm(params, curpos); - const int arrangement = nextIntParm(params, curpos); + const int arrangement = nextIntParm(params, curpos); //This command can only be used to transfer non-weapon objects not contained directly by the player unless it is not armor if (item && actorObject && !isGoingInWeaponSlot(*item, arrangement) && - ( destId != actor || !GameObjectTypes::isTypeOf(item->getGameObjectType(), SharedObjectTemplate::GOT_armor)) ) + (destId != actor || !GameObjectTypes::isTypeOf(item->getGameObjectType(), SharedObjectTemplate::GOT_armor))) { commandFuncTransferItem(c, actor, target, params); } @@ -3402,23 +3386,23 @@ static void commandFuncOpenContainer(Command const & cmd, NetworkId const &actor } //-- don't open factory crates - if (container->getGameObjectType () == SharedObjectTemplate::GOT_misc_factory_crate) + if (container->getGameObjectType() == SharedObjectTemplate::GOT_misc_factory_crate) return; //-- if they are opening a crafting station, what they really want is the hopper //-- but only if the object is not a volume container - if (container->getGameObjectType () == SharedObjectTemplate::GOT_misc_crafting_station - && (nullptr == ContainerInterface::getVolumeContainer (*container))) - { + if (container->getGameObjectType() == SharedObjectTemplate::GOT_misc_crafting_station + && (nullptr == ContainerInterface::getVolumeContainer(*container))) + { static const SlotId inputHopperId(SlotIdManager::findSlotId(CrcLowerString("ingredient_hopper"))); ServerObject const * const station = container; ServerObject * hopper = nullptr; - const SlottedContainer * stationContainer = ContainerInterface::getSlottedContainer (*station); + const SlottedContainer * stationContainer = ContainerInterface::getSlottedContainer(*station); if (stationContainer != nullptr) { Container::ContainerErrorCode tmp = Container::CEC_Success; - Object* tmpHopperObj = (stationContainer->getObjectInSlot (inputHopperId, tmp)).getObject(); + Object* tmpHopperObj = (stationContainer->getObjectInSlot(inputHopperId, tmp)).getObject(); if (tmp == Container::CEC_Success && tmpHopperObj) { hopper = tmpHopperObj->asServerObject(); @@ -3439,18 +3423,18 @@ static void commandFuncOpenContainer(Command const & cmd, NetworkId const &actor size_t curpos = 0; std::string slotName; - int sequence = nextIntParm (params, curpos); + int sequence = nextIntParm(params, curpos); if (curpos != std::string::npos) { ++curpos; - slotName = nextStringParm (params, curpos); + slotName = nextStringParm(params, curpos); } if (container->isAuthoritative()) { Container::ContainerErrorCode code = Container::CEC_Success; - bool const isPublicContainer = container->getGameObjectType () == SharedObjectTemplate::GOT_misc_container_public; + bool const isPublicContainer = container->getGameObjectType() == SharedObjectTemplate::GOT_misc_container_public; if (isPublicContainer && player->getClient()) ObserveTracker::onClientAboutToOpenPublicContainer(*player->getClient(), *container); @@ -3461,10 +3445,10 @@ static void commandFuncOpenContainer(Command const & cmd, NetworkId const &actor if (player->canManipulateObject(*container, false, doPermissionCheckOnItem, doPermissionCheckOnParents, 6.0f, code)) { // Additional check for Locked containers. - if(container->asTangibleObject() && container->asTangibleObject()->isLocked()) + if (container->asTangibleObject() && container->asTangibleObject()->isLocked()) { TangibleObject * tangibleTarget = container->asTangibleObject(); - if(!tangibleTarget->isUserOnAccessList(player->getNetworkId()) && !tangibleTarget->isGuildOnAccessList(player->getGuildId())) + if (!tangibleTarget->isUserOnAccessList(player->getNetworkId()) && !tangibleTarget->isGuildOnAccessList(player->getGuildId())) { // Player is NOT on the admin list or guild list, they cannot open the container. ContainerInterface::sendContainerMessageToClient(*player, Container::CEC_NoPermission, container); @@ -3532,7 +3516,6 @@ static void commandFuncCloseContainer(Command const &, NetworkId const &actor, N //@todo the player is trying to access a container not on this server. Somehow get it here //Then do the check } - } //------------------------------------------------------------------------------------------ @@ -3591,7 +3574,7 @@ static void commandFuncCloseLotteryContainer(Command const & cmd, NetworkId cons */ static void commandFuncGiveItem(Command const &, NetworkId const &actor, NetworkId const &target, Unicode::String const & params) { - ServerObject * const item = ServerWorld::findObjectByNetworkId(target); + ServerObject * const item = ServerWorld::findObjectByNetworkId(target); ServerObject * const player = ServerWorld::findObjectByNetworkId(actor); if (!player || !item) { @@ -3654,14 +3637,14 @@ static void commandFuncGiveItem(Command const &, NetworkId const &actor, Network TangibleObject * const gem = dynamic_cast(item); if (gem != nullptr) { - const int destGot = socket->getGameObjectType(); + const int destGot = socket->getGameObjectType(); const SharedTangibleObjectTemplate * const gemTemplate = safe_cast(gem->getSharedTemplate()); - const int count = gemTemplate->getSocketDestinationsCount(); + const int count = gemTemplate->getSocketDestinationsCount(); for (int i = 0; i < count; ++i) { const int gemSocketGot = gemTemplate->getSocketDestinations(i); - if (destGot == gemSocketGot || GameObjectTypes::isTypeOf (destGot, gemSocketGot)) + if (destGot == gemSocketGot || GameObjectTypes::isTypeOf(destGot, gemSocketGot)) { // make sure the gem and socket are both in the player's inventory if (!socket->isContainedBy(*player, true) || @@ -3706,14 +3689,13 @@ static void commandFuncGiveItem(Command const &, NetworkId const &actor, Network // nope, pass it on to scripts ScriptParams scriptParameters; - scriptParameters.addParam (target); - scriptParameters.addParam (actor); + scriptParameters.addParam(target); + scriptParameters.addParam(actor); if (destination->getScriptObject()->trigAllScripts(Scripting::TRIG_GIVE_ITEM, scriptParameters) == SCRIPT_OVERRIDE) { item->permanentlyDestroy(DeleteReasons::BadContainerTransfer); } - } // ---------------------------------------------------------------------- @@ -3776,8 +3758,8 @@ static void commandFuncGroupInvite(Command const & command, NetworkId const &act // send a messageTo to the target to invite to group char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s|%s|%s|%s", actor.getValueString().c_str(), (actorShipObject ? actorShipObject->getNetworkId().getValueString().c_str() : "0"), (groupObj ? groupObj->getNetworkId().getValueString().c_str() : "0"), Unicode::wideToNarrow(actorObj->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s|%s|%s|%s", actor.getValueString().c_str(), (actorShipObject ? actorShipObject->getNetworkId().getValueString().c_str() : "0"), (groupObj ? groupObj->getNetworkId().getValueString().c_str() : "0"), Unicode::wideToNarrow(actorObj->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(parsedNetworkId, "C++InviteToGroupReq", @@ -3823,8 +3805,8 @@ static void commandFuncGroupUninvite(Command const &, NetworkId const &actor, Ne // send a messageTo to the target to uninvite char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s|%s", actor.getValueString().c_str(), Unicode::wideToNarrow(actorObj->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s|%s", actor.getValueString().c_str(), Unicode::wideToNarrow(actorObj->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(parsedNetworkId, "C++UninviteFromGroupReq", @@ -3944,10 +3926,10 @@ static void commandFuncGroupDisband(Command const &, NetworkId const &actor, Net GroupObject::GroupMemberParamVector membersOutsidePOB; GroupHelpers::separateGroupBasedOffofPOBShip(groupObj, - actor, - POBShipId, - membersInsidePOB, - membersOutsidePOB); + actor, + POBShipId, + membersInsidePOB, + membersOutsidePOB); // if there are no members outside, then the group only consisted of // the people in the POB. If that's the case, then don't destroy the @@ -4025,10 +4007,10 @@ static void commandFuncGroupDisband(Command const &, NetworkId const &actor, Net NetworkId const & POBShipId = (*ii).m_memberShipId; GroupHelpers::separateGroupBasedOffofPOBShip(groupObj, - memberId, - POBShipId, - membersInsidePOB[memberId], - membersOutsidePOB[memberId]); + memberId, + POBShipId, + membersInsidePOB[memberId], + membersOutsidePOB[memberId]); } } @@ -4150,7 +4132,7 @@ static void commandFuncGroupDisband(Command const &, NetworkId const &actor, Net static void commandFuncKickFromShip(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const ¶ms) { - CreatureObject const * const actorObject = dynamic_cast(ServerWorld::findObjectByNetworkId(actor)); + CreatureObject const * const actorObject = dynamic_cast(ServerWorld::findObjectByNetworkId(actor)); if (actorObject != 0) { CreatureObject * const targetObject = dynamic_cast(ServerWorld::findObjectByNetworkId(target)); @@ -4209,7 +4191,6 @@ static void commandFuncAuctionChat(Command const &, NetworkId const &actor, Netw const std::string channelName = "SWG." + GameServer::getInstance().getClusterName() + "." + ServerWorld::getSceneId() + ".named.Auction"; Chat::sendToRoom(firstName, channelName, params, Unicode::String()); - } } @@ -4357,8 +4338,8 @@ static void commandFuncCreateGroupPickup(Command const &, NetworkId const &actor if ((iterGroupMember->first != actor) && groupObj->isMemberPC(iterGroupMember->first)) { char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s|%d|%d|%d|%s", currentScene.c_str(), static_cast(currentWorldLocation.x), static_cast(currentWorldLocation.y), static_cast(currentWorldLocation.z), actorName.c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s|%d|%d|%d|%s", currentScene.c_str(), static_cast(currentWorldLocation.x), static_cast(currentWorldLocation.y), static_cast(currentWorldLocation.z), actorName.c_str()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(iterGroupMember->first, "C++GroupPickupPointCreated", @@ -4558,7 +4539,7 @@ static void commandFuncUseGroupPickup(Command const &, NetworkId const &actor, N return; } - // if nearest travel point and current planet is the same, and the nearest travel point to the + // if nearest travel point and current planet is the same, and the nearest travel point to the // group pickup point is farther away than the current location to the group pickup point, then // fail, as there is no need to travel as the player is currently closer to the group pickup point if ((sceneIdOfNearestTravelPoint == currentScene) && (sceneIdOfNearestTravelPoint == groupPickupLocation.first) && (groupPickupLocation.second.magnitudeBetweenSquared(nearestTravelPoint->getPosition_w()) > groupPickupLocation.second.magnitudeBetweenSquared(currentWorldLocation))) @@ -4613,8 +4594,8 @@ static void commandFuncUseGroupPickup(Command const &, NetworkId const &actor, N if (cityHallAtNearestTravelPoint.isValid() && (cityShareOfCost > 0)) { char buffer[64]; - snprintf(buffer, sizeof(buffer)-1, "%d", cityShareOfCost); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%d", cityShareOfCost); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(cityHallAtNearestTravelPoint, "C++CityShareGroupPickupPointTravelCost", @@ -5247,37 +5228,37 @@ static void commandFuncShowMusicianVisuals(Command const &, NetworkId const &act // ---------------------------------------------------------------------- -static void commandFuncPlaceStructure (const Command& /*command*/, const NetworkId& actor, const NetworkId& /*target*/, const Unicode::String& parameters) +static void commandFuncPlaceStructure(const Command& /*command*/, const NetworkId& actor, const NetworkId& /*target*/, const Unicode::String& parameters) { - Object* const object = NetworkIdManager::getObjectById (actor); + Object* const object = NetworkIdManager::getObjectById(actor); if (!object) { - DEBUG_WARNING (true, ("commandFuncPlaceStructure: PB nullptr actor\n")); + DEBUG_WARNING(true, ("commandFuncPlaceStructure: PB nullptr actor\n")); return; } ServerObject* const serverObject = dynamic_cast (object); if (!serverObject) { - DEBUG_WARNING (true, ("commandFuncPlaceStructure: object is not a server object\n")); + DEBUG_WARNING(true, ("commandFuncPlaceStructure: object is not a server object\n")); return; } size_t pos = 0; - const NetworkId deedNetworkId = nextOidParm (parameters, pos); - const float x = nextFloatParm (parameters, pos); - const float z = nextFloatParm (parameters, pos); - const Vector position (x, 0.f, z); - const int rotation = nextIntParm (parameters, pos); + const NetworkId deedNetworkId = nextOidParm(parameters, pos); + const float x = nextFloatParm(parameters, pos); + const float z = nextFloatParm(parameters, pos); + const Vector position(x, 0.f, z); + const int rotation = nextIntParm(parameters, pos); ScriptParams scriptParameters; - scriptParameters.addParam (actor); - scriptParameters.addParam (deedNetworkId); - scriptParameters.addParam (position); - scriptParameters.addParam (rotation); + scriptParameters.addParam(actor); + scriptParameters.addParam(deedNetworkId); + scriptParameters.addParam(position); + scriptParameters.addParam(rotation); - if (serverObject->getScriptObject ()->trigAllScripts (Scripting::TRIG_PLACE_STRUCTURE, scriptParameters) != SCRIPT_CONTINUE) - DEBUG_REPORT_LOG (true, ("commandFuncPlaceStructure: did not return SCRIPT_CONTINUE\n")); + if (serverObject->getScriptObject()->trigAllScripts(Scripting::TRIG_PLACE_STRUCTURE, scriptParameters) != SCRIPT_CONTINUE) + DEBUG_REPORT_LOG(true, ("commandFuncPlaceStructure: did not return SCRIPT_CONTINUE\n")); } // ---------------------------------------------------------------------- @@ -5336,14 +5317,14 @@ static void commandFuncSitServer(const Command& /*command*/, const NetworkId& ac if (!sittingOnChair) { // Trying to sit on the ground. - const TerrainObject* const terrainObject = TerrainObject::getConstInstance(); - const CollisionProperty* const collisionProperty = actorObject->getCollisionProperty (); - const bool isOnSolidFloor = collisionProperty && collisionProperty->getFootprint() && collisionProperty->getFootprint()->isOnSolidFloor(); + const TerrainObject* const terrainObject = TerrainObject::getConstInstance(); + const CollisionProperty* const collisionProperty = actorObject->getCollisionProperty(); + const bool isOnSolidFloor = collisionProperty && collisionProperty->getFootprint() && collisionProperty->getFootprint()->isOnSolidFloor(); Vector normal = Vector::unitY; if (terrainObject && actorObject->isInWorldCell() && !isOnSolidFloor) { - const Vector position = actorObject->getPosition_w (); + const Vector position = actorObject->getPosition_w(); float terrainHeight; if (terrainObject->getHeight(position, terrainHeight, normal)) @@ -5352,10 +5333,10 @@ static void commandFuncSitServer(const Command& /*command*/, const NetworkId& ac float waterHeight; if (terrainObject->getWaterHeight(position, waterHeight)) { - if (waterHeight >terrainHeight) + if (waterHeight > terrainHeight) { // Client is in the water, abort the command. - Chat::sendSystemMessage (*creatureActorObject, SharedStringIds::no_sitting_in_water, Unicode::emptyString); + Chat::sendSystemMessage(*creatureActorObject, SharedStringIds::no_sitting_in_water, Unicode::emptyString); return; } } @@ -5382,7 +5363,6 @@ static void commandFuncSitServer(const Command& /*command*/, const NetworkId& ac //-- Send a SitOnObject message with the chair coordinates. const_cast(creatureActorObject)->sitOnObject(chairCellId, chairPosition_p); } - } // ---------------------------------------------------------------------- @@ -5397,11 +5377,11 @@ static void commandFuncGetAttributes(Command const &, NetworkId const &actor, Ne // ---------------------------------------------------------------------- -static void commandFuncGetAttributesBatch(Command const &, NetworkId const &actor, NetworkId const & , Unicode::String const & params) +static void commandFuncGetAttributesBatch(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const & params) { size_t curpos = 0; NetworkId obj = nextOidParm(params, curpos); - while(obj != NetworkId::cms_invalid) + while (obj != NetworkId::cms_invalid) { int const clientRevision = nextIntParm(params, curpos); TaskGetAttributes * const task = new TaskGetAttributes(actor, obj, clientRevision); @@ -5412,55 +5392,55 @@ static void commandFuncGetAttributesBatch(Command const &, NetworkId const &acto // ---------------------------------------------------------------------- -static std::string underscoreToSpace (const std::string& source) +static std::string underscoreToSpace(const std::string& source) { std::string result = source; - std::replace (result.begin (), result.end (), '_', ' '); + std::replace(result.begin(), result.end(), '_', ' '); return result; } // ---------------------------------------------------------------------- -static void commandFuncPurchaseTicket (const Command& /*command*/, const NetworkId& actor, const NetworkId& /*target*/, const Unicode::String& parameters) +static void commandFuncPurchaseTicket(const Command& /*command*/, const NetworkId& actor, const NetworkId& /*target*/, const Unicode::String& parameters) { ServerObject* const serverObject = ServerObject::getServerObject(actor); if (!serverObject) { - DEBUG_WARNING (true, ("commandFuncPurchaseTicket: object is not a server object")); + DEBUG_WARNING(true, ("commandFuncPurchaseTicket: object is not a server object")); return; } size_t pos = 0; - const Unicode::String planetName1 = Unicode::narrowToWide (nextStringParm (parameters, pos)); - const Unicode::String travelPoint1 = Unicode::narrowToWide (underscoreToSpace (nextStringParm (parameters, pos))); - const Unicode::String planetName2 = Unicode::narrowToWide (nextStringParm (parameters, pos)); - const Unicode::String travelPoint2 = Unicode::narrowToWide (underscoreToSpace (nextStringParm (parameters, pos))); - const bool roundTrip = nextBoolParm (parameters, pos); - const bool instantTravel = nextBoolParm (parameters, pos); + const Unicode::String planetName1 = Unicode::narrowToWide(nextStringParm(parameters, pos)); + const Unicode::String travelPoint1 = Unicode::narrowToWide(underscoreToSpace(nextStringParm(parameters, pos))); + const Unicode::String planetName2 = Unicode::narrowToWide(nextStringParm(parameters, pos)); + const Unicode::String travelPoint2 = Unicode::narrowToWide(underscoreToSpace(nextStringParm(parameters, pos))); + const bool roundTrip = nextBoolParm(parameters, pos); + const bool instantTravel = nextBoolParm(parameters, pos); ScriptParams scriptParameters; - scriptParameters.addParam (actor); - scriptParameters.addParam (planetName1); - scriptParameters.addParam (travelPoint1); - scriptParameters.addParam (planetName2); - scriptParameters.addParam (travelPoint2); - scriptParameters.addParam (roundTrip); + scriptParameters.addParam(actor); + scriptParameters.addParam(planetName1); + scriptParameters.addParam(travelPoint1); + scriptParameters.addParam(planetName2); + scriptParameters.addParam(travelPoint2); + scriptParameters.addParam(roundTrip); Scripting::TrigId id = instantTravel ? Scripting::TRIG_PURCHASE_TICKET_INSTANT_TRAVEL : Scripting::TRIG_PURCHASE_TICKET; - if (serverObject->getScriptObject ()->trigAllScripts (id, scriptParameters) != SCRIPT_CONTINUE) - DEBUG_REPORT_LOG (true, ("commandFuncPurchaseTicket: did not return SCRIPT_CONTINUE\n")); + if (serverObject->getScriptObject()->trigAllScripts(id, scriptParameters) != SCRIPT_CONTINUE) + DEBUG_REPORT_LOG(true, ("commandFuncPurchaseTicket: did not return SCRIPT_CONTINUE\n")); } //---------------------------------------------------------------------- -static void commandFuncRequestResourceWeights(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncRequestResourceWeights(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncRequestResourceWeights: PB nullptr actor")); + WARNING(true, ("commandFuncRequestResourceWeights: PB nullptr actor")); return; } @@ -5471,12 +5451,12 @@ static void commandFuncRequestResourceWeights(const Command& , const NetworkId& //---------------------------------------------------------------------- -static void commandFuncRequestResourceWeightsBatch(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncRequestResourceWeightsBatch(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { - CreatureObject* const creature = dynamic_cast(NetworkIdManager::getObjectById (actor)); + CreatureObject* const creature = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (creature == nullptr) { - WARNING (true, ("commandFuncRequestResourceWeightsBatch: PB nullptr actor")); + WARNING(true, ("commandFuncRequestResourceWeightsBatch: PB nullptr actor")); return; } @@ -5484,7 +5464,7 @@ static void commandFuncRequestResourceWeightsBatch(const Command& , const Networ size_t curpos = 0; schematicCrc = nextIntParm(params, curpos); - while(schematicCrc != -1) + while (schematicCrc != -1) { DraftSchematicObject::requestResourceWeights(*creature, static_cast(schematicCrc)); schematicCrc = nextIntParm(params, curpos); @@ -5493,19 +5473,19 @@ static void commandFuncRequestResourceWeightsBatch(const Command& , const Networ //---------------------------------------------------------------------- -static void commandFuncRequestDraftSlots (const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncRequestDraftSlots(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncRequestDraftSlots: PB nullptr actor")); + WARNING(true, ("commandFuncRequestDraftSlots: PB nullptr actor")); return; } PlayerObject * const player = PlayerCreatureController::getPlayerObject(creature); if (player == nullptr) { - WARNING (true, ("commandFuncRequestDraftSlots: no player object for actor ""%s", actor.getValueString().c_str())); + WARNING(true, ("commandFuncRequestDraftSlots: no player object for actor ""%s", actor.getValueString().c_str())); return; } @@ -5515,26 +5495,26 @@ static void commandFuncRequestDraftSlots (const Command& , const NetworkId& acto MessageQueueDraftSlotsQueryResponse * const message = new MessageQueueDraftSlotsQueryResponse(std::make_pair(serverCrc, sharedCrc)); if (!player->requestDraftSlots(serverCrc, nullptr, message)) { - WARNING (true, ("commandFuncRequestDraftSlots failed to request draft slots for %u", serverCrc)); + WARNING(true, ("commandFuncRequestDraftSlots failed to request draft slots for %u", serverCrc)); delete message; } } // ---------------------------------------------------------------------- -static void commandFuncRequestDraftSlotsBatch (const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncRequestDraftSlotsBatch(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncRequestDraftSlotsBatch: PB nullptr actor")); + WARNING(true, ("commandFuncRequestDraftSlotsBatch: PB nullptr actor")); return; } PlayerObject * const player = PlayerCreatureController::getPlayerObject(creature); if (player == nullptr) { - WARNING (true, ("commandFuncRequestDraftSlotsBatch: no player object for actor ""%s", actor.getValueString().c_str())); + WARNING(true, ("commandFuncRequestDraftSlotsBatch: no player object for actor ""%s", actor.getValueString().c_str())); return; } @@ -5543,29 +5523,29 @@ static void commandFuncRequestDraftSlotsBatch (const Command& , const NetworkId& size_t curpos = 0; std::string serverCrcString = nextStringParm(params, curpos); - if(serverCrcString.empty()) + if (serverCrcString.empty()) return; sscanf(serverCrcString.c_str(), "%lu", &uServerCrc); std::string sharedCrcString = nextStringParm(params, curpos); - if(sharedCrcString.empty()) + if (sharedCrcString.empty()) return; sscanf(sharedCrcString.c_str(), "%lu", &uSharedCrc); bool done = false; - while(uServerCrc != 0 && uSharedCrc != 0 && !done) + while (uServerCrc != 0 && uSharedCrc != 0 && !done) { MessageQueueDraftSlotsQueryResponse * const message = new MessageQueueDraftSlotsQueryResponse(std::make_pair(uServerCrc, uSharedCrc)); if (!player->requestDraftSlots(uServerCrc, nullptr, message)) { - WARNING (true, ("commandFuncRequestDraftSlotsBatch failed to request draft slots for %lu", uServerCrc)); + WARNING(true, ("commandFuncRequestDraftSlotsBatch failed to request draft slots for %lu", uServerCrc)); delete message; } serverCrcString = nextStringParm(params, curpos); - if(serverCrcString.empty()) + if (serverCrcString.empty()) done = true; sscanf(serverCrcString.c_str(), "%lu", &uServerCrc); sharedCrcString = nextStringParm(params, curpos); - if(sharedCrcString.empty()) + if (sharedCrcString.empty()) done = true; sscanf(sharedCrcString.c_str(), "%lu", &uSharedCrc); } @@ -5573,12 +5553,12 @@ static void commandFuncRequestDraftSlotsBatch (const Command& , const NetworkId& // ---------------------------------------------------------------------- -static void commandFuncRequestManfSchematicSlots (const Command& , const NetworkId& actor, const NetworkId& target, const Unicode::String& params) +static void commandFuncRequestManfSchematicSlots(const Command&, const NetworkId& actor, const NetworkId& target, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncRequestDraftSlots: PB nullptr actor")); + WARNING(true, ("commandFuncRequestDraftSlots: PB nullptr actor")); return; } @@ -5592,19 +5572,19 @@ static void commandFuncRequestManfSchematicSlots (const Command& , const Network // ---------------------------------------------------------------------- -static void commandFuncRequestCraftingSession (const Command& , const NetworkId& actor, const NetworkId& target, const Unicode::String& params) +static void commandFuncRequestCraftingSession(const Command&, const NetworkId& actor, const NetworkId& target, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncRequestCraftingSession: PB nullptr actor")); + WARNING(true, ("commandFuncRequestCraftingSession: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); if (player == nullptr) { - WARNING (true, ("commandFuncRequestCraftingSession: no player object for actor " + WARNING(true, ("commandFuncRequestCraftingSession: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5617,7 +5597,7 @@ static void commandFuncRequestCraftingSession (const Command& , const NetworkId& // 1 means this request was made on a crafting station versus a crafting tool. uint8 const sequenceId = static_cast(craftingObject && craftingObject->isCraftingStation() ? 1 : 0); - MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse ( + MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse( CM_requestCraftingSession, false, sequenceId); creature->getController()->appendMessage(CM_craftingResult, 0.0f, response, GameControllerMessageFlags::SEND | @@ -5645,19 +5625,19 @@ static void commandFuncRequestCraftingSessionFail(Command const &, NetworkId con // ---------------------------------------------------------------------- -static void commandFuncSelectDraftSchematic (const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncSelectDraftSchematic(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncSelectDraftSchematic: PB nullptr actor")); + WARNING(true, ("commandFuncSelectDraftSchematic: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); if (player == nullptr) { - WARNING (true, ("commandFuncSelectDraftSchematic: no player object for actor " + WARNING(true, ("commandFuncSelectDraftSchematic: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5669,19 +5649,19 @@ static void commandFuncSelectDraftSchematic (const Command& , const NetworkId& a // ---------------------------------------------------------------------- -static void commandFuncNextCraftingStage(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncNextCraftingStage(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncNextCraftingStage: PB nullptr actor")); + WARNING(true, ("commandFuncNextCraftingStage: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); if (player == nullptr) { - WARNING (true, ("commandFuncNextCraftingStage: no player object for actor " + WARNING(true, ("commandFuncNextCraftingStage: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5689,7 +5669,7 @@ static void commandFuncNextCraftingStage(const Command& , const NetworkId& actor uint8 sequenceId = static_cast(atoi(Unicode::wideToNarrow(params).c_str())); int result = player->goToNextCraftingStage(); - MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse ( + MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse( CM_nextCraftingStage, result, sequenceId); creature->getController()->appendMessage(CM_nextCraftingStageResult, 0.0f, response, GameControllerMessageFlags::SEND | @@ -5699,19 +5679,19 @@ static void commandFuncNextCraftingStage(const Command& , const NetworkId& actor // ---------------------------------------------------------------------- -static void commandFuncCreatePrototype(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncCreatePrototype(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncCreatePrototype: PB nullptr actor")); + WARNING(true, ("commandFuncCreatePrototype: PB nullptr actor")); return; } PlayerObject * const player = PlayerCreatureController::getPlayerObject(creature); if (player == nullptr) { - WARNING (true, ("commandFuncCreatePrototype: no player object for actor %s", actor.getValueString().c_str())); + WARNING(true, ("commandFuncCreatePrototype: no player object for actor %s", actor.getValueString().c_str())); return; } @@ -5721,7 +5701,7 @@ static void commandFuncCreatePrototype(const Command& , const NetworkId& actor, const bool result = player->createPrototype(realPrototype); - MessageQueueGenericIntResponse * const response = new MessageQueueGenericIntResponse (CM_createPrototype, result, sequenceId); + MessageQueueGenericIntResponse * const response = new MessageQueueGenericIntResponse(CM_createPrototype, result, sequenceId); creature->getController()->appendMessage(CM_craftingResult, 0.0f, response, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | @@ -5733,19 +5713,19 @@ static void commandFuncCreatePrototype(const Command& , const NetworkId& actor, // ---------------------------------------------------------------------- -static void commandFuncCreateManfSchematic(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncCreateManfSchematic(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncCreateManfSchematic: PB nullptr actor")); + WARNING(true, ("commandFuncCreateManfSchematic: PB nullptr actor")); return; } PlayerObject * const player = PlayerCreatureController::getPlayerObject(creature); if (player == nullptr) { - WARNING (true, ("commandFuncCreateManfSchematic: no player object for actor %s", actor.getValueString().c_str())); + WARNING(true, ("commandFuncCreateManfSchematic: no player object for actor %s", actor.getValueString().c_str())); return; } @@ -5753,7 +5733,7 @@ static void commandFuncCreateManfSchematic(const Command& , const NetworkId& act const bool result = player->createManufacturingSchematic(); - MessageQueueGenericIntResponse * const response = new MessageQueueGenericIntResponse (CM_createManfSchematic, result, sequenceId); + MessageQueueGenericIntResponse * const response = new MessageQueueGenericIntResponse(CM_createManfSchematic, result, sequenceId); creature->getController()->appendMessage(CM_craftingResult, 0.0f, response, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | @@ -5765,19 +5745,19 @@ static void commandFuncCreateManfSchematic(const Command& , const NetworkId& act // ---------------------------------------------------------------------- -static void commandFuncCancelCraftingSession(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncCancelCraftingSession(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncCancelCraftingSession: PB nullptr actor")); + WARNING(true, ("commandFuncCancelCraftingSession: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); if (player == nullptr) { - WARNING (true, ("commandFuncCancelCraftingSession: no player object for actor " + WARNING(true, ("commandFuncCancelCraftingSession: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5787,19 +5767,19 @@ static void commandFuncCancelCraftingSession(const Command& , const NetworkId& a // ---------------------------------------------------------------------- -static void commandFuncStopCraftingSession(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncStopCraftingSession(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncStopCraftingSession: PB nullptr actor")); + WARNING(true, ("commandFuncStopCraftingSession: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); if (player == nullptr) { - WARNING (true, ("commandFuncStopCraftingSession: no player object for actor " + WARNING(true, ("commandFuncStopCraftingSession: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5809,19 +5789,19 @@ static void commandFuncStopCraftingSession(const Command& , const NetworkId& act // ---------------------------------------------------------------------- -static void commandFuncRestartCraftingSession(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncRestartCraftingSession(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncRestartCraftingSession: PB nullptr actor")); + WARNING(true, ("commandFuncRestartCraftingSession: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); if (player == nullptr) { - WARNING (true, ("commandFuncRestartCraftingSession: no player object for actor " + WARNING(true, ("commandFuncRestartCraftingSession: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5830,7 +5810,7 @@ static void commandFuncRestartCraftingSession(const Command& , const NetworkId& const bool success = player->restartCrafting(); - MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse ( + MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse( CM_restartCraftingSession, success, sequenceId); creature->getController()->appendMessage(CM_craftingResult, 0.0f, response, GameControllerMessageFlags::SEND | @@ -6018,18 +5998,18 @@ static void commandFuncSetBiography(Command const &, NetworkId const & actor, Ne CreatureObject * const creatureActor = CreatureObject::getCreatureObject(actor); if (!creatureActor) { - WARNING (true, ("commandFuncSetBiography: bad actor")); + WARNING(true, ("commandFuncSetBiography: bad actor")); return; } Client * const clientActor = creatureActor->getClient(); - if(!clientActor) + if (!clientActor) { WARNING(true, ("no Client in commandFuncSetBiography")); return; } - if(!clientActor->isGod()) + if (!clientActor->isGod()) { LOG("CustomerService", ("CheatChannel:%s attempted to set biography data on %s, but is not a God", PlayerObject::getAccountDescription(actor).c_str(), PlayerObject::getAccountDescription(target).c_str())); } @@ -6051,13 +6031,13 @@ static void commandFuncRequestCharacterSheetInfo(Command const &, NetworkId cons const CreatureObject* const creatureActor = CreatureObject::getCreatureObject(actor); if (creatureActor == nullptr) { - WARNING (true, ("commandFuncRequestCharacterSheetInfo: nullptr actor")); + WARNING(true, ("commandFuncRequestCharacterSheetInfo: nullptr actor")); return; } //TODO get the born and played times (once they're in the DB) - int born = 0; - int played = 0; + int born = 0; + int played = 0; //get the bind location Vector bindLoc; @@ -6067,12 +6047,12 @@ static void commandFuncRequestCharacterSheetInfo(Command const &, NetworkId cons { creatureActor->getObjVars().getItem("bind.facility", bindId); } - if(bindId != NetworkId::cms_invalid) + if (bindId != NetworkId::cms_invalid) { const ServerObject* const bindObject = ServerObject::getServerObject(bindId); if (bindObject != nullptr) { - bindLoc = bindObject->getPosition_w(); + bindLoc = bindObject->getPosition_w(); bindPlanet = bindObject->getSceneId(); } } @@ -6124,7 +6104,7 @@ static void commandFuncRequestCharacterSheetInfo(Command const &, NetworkId cons const ServerObject* const resObject = ServerObject::getServerObject(houseNetworkId); if (resObject != nullptr) { - resLoc = resObject->getPosition_w(); + resLoc = resObject->getPosition_w(); resPlanet = ServerWorld::getSceneId(); } else if (houseNetworkId.isValid() && MessageToQueue::isInstalled()) @@ -6148,7 +6128,7 @@ static void commandFuncRequestCharacterSheetInfo(Command const &, NetworkId cons int lots = creatureActor->getMaxNumberOfLots(); PlayerObject const * const player = PlayerCreatureController::getPlayerObject(creatureActor); - if(player) + if (player) { int lotsUsed = player->getAccountNumLots(); lots -= lotsUsed; @@ -6183,21 +6163,21 @@ static void commandFuncExtractObject(Command const &, NetworkId const &actor, Ne CreatureObject* const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncExtractObject: PB nullptr actor")); + WARNING(true, ("commandFuncExtractObject: PB nullptr actor")); return; } if (creature->getInventory() == nullptr) { - WARNING (true, ("commandFuncExtractObject: actor %s has no inventory", + WARNING(true, ("commandFuncExtractObject: actor %s has no inventory", actor.getValueString().c_str())); return; } - FactoryObject* const factory = dynamic_cast(NetworkIdManager::getObjectById (target)); + FactoryObject* const factory = dynamic_cast(NetworkIdManager::getObjectById(target)); if (factory == nullptr) { - WARNING (true, ("commandFuncExtractObject: PB nullptr target")); + WARNING(true, ("commandFuncExtractObject: PB nullptr target")); return; } @@ -6215,22 +6195,22 @@ static void commandFuncRevokeSkill(Command const &, NetworkId const &actor, Netw CreatureObject * const creature = CreatureObject::getCreatureObject(actor); if (creature == nullptr) { - WARNING (true, ("commandFuncRevokeSkill: PB nullptr actor")); + WARNING(true, ("commandFuncRevokeSkill: PB nullptr actor")); return; } size_t pos = 0; std::string skillName = nextStringParm(params, pos); - const SkillObject * skill = SkillManager::getInstance ().getSkill (skillName); + const SkillObject * skill = SkillManager::getInstance().getSkill(skillName); if (skill == nullptr) { - WARNING (true, ("commandFuncRevokeSkill: can't revoke bad skill")); + WARNING(true, ("commandFuncRevokeSkill: can't revoke bad skill")); } else { LOG("CustomerService", ("Skill: God (via cmdfunc) has requested the revocation of skill %s from character %s.", skillName.c_str(), creature->getNetworkId().getValueString().c_str())); - creature->revokeSkill (*skill); + creature->revokeSkill(*skill); } } @@ -6358,8 +6338,8 @@ static void commandFuncSetCurrentSkillTitle(Command const &, NetworkId const &ac { SkillObject const *skillObject = (*iterSkillList); - if ( (skillObject != nullptr) - && skillObject->isTitle() + if ((skillObject != nullptr) + && skillObject->isTitle() && (skillObject->getSkillName() == title)) { playerObject->setTitle(title); @@ -6381,17 +6361,17 @@ static void commandFuncSetCurrentSkillTitle(Command const &, NetworkId const &ac static void commandFuncRepair(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { - CreatureObject* const creature = dynamic_cast(NetworkIdManager::getObjectById (actor)); + CreatureObject* const creature = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (creature == nullptr) { - WARNING (true, ("commandFuncRepair: PB nullptr actor")); + WARNING(true, ("commandFuncRepair: PB nullptr actor")); return; } - TangibleObject* const object = dynamic_cast(NetworkIdManager::getObjectById (target)); + TangibleObject* const object = dynamic_cast(NetworkIdManager::getObjectById(target)); if (object == nullptr) { - WARNING (true, ("commandFuncRepair: PB nullptr target")); + WARNING(true, ("commandFuncRepair: PB nullptr target")); return; } } @@ -6466,7 +6446,6 @@ static void commandFuncToggleRolePlay(Command const &, NetworkId const &actor, N } } - // ---------------------------------------------------------------------- static void commandFuncToggleOutOfCharacter(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) @@ -6491,7 +6470,6 @@ static void commandFuncToggleLookingForWork(Command const &, NetworkId const &ac } } - // ---------------------------------------------------------------------- static void commandFuncToggleLookingForGroup(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) @@ -6564,14 +6542,14 @@ static void commandFuncReport(Command const &, NetworkId const &actor, NetworkId Unicode::String const delimiter = Unicode::narrowToWide("|"); Unicode::UnicodeStringVector tokens; - if(Unicode::tokenize(params, tokens, &delimiter) && tokens.size() > 1) + if (Unicode::tokenize(params, tokens, &delimiter) && tokens.size() > 1) { harassingPlayerName = tokens[0]; Unicode::String rest; uint32 numTokens = tokens.size(); - for(uint32 i = 1; i < numTokens; ++i) + for (uint32 i = 1; i < numTokens; ++i) { - if(i != 1) + if (i != 1) { rest.append(delimiter); } @@ -6588,7 +6566,6 @@ static void commandFuncReport(Command const &, NetworkId const &actor, NetworkId Chat::sendSystemMessage(*reportingCreatureObject, StringId("system_msg", "report_no_name"), Unicode::emptyString); } - //if (Unicode::getFirstToken(name, curpos, endpos, harassingPlayerName)) //{ @@ -6639,7 +6616,7 @@ static void commandFuncNpcConversationStart(Command const &, NetworkId const &ac return; } } - + std::string const & realParams = Unicode::wideToNarrow(params); if (realParams.size() < 2) { @@ -6650,7 +6627,7 @@ static void commandFuncNpcConversationStart(Command const &, NetworkId const &ac const char * const conversationName = &realParams[2]; NpcConversationData::ConversationStarter const starter = static_cast(atoi(realParams.c_str())); - player->startNpcConversation (*npc, conversationName, starter, 0); + player->startNpcConversation(*npc, conversationName, starter, 0); } //---------------------------------------------------------------------- @@ -6658,7 +6635,7 @@ static void commandFuncNpcConversationStart(Command const &, NetworkId const &ac static void commandFuncNpcConversationStop(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { ServerObject * const actorObject = safe_cast(NetworkIdManager::getObjectById(actor)); - TangibleObject * const player = actorObject != nullptr ? actorObject->asTangibleObject(): nullptr; + TangibleObject * const player = actorObject != nullptr ? actorObject->asTangibleObject() : nullptr; if (player == nullptr) { DEBUG_WARNING(true, ("commandFuncNpcConversationStop: couldn't find actor")); @@ -6686,27 +6663,27 @@ static void commandFuncNpcConversationSelect(Command const &, NetworkId const &a //---------------------------------------------------------------------- -static void commandFuncServerDestroyObject (Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) +static void commandFuncServerDestroyObject(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) { - CreatureObject * const player = dynamic_cast (NetworkIdManager::getObjectById (actor)); + CreatureObject * const player = dynamic_cast (NetworkIdManager::getObjectById(actor)); if (player == nullptr) { - DEBUG_WARNING (true, ("commandFuncServerDestroyObject: couldn't find actor")); + DEBUG_WARNING(true, ("commandFuncServerDestroyObject: couldn't find actor")); return; } - ServerObject * const targetObject = safe_cast(NetworkIdManager::getObjectById (target)); + ServerObject * const targetObject = safe_cast(NetworkIdManager::getObjectById(target)); if (!targetObject) { PlayerObject * p = PlayerCreatureController::getPlayerObject(player); - if(p) + if (p) { p->destroyWaypoint(target); return; } else { - DEBUG_WARNING (true, ("commandFuncServerDestroyObject: couldn't find target")); + DEBUG_WARNING(true, ("commandFuncServerDestroyObject: couldn't find target")); return; } } @@ -6714,18 +6691,18 @@ static void commandFuncServerDestroyObject (Command const &, NetworkId const & a ServerObject const * const topMost = getFirstParentInWorldOrPlayer(targetObject); if (!topMost || topMost->getNetworkId() != actor) { - DEBUG_WARNING (true, ("player tried to delete something not in their inventory")); + DEBUG_WARNING(true, ("player tried to delete something not in their inventory")); return; } ProsePackage pp; - const bool sendResponse = !params.empty (); + const bool sendResponse = !params.empty(); - int const got = targetObject->getGameObjectType (); + int const got = targetObject->getGameObjectType(); if (sendResponse) { - ProsePackageManagerServer::createSimpleProsePackage (*targetObject, SharedStringIds::rsp_object_deleted_prose, pp); - pp.other.stringId = GameObjectTypes::getStringId (got); + ProsePackageManagerServer::createSimpleProsePackage(*targetObject, SharedStringIds::rsp_object_deleted_prose, pp); + pp.other.stringId = GameObjectTypes::getStringId(got); } // Cannot destroy an empty ship pcd while contained by a ship you own @@ -6749,7 +6726,7 @@ static void commandFuncServerDestroyObject (Command const &, NetworkId const & a return; Object const * const currentContainer = ContainerInterface::getContainedByObject(*targetObject); - if(currentContainer && currentContainer->asServerObject() && ( currentContainer->asServerObject()->getGameObjectType() == SharedObjectTemplate::GOT_chronicles_quest_holocron || currentContainer->asServerObject()->getGameObjectType() == SharedObjectTemplate::GOT_chronicles_quest_holocron_recipe ) ) + if (currentContainer && currentContainer->asServerObject() && (currentContainer->asServerObject()->getGameObjectType() == SharedObjectTemplate::GOT_chronicles_quest_holocron || currentContainer->asServerObject()->getGameObjectType() == SharedObjectTemplate::GOT_chronicles_quest_holocron_recipe)) { // Give the player a warning here? return; @@ -6759,10 +6736,10 @@ static void commandFuncServerDestroyObject (Command const &, NetworkId const & a { LOG("CustomerService", ("Deletion:%s is deleting object %s", PlayerObject::getAccountDescription(actor).c_str(), ServerObject::getLogDescription(targetObject).c_str())); if (sendResponse) - Chat::sendSystemMessage (*player, pp); + Chat::sendSystemMessage(*player, pp); } else - WARNING (true, ("commandFuncServerDestroyObject: Error encountered while deleting object %s", target.getValueString ().c_str ())); + WARNING(true, ("commandFuncServerDestroyObject: Error encountered while deleting object %s", target.getValueString().c_str())); } // ---------------------------------------------------------------------- @@ -6855,10 +6832,10 @@ static void commandFuncUnstick(Command const &, NetworkId const &actor, NetworkI static void commandFuncGetAccountInfo(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { const CreatureObject * gm = dynamic_cast(NetworkIdManager::getObjectById(actor)); - if(gm) + if (gm) { const Client * gmClient = gm->getClient(); - if(gmClient) + if (gmClient) { bool foundAsPilot = false; const CreatureObject * player = dynamic_cast(NetworkIdManager::getObjectById(target)); @@ -6872,23 +6849,23 @@ static void commandFuncGetAccountInfo(Command const &, NetworkId const &actor, N } } std::string result; - if(player) + if (player) { const Client * client = player->getClient(); - if(client) + if (client) { if (foundAsPilot) - result = "Pilot Character Name : "; + result = "Pilot Character Name : "; else - result = "Character Name : "; + result = "Character Name : "; result += Unicode::wideToNarrow(player->getAssignedObjectName()); result += "\nAccount Name : "; result += client->getAccountName(); result += "\nStation Id : "; char buf[32]; - IGNORE_RETURN(snprintf(buf, sizeof(buf)-1, "%d", client->getStationId())); - buf[sizeof(buf)-1] = '\0'; + IGNORE_RETURN(snprintf(buf, sizeof(buf) - 1, "%d", client->getStationId())); + buf[sizeof(buf) - 1] = '\0'; result += buf; result += "\nGame Features : "; result += ClientGameFeature::getDescription(client->getGameFeatures()); @@ -6916,7 +6893,7 @@ static void commandFuncGetAccountInfo(Command const &, NetworkId const &actor, N result += "\nIP Address : "; result += client->getIpAddress(); result += "\nGod Mode : "; - if(client->isGod()) + if (client->isGod()) result += "true"; else result += "false"; @@ -6938,28 +6915,28 @@ static void commandFuncGetAccountInfo(Command const &, NetworkId const &actor, N // ---------------------------------------------------------------------- -static void commandFuncApplyPowerup (Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) +static void commandFuncApplyPowerup(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { - const NetworkId & powerupId = target; - const NetworkId targetOfApplyId (Unicode::wideToNarrow (params)); - ServerObject * const powerup = safe_cast(NetworkIdManager::getObjectById (powerupId)); + const NetworkId & powerupId = target; + const NetworkId targetOfApplyId(Unicode::wideToNarrow(params)); + ServerObject * const powerup = safe_cast(NetworkIdManager::getObjectById(powerupId)); if (powerup) { - const ServerObject * const targetOfApply = safe_cast(NetworkIdManager::getObjectById (targetOfApplyId)); + const ServerObject * const targetOfApply = safe_cast(NetworkIdManager::getObjectById(targetOfApplyId)); if (targetOfApply) { - const int got_targetOfApply = targetOfApply->getGameObjectType (); - const int got_powerup = powerup->getGameObjectType (); + const int got_targetOfApply = targetOfApply->getGameObjectType(); + const int got_powerup = powerup->getGameObjectType(); - if (GameObjectTypes::doesPowerupApply (got_powerup, got_targetOfApply)) + if (GameObjectTypes::doesPowerupApply(got_powerup, got_targetOfApply)) { GameScriptObject * const gso = powerup->getScriptObject(); if (gso) { ScriptParams scriptParams; - scriptParams.addParam (actor); - scriptParams.addParam (targetOfApplyId); + scriptParams.addParam(actor); + scriptParams.addParam(targetOfApplyId); gso->trigAllScripts(Scripting::TRIG_APPLY_POWERUP, scriptParams); } } @@ -6969,20 +6946,20 @@ static void commandFuncApplyPowerup (Command const &, NetworkId const &actor, Ne // ---------------------------------------------------------------------- -static void commandFuncLag (Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) +static void commandFuncLag(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { #if 0 ServerObject * a = safe_cast(NetworkIdManager::getObjectById(actor)); ServerObject * t = safe_cast(NetworkIdManager::getObjectById(target)); - if(! t) + if (!t) { t = a; } - if(t != 0) + if (t != 0) { - if(t->getClient()) + if (t->getClient()) { - if(a && a->getClient()) + if (a && a->getClient()) { GameNetworkMessage const request("LagRequest"); t->getClient()->send(request, true); @@ -7001,7 +6978,7 @@ static void commandFuncLag (Command const &, NetworkId const &actor, NetworkId c // ---------------------------------------------------------------------- -static void commandExecuteKnowledgeBaseMessage (Command const &, NetworkId const &actor, NetworkId const & , Unicode::String const ¶ms) +static void commandExecuteKnowledgeBaseMessage(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { UNREF(actor); UNREF(params); @@ -7030,7 +7007,7 @@ static void commandFuncSetPlayerAppearance(Command const &, NetworkId const &act std::string objectTemplateName; bool useTarget = false; - size_t pos = 0; + size_t pos = 0; do { @@ -7042,15 +7019,15 @@ static void commandFuncSetPlayerAppearance(Command const &, NetworkId const &act } while (!token.empty()); //-- Log attempt. - NetworkId subjectNetworkId = useTarget ? target: actor; + NetworkId subjectNetworkId = useTarget ? target : actor; - LOG("setPlayerAppearance", + LOG("setPlayerAppearance", ("commandFuncSetPlayerAppearance(): command called by actor id=[%s]: attempting to change appearance for player id=[%s], using appearance info from object template=[%s], subject=[%s]", - actor.getValueString().c_str(), - subjectNetworkId.getValueString().c_str(), - objectTemplateName.c_str(), - useTarget ? "target" : "self" - )); + actor.getValueString().c_str(), + subjectNetworkId.getValueString().c_str(), + objectTemplateName.c_str(), + useTarget ? "target" : "self" + )); //-- Validate parameters. if (subjectNetworkId == NetworkId::cms_invalid) @@ -7076,11 +7053,11 @@ static void commandFuncSetPlayerAppearance(Command const &, NetworkId const &act // Ensure non-default object template name refers to an existing file. if (!TreeFile::exists(objectTemplateName.c_str())) { - WARNING(true, + WARNING(true, ("commandFuncSetPlayerAppearance(): could not change id=[%s] to non-default object template name=[%s]: object template does not exist", - subjectNetworkId.getValueString().c_str(), - objectTemplateName.c_str() - )); + subjectNetworkId.getValueString().c_str(), + objectTemplateName.c_str() + )); return; } } @@ -7104,7 +7081,7 @@ static void commandFuncRevertPlayerAppearance(Command const &, NetworkId const & std::string objectTemplateName; bool useTarget = false; - size_t pos = 0; + size_t pos = 0; do { @@ -7116,15 +7093,15 @@ static void commandFuncRevertPlayerAppearance(Command const &, NetworkId const & } while (!token.empty()); //-- Log attempt. - NetworkId subjectNetworkId = useTarget ? target: actor; + NetworkId subjectNetworkId = useTarget ? target : actor; - LOG("setPlayerAppearance", + LOG("setPlayerAppearance", ("commandFuncRevertPlayerAppearance(): command called by actor id=[%s]: attempting to change appearance for player id=[%s], using appearance info from object template=[%s], subject=[%s]", - actor.getValueString().c_str(), - subjectNetworkId.getValueString().c_str(), - objectTemplateName.c_str(), - useTarget ? "target" : "self" - )); + actor.getValueString().c_str(), + subjectNetworkId.getValueString().c_str(), + objectTemplateName.c_str(), + useTarget ? "target" : "self" + )); //-- Validate parameters. if (subjectNetworkId == NetworkId::cms_invalid) @@ -7155,7 +7132,7 @@ static void commandFuncRevertPlayerAppearance(Command const &, NetworkId const & //----------------------------------------------------------------------- -static void commandFuncReconnectToTransferServer(Command const &, NetworkId const &, NetworkId const & , Unicode::String const &) +static void commandFuncReconnectToTransferServer(Command const &, NetworkId const &, NetworkId const &, Unicode::String const &) { GameNetworkMessage const msg("ReconnectToTransferServer"); GameServer::getInstance().sendToCentralServer(msg); @@ -7163,17 +7140,17 @@ static void commandFuncReconnectToTransferServer(Command const &, NetworkId cons //----------------------------------------------------------------------- -static void commandFuncFindFriend(Command const &, NetworkId const &actor, NetworkId const & , Unicode::String const ¶ms) +static void commandFuncFindFriend(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { ServerObject * a = safe_cast(NetworkIdManager::getObjectById(actor)); - if(a && a->getClient()) + if (a && a->getClient()) { size_t pos = 0; - const std::string playerName = nextStringParm (params, pos); + const std::string playerName = nextStringParm(params, pos); CreatureObject * creatureObject = a->asCreatureObject(); - if(creatureObject) + if (creatureObject) { - if(! playerName.empty()) + if (!playerName.empty()) { // break the name down into its subcomponents ChatAvatarId const cav(NameManager::normalizeName(playerName)); @@ -7190,7 +7167,7 @@ static void commandFuncFindFriend(Command const &, NetworkId const &actor, Netwo else { PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(creatureObject); - if(playerObject) + if (playerObject) { playerObject->findFriend(cav.name); } @@ -7200,7 +7177,7 @@ static void commandFuncFindFriend(Command const &, NetworkId const &actor, Netwo { // playerName is empty, send an error to requesting client StringId stringId = StringId("ui_cmnty", "friend_location_failed_usage"); - Chat::sendSystemMessage(*creatureObject, stringId, Unicode::emptyString); + Chat::sendSystemMessage(*creatureObject, stringId, Unicode::emptyString); } } } @@ -7213,87 +7190,87 @@ static void commandFuncFormCommand(Command const &, NetworkId const & actor, Net UNREF(target); Unicode::UnicodeStringVector tokens; - IGNORE_RETURN(Unicode::tokenize (params, tokens)); + IGNORE_RETURN(Unicode::tokenize(params, tokens)); - if(tokens.size() == 0) + if (tokens.size() == 0) return; std::string const commandStr = Unicode::wideToNarrow(tokens[0]); FormManager::Command const command = static_cast(atoi(commandStr.c_str())); - switch(command) + switch (command) { - case FormManager::CREATE_OBJECT: + case FormManager::CREATE_OBJECT: + { + if (tokens.size() < 5) + return; + + std::string const templateName = Unicode::wideToNarrow(tokens[1]); + + std::string const & xStr = Unicode::wideToNarrow(tokens[2]); + std::string const & yStr = Unicode::wideToNarrow(tokens[3]); + std::string const & zStr = Unicode::wideToNarrow(tokens[4]); + std::string const & cellStr = Unicode::wideToNarrow(tokens[5]); + NetworkId const cellId(cellStr); + + float const x = static_cast(atof(xStr.c_str())); + float const y = static_cast(atof(yStr.c_str())); + float const z = static_cast(atof(zStr.c_str())); + + //we must have an odd number of tokens left (so that the datamap has a full key->value mapping) + if (tokens.size() % 2 != 0) + return; + + //TODO centralize pack/unpack + FormManager::UnpackedFormData dataMap; + std::vector values; + for (int i = 6; i < static_cast(tokens.size()) - 1; i += 2) { - if(tokens.size() < 5) - return; - - std::string const templateName = Unicode::wideToNarrow(tokens[1]); - - std::string const & xStr = Unicode::wideToNarrow(tokens[2]); - std::string const & yStr = Unicode::wideToNarrow(tokens[3]); - std::string const & zStr = Unicode::wideToNarrow(tokens[4]); - std::string const & cellStr = Unicode::wideToNarrow(tokens[5]); - NetworkId const cellId(cellStr); - - float const x = static_cast(atof(xStr.c_str())); - float const y = static_cast(atof(yStr.c_str())); - float const z = static_cast(atof(zStr.c_str())); - - //we must have an odd number of tokens left (so that the datamap has a full key->value mapping) - if(tokens.size() % 2 != 0) - return; - - //TODO centralize pack/unpack - FormManager::UnpackedFormData dataMap; - std::vector values; - for(int i = 6; i < static_cast(tokens.size()) - 1; i += 2) - { - std::string const & key = Unicode::wideToNarrow(tokens[static_cast(i)]); - std::string const & value = Unicode::wideToNarrow(tokens[static_cast(i + 1)]); - values.clear(); - values.push_back(value); - dataMap[key] = values; - } - - FormManagerServer::handleCreateObjectData(actor, templateName, Vector(x, y, z), cellId, dataMap); - break; + std::string const & key = Unicode::wideToNarrow(tokens[static_cast(i)]); + std::string const & value = Unicode::wideToNarrow(tokens[static_cast(i + 1)]); + values.clear(); + values.push_back(value); + dataMap[key] = values; } - case FormManager::EDIT_OBJECT: + FormManagerServer::handleCreateObjectData(actor, templateName, Vector(x, y, z), cellId, dataMap); + break; + } + + case FormManager::EDIT_OBJECT: + { + if (tokens.size() < 1) + return; + + //we must have an even number of tokens left (so that the datamap has a full key->value mapping) + if (tokens.size() % 2 != 1) + return; + + //TODO centralize pack/unpack + FormManager::UnpackedFormData dataMap; + std::vector values; + for (int i = 1; i < static_cast(tokens.size()) - 1; i += 2) { - if(tokens.size() < 1) - return; - - //we must have an even number of tokens left (so that the datamap has a full key->value mapping) - if(tokens.size() % 2 != 1) - return; - - //TODO centralize pack/unpack - FormManager::UnpackedFormData dataMap; - std::vector values; - for(int i = 1; i < static_cast(tokens.size()) - 1; i += 2) - { - std::string const & key = Unicode::wideToNarrow(tokens[static_cast(i)]); - std::string const & value = Unicode::wideToNarrow(tokens[static_cast(i + 1)]); - values.clear(); - values.push_back(value); - dataMap[key] = values; - } - - FormManagerServer::handleEditObjectData(actor, target, dataMap); - break; + std::string const & key = Unicode::wideToNarrow(tokens[static_cast(i)]); + std::string const & value = Unicode::wideToNarrow(tokens[static_cast(i + 1)]); + values.clear(); + values.push_back(value); + dataMap[key] = values; } - case FormManager::REQUEST_EDIT_OBJECT: - { - FormManagerServer::requestEditObjectDataForClient(actor, target); - break; - } + FormManagerServer::handleEditObjectData(actor, target, dataMap); + break; + } - default: - DEBUG_FATAL(true, ("Unknown command in commandFuncFormCommand")); - break; + case FormManager::REQUEST_EDIT_OBJECT: + { + FormManagerServer::requestEditObjectDataForClient(actor, target); + break; + } + + default: + DEBUG_FATAL(true, ("Unknown command in commandFuncFormCommand")); + break; } } @@ -7302,25 +7279,25 @@ static void commandFuncFormCommand(Command const &, NetworkId const & actor, Net static void commandFuncInstallShipComponents(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) { //params for installShipComponent are " " - + Object const * const actorObj = NetworkIdManager::getObjectById(actor); ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; - if(!actorCreature) + if (!actorCreature) { return; } //they must be near a space terminal (if not a god) Client const * const client = actorCreature->getClient(); - if(!client) + if (!client) return; - if(!client->isGod()) + if (!client->isGod()) { Object * const targetObj = NetworkIdManager::getObjectById(target); ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : nullptr; - if( !targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && - (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe)) ) + if (!targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && + (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe))) return; } else @@ -7333,7 +7310,7 @@ static void commandFuncInstallShipComponents(Command const &, NetworkId const & Object * const shipObj = NetworkIdManager::getObjectById(shipId); ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : nullptr; ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : nullptr; - if(!ship) + if (!ship) return; ShipChassisSlotType::Type const slotType = static_cast(nextIntParm(params, pos)); @@ -7341,7 +7318,7 @@ static void commandFuncInstallShipComponents(Command const &, NetworkId const & Object * const componentObj = NetworkIdManager::getObjectById(componentId); ServerObject * const componentServerObj = componentObj ? componentObj->asServerObject() : nullptr; TangibleObject * const component = componentServerObj ? componentServerObj->asTangibleObject() : nullptr; - if(!component) + if (!component) { return; } @@ -7363,14 +7340,14 @@ static void commandFuncInstallShipComponents(Command const &, NetworkId const & if (containedByObject) { SlottedContainer const * const slottedContainer = ContainerInterface::getSlottedContainer(*containedByObject); - if(slottedContainer) + if (slottedContainer) { SlotId const & slotId = slottedContainer->findFirstSlotIdForObject(component->getNetworkId()); - if(slotId != SlotId::invalid) + if (slotId != SlotId::invalid) { - if(!ContainerInterface::canPlayerManipulateSlot(slotId)) + if (!ContainerInterface::canPlayerManipulateSlot(slotId)) { - StringId cantManipulateId("player_utility", "cannot_manipulate_slot"); + StringId cantManipulateId("player_utility", "cannot_manipulate_slot"); Chat::sendSystemMessage(*actorCreature, cantManipulateId, Unicode::emptyString); return; } @@ -7391,23 +7368,23 @@ static void commandFuncUninstallShipComponents(Command const &, NetworkId const Object * const actorObj = NetworkIdManager::getObjectById(actor); ServerObject * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; CreatureObject * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; - if(!actorCreature) + if (!actorCreature) return; ServerObject * const actorInv = actorCreature->getInventory(); - if(!actorInv) + if (!actorInv) return; //they must be near a space terminal (if not a god) Client const * const client = actorCreature->getClient(); - if(!client) + if (!client) return; - if(!client->isGod()) + if (!client->isGod()) { Object * const targetObj = NetworkIdManager::getObjectById(target); ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : nullptr; - if(!targetServerObj || - ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) - && (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe)) ) + if (!targetServerObj || + ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) + && (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe))) return; } else @@ -7416,13 +7393,13 @@ static void commandFuncUninstallShipComponents(Command const &, NetworkId const } ServerObject const * const actorInventoryObject = actorCreature->getInventory(); - if(!actorInventoryObject) + if (!actorInventoryObject) { Chat::sendSystemMessage(*actorCreature, SharedStringIds::shipcomponentinstall_noinventory, Unicode::emptyString); return; } VolumeContainer const * const inventoryContainer = ContainerInterface::getVolumeContainer(*actorInventoryObject); - if(!inventoryContainer) + if (!inventoryContainer) { Chat::sendSystemMessage(*actorCreature, SharedStringIds::shipcomponentinstall_noinventorycontainer, Unicode::emptyString); return; @@ -7438,7 +7415,7 @@ static void commandFuncUninstallShipComponents(Command const &, NetworkId const Object * const shipObj = NetworkIdManager::getObjectById(shipId); ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : nullptr; ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : nullptr; - if(!ship) + if (!ship) return; ShipChassisSlotType::Type const slotType = static_cast(nextIntParm(params, pos)); @@ -7446,7 +7423,6 @@ static void commandFuncUninstallShipComponents(Command const &, NetworkId const IGNORE_RETURN(ship->uninstallComponent(actor, slotType, *actorInv)); } - // ---------------------------------------------------------------------- static void commandFuncInsertItemIntoShipComponentSlot(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) @@ -7456,19 +7432,19 @@ static void commandFuncInsertItemIntoShipComponentSlot(Command const &, NetworkI Object * const actorObj = NetworkIdManager::getObjectById(actor); ServerObject * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; CreatureObject * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; - if(!actorCreature) + if (!actorCreature) return; //they must be near a space terminal (if not a god) Client const * const client = actorCreature->getClient(); - if(!client) + if (!client) return; - if(!client->isGod()) + if (!client->isGod()) { Object * const targetObj = NetworkIdManager::getObjectById(target); ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : nullptr; - if(!targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && - (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe)) ) + if (!targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && + (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe))) return; } else @@ -7481,12 +7457,12 @@ static void commandFuncInsertItemIntoShipComponentSlot(Command const &, NetworkI Object * const shipObj = NetworkIdManager::getObjectById(shipId); ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : nullptr; ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : nullptr; - if(!ship) + if (!ship) return; ShipChassisSlotType::Type const slotType = static_cast(nextIntParm(params, pos)); - if(!ship->isSlotInstalled(slotType)) + if (!ship->isSlotInstalled(slotType)) return; NetworkId const componentId = nextOidParm(params, pos); @@ -7514,14 +7490,14 @@ static void commandFuncAssociateDroidControlDeviceWithShip(Command const &, Netw //they must be near a space terminal (if not a god) Client const * const client = actorCreature->getClient(); - if(!client) + if (!client) return; - if(!client->isGod()) + if (!client->isGod()) { Object * const targetObj = NetworkIdManager::getObjectById(target); ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : nullptr; - if(!targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && - (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe)) ) + if (!targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && + (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe))) return; } else @@ -7534,7 +7510,7 @@ static void commandFuncAssociateDroidControlDeviceWithShip(Command const &, Netw Object * const shipObj = NetworkIdManager::getObjectById(shipId); ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : nullptr; ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : nullptr; - if(!ship) + if (!ship) return; NetworkId const droidControlDeviceId = nextOidParm(params, pos); @@ -7558,12 +7534,12 @@ static void commandFuncAssociateDroidControlDeviceWithShip(Command const &, Netw // ---------------------------------------------------------------------- -static void commandFuncServerAsteroidDataListen(Command const &, NetworkId const & actor, NetworkId const & , Unicode::String const & ) +static void commandFuncServerAsteroidDataListen(Command const &, NetworkId const & actor, NetworkId const &, Unicode::String const &) { Object const * const actorObj = NetworkIdManager::getObjectById(actor); ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; - if(!actorCreature) + if (!actorCreature) return; ServerAsteroidManager::listenforServerAsteroidDebugData(actor); @@ -7571,12 +7547,12 @@ static void commandFuncServerAsteroidDataListen(Command const &, NetworkId const // ---------------------------------------------------------------------- -static void commandFuncServerAsteroidDataStopListening(Command const &, NetworkId const & actor, NetworkId const & , Unicode::String const & ) +static void commandFuncServerAsteroidDataStopListening(Command const &, NetworkId const & actor, NetworkId const &, Unicode::String const &) { Object const * const actorObj = NetworkIdManager::getObjectById(actor); ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; - if(!actorCreature) + if (!actorCreature) return; ServerAsteroidManager::endListenforServerAsteroidDebugData(actor); @@ -7603,21 +7579,21 @@ static void commandFuncSetFormation(Command const &, NetworkId const & actor, Ne Object * const o = NetworkIdManager::getObjectById(actor); ServerObject * const so = o ? o->asServerObject() : nullptr; CreatureObject * const actorCreature = so ? so->asCreatureObject() : nullptr; - if(actorCreature) + if (actorCreature) { GroupObject * const group = actorCreature->getGroup(); - if(group) + if (group) { - if(group->getGroupLeaderId() == actor) + if (group->getGroupLeaderId() == actor) { std::string paramsNarrow = Unicode::wideToNarrow(params); - if(paramsNarrow == "none") + if (paramsNarrow == "none") { group->setFormationNameCrc(Crc::crcNull); } else { - if(PlayerFormationManager::isValidFormationName(paramsNarrow)) + if (PlayerFormationManager::isValidFormationName(paramsNarrow)) group->setFormationNameCrc(Crc::normalizeAndCalculate(paramsNarrow.c_str())); } } @@ -7683,20 +7659,20 @@ static void commandFuncUnDock(Command const &, NetworkId const & actor, NetworkI WARNING(true, ("commandFuncUnDock() Undock requested on a nullptr object(%s).", actor.getValueString().c_str())); } } - + //---------------------------------------------------------------------- static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; - if(!actorCreature) + if (!actorCreature) { WARNING(true, ("No actorCreature in commandFuncLaunchIntoSpace")); return; } - if(!target.isValid()) + if (!target.isValid()) { StringId invalidTargetId("player_utility", "invalid_target"); Chat::sendSystemMessage(*actorCreature, invalidTargetId, Unicode::emptyString); @@ -7706,13 +7682,13 @@ static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, //target must be a space terminal Object const * const o = NetworkIdManager::getObjectById(target); ServerObject const * const so = o ? o->asServerObject() : nullptr; - if(!so) + if (!so) { StringId invalidTargetId("player_utility", "target_not_server_object"); Chat::sendSystemMessage(*actorCreature, invalidTargetId, Unicode::emptyString); return; } - if(so->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) + if (so->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) { ProsePackage p; p.stringId = StringId("player_utility", "not_space_terminal"); @@ -7724,35 +7700,35 @@ static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, } Unicode::UnicodeStringVector tokens; - Unicode::tokenize (params, tokens); - - if(tokens.empty()) + Unicode::tokenize(params, tokens); + + if (tokens.empty()) { Chat::sendSystemMessage(*actorCreature, Unicode::narrowToWide("(unlocalized) No parameters."), Unicode::emptyString); return; } NetworkId const shipPCDId(Unicode::wideToNarrow(tokens[0]).c_str()); - if(!shipPCDId.isValid()) + if (!shipPCDId.isValid()) { Chat::sendSystemMessage(*actorCreature, Unicode::narrowToWide("(unlocalized) Invalid ship."), Unicode::emptyString); return; } Object * const terminalO = NetworkIdManager::getObjectById(target); ServerObject * const terminalSO = terminalO ? terminalO->asServerObject() : nullptr; - if(terminalSO) + if (terminalSO) { std::vector networkIds; unsigned int tokenIndex = 1; - if(tokens.size() > tokenIndex) + if (tokens.size() > tokenIndex) { int const numberOfNetworkIds = atoi(Unicode::wideToNarrow(tokens[tokenIndex]).c_str()); for (int i = 0; i < numberOfNetworkIds; ++i) { ++tokenIndex; - if(tokens.size() > tokenIndex) + if (tokens.size() > tokenIndex) { NetworkId const Id(Unicode::wideToNarrow(tokens[tokenIndex])); if (Id.isValid()) @@ -7761,13 +7737,13 @@ static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, } } } - } + } ++tokenIndex; //adding an empty string is fine (it means they aren't traveling to another ground starport) std::string strPointPlanetResult; - if(tokens.size() > tokenIndex) + if (tokens.size() > tokenIndex) { strPointPlanetResult = Unicode::wideToNarrow(tokens[tokenIndex]); } @@ -7776,10 +7752,10 @@ static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, //adding an empty string is fine (it means they aren't traveling to another ground starport) std::string strPointLocationResult; - if(tokens.size() > tokenIndex) + if (tokens.size() > tokenIndex) { strPointLocationResult = Unicode::wideToNarrow(tokens[tokenIndex]); - std::replace (strPointLocationResult.begin (), strPointLocationResult.end (), '_', ' '); + std::replace(strPointLocationResult.begin(), strPointLocationResult.end(), '_', ' '); } ScriptParams params; @@ -7805,20 +7781,20 @@ static void commandFuncAcceptQuest(Command const &, NetworkId const & actor, Net { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; - if(!actorCreature) + if (!actorCreature) { WARNING(true, ("No actorCreature in commandFuncAcceptQuest")); return; } PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(actorCreature); - if(!playerObject) + if (!playerObject) { WARNING(true, ("No playerObject in commandFuncAcceptQuest")); return; } uint32 const questCrc = atoi(Unicode::wideToNarrow(params).c_str()); - if(playerObject->getPendingRequestQuestCrc() == questCrc) + if (playerObject->getPendingRequestQuestCrc() == questCrc) { NetworkId const & questGiver = playerObject->getPendingRequestQuestGiver(); playerObject->questActivateQuest(questCrc, questGiver); @@ -7832,29 +7808,29 @@ static void commandFuncReceiveReward(Command const &, NetworkId const & actor, N { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; - if(!actorCreature) + if (!actorCreature) { WARNING(true, ("No actorCreature in commandFuncReceiveReward")); return; } PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(actorCreature); - if(!playerObject) + if (!playerObject) { WARNING(true, ("No playerObject in commandFuncReceiveReward")); return; } Unicode::UnicodeStringVector sv; - Unicode::tokenize (params, sv); - - if(sv.empty()) + Unicode::tokenize(params, sv); + + if (sv.empty()) return; uint32 const questCrc = atoi(Unicode::wideToNarrow(sv[0]).c_str()); std::string selectedReward; - if(sv.size() > 1) + if (sv.size() > 1) selectedReward = Unicode::wideToNarrow(sv[1]); - if((playerObject->getPendingRequestQuestCrc() == questCrc) || playerObject->questPlayerCanClaimRewardFor(questCrc)) + if ((playerObject->getPendingRequestQuestCrc() == questCrc) || playerObject->questPlayerCanClaimRewardFor(questCrc)) { playerObject->questGrantQuestReward(questCrc, selectedReward); playerObject->setPendingRequestQuestInformation(0, NetworkId::cms_invalid); @@ -7863,26 +7839,26 @@ static void commandFuncReceiveReward(Command const &, NetworkId const & actor, N //---------------------------------------------------------------------- -static void commandFuncAbandonQuest(Command const &, NetworkId const & actor, NetworkId const & , Unicode::String const & params) +static void commandFuncAbandonQuest(Command const &, NetworkId const & actor, NetworkId const &, Unicode::String const & params) { size_t pos = 0; - + //not currently used, but can distinguish between different quest types int const questSystemType = nextIntParm(params, pos); UNREF(questSystemType); std::string const & questName = nextStringParm(params, pos); - if(QuestManager::isQuestAbandonable(questName)) + if (QuestManager::isQuestAbandonable(questName)) { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; - if(actorCreature) + if (actorCreature) { PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(actorCreature); - if(playerObject) + if (playerObject) { Quest const * const q = QuestManager::getQuest(questName); - if(q && playerObject->questHasActiveQuest(q->getId()) && !playerObject->questHasCompletedQuest(q->getId())) + if (q && playerObject->questHasActiveQuest(q->getId()) && !playerObject->questHasCompletedQuest(q->getId())) { LOG("Quest", ("Abandon:%s abandoned quest [%s] with status [0x%08X].\n", PlayerObject::getAccountDescription(actorServerObj->getClient()->getCharacterObjectId()).c_str(), @@ -7895,43 +7871,39 @@ static void commandFuncAbandonQuest(Command const &, NetworkId const & actor, Ne } } - - // ---------------------------------------------------------------------- static void commandFuncExchangeListCredits(Command const &, NetworkId const &actor, NetworkId const &target, Unicode::String const ¶ms) { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; - if(!actorCreature) + if (!actorCreature) { WARNING(true, ("No actorCreature in commandFuncReceiveReward")); return; } PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(actorCreature); - if(!playerObject) + if (!playerObject) { WARNING(true, ("No playerObject in commandFuncReceiveReward")); return; } Unicode::UnicodeStringVector sv; - Unicode::tokenize (params, sv); - - if(sv.empty()) + Unicode::tokenize(params, sv); + + if (sv.empty()) return; uint32 const credits = (uint32)atoi(Unicode::wideToNarrow(sv[0]).c_str()); - if ( credits <= 0 ) + if (credits <= 0) return; - char message[512]; - sprintf(message,"Listing %ld credits on station exchange.", credits); + sprintf(message, "Listing %ld credits on station exchange.", credits); Chat::sendSystemMessage(*actorCreature, Unicode::narrowToWide(message), Unicode::emptyString); - ExchangeListCreditsMessage const msg(actor, credits, GameServer::getInstance().getProcessId()); - GameServer::getInstance().sendToCentralServer(msg); + GameServer::getInstance().sendToCentralServer(msg); } //----------------------------------------------------------------------- @@ -7955,8 +7927,8 @@ static void commandFuncSquelch(Command const &, NetworkId const &actor, NetworkI ServerObject * so = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!so) { - snprintf(buffer, sizeof(buffer)-1, "Error! Cannot find object for %s", target.getValueString().c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! Cannot find object for %s", target.getValueString().c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -7965,8 +7937,8 @@ static void commandFuncSquelch(Command const &, NetworkId const &actor, NetworkI CreatureObject * c = so->asCreatureObject(); if (!c) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -7975,22 +7947,22 @@ static void commandFuncSquelch(Command const &, NetworkId const &actor, NetworkI PlayerObject * p = PlayerCreatureController::getPlayerObject(c); if (!p) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else if (p->getSecondsUntilUnsquelched() < 0) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is already squelched", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is already squelched", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else { - snprintf(buffer, sizeof(buffer)-1, "Squelching %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Squelching %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); @@ -8024,8 +7996,8 @@ static void commandFuncUnsquelch(Command const &, NetworkId const &actor, Networ ServerObject * so = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!so) { - snprintf(buffer, sizeof(buffer)-1, "Error! Cannot find object for %s", target.getValueString().c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! Cannot find object for %s", target.getValueString().c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8034,8 +8006,8 @@ static void commandFuncUnsquelch(Command const &, NetworkId const &actor, Networ CreatureObject * c = so->asCreatureObject(); if (!c) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8044,22 +8016,22 @@ static void commandFuncUnsquelch(Command const &, NetworkId const &actor, Networ PlayerObject * p = PlayerCreatureController::getPlayerObject(c); if (!p) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else if (p->getSecondsUntilUnsquelched() == 0) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not currently squelched", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not currently squelched", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else { - snprintf(buffer, sizeof(buffer)-1, "Unsquelching %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Unsquelching %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); @@ -8093,8 +8065,8 @@ static void commandFuncGrantWarden(Command const &, NetworkId const &actor, Netw ServerObject * so = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!so) { - snprintf(buffer, sizeof(buffer)-1, "Error! Cannot find object for %s", target.getValueString().c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! Cannot find object for %s", target.getValueString().c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8103,8 +8075,8 @@ static void commandFuncGrantWarden(Command const &, NetworkId const &actor, Netw CreatureObject * c = so->asCreatureObject(); if (!c) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8113,22 +8085,22 @@ static void commandFuncGrantWarden(Command const &, NetworkId const &actor, Netw PlayerObject * p = PlayerCreatureController::getPlayerObject(c); if (!p) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else if (p->isWarden()) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is already a warden", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is already a warden", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else { - snprintf(buffer, sizeof(buffer)-1, "Granting warden to %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Granting warden to %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); @@ -8164,8 +8136,8 @@ static void commandFuncRevokeWarden(Command const &, NetworkId const &actor, Net ServerObject * so = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!so) { - snprintf(buffer, sizeof(buffer)-1, "Error! Cannot find object for %s", target.getValueString().c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! Cannot find object for %s", target.getValueString().c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8174,8 +8146,8 @@ static void commandFuncRevokeWarden(Command const &, NetworkId const &actor, Net CreatureObject * c = so->asCreatureObject(); if (!c) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8184,22 +8156,22 @@ static void commandFuncRevokeWarden(Command const &, NetworkId const &actor, Net PlayerObject * p = PlayerCreatureController::getPlayerObject(c); if (!p) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else if (!p->isWarden()) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a warden", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a warden", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else { - snprintf(buffer, sizeof(buffer)-1, "Revoking warden from %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Revoking warden from %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); @@ -8273,8 +8245,8 @@ static void commandFuncSpammer(Command const &, NetworkId const &actor, NetworkI { // send a messageTo to the target to do apply the /spammer operation char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s %s", actor.getValueString().c_str(), Unicode::wideToNarrow(gm->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s %s", actor.getValueString().c_str(), Unicode::wideToNarrow(gm->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(parsedNetworkId, "C++SpammerReq", @@ -8534,8 +8506,8 @@ static void commandFuncDeputizeWarden(Command const &, NetworkId const &actor, N // send a messageTo to the target to complete the deputize process char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s|%lu", gm->getNetworkId().getValueString().c_str(), gmPlayerObject->getStationId()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s|%lu", gm->getNetworkId().getValueString().c_str(), gmPlayerObject->getStationId()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(parsedNetworkId, "C++DeputizeWardenReq", @@ -8597,8 +8569,8 @@ static void commandFuncUndeputizeWarden(Command const &, NetworkId const &actor, // send a messageTo to the target to complete the undeputize process char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s|%lu", gm->getNetworkId().getValueString().c_str(), gmPlayerObject->getStationId()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s|%lu", gm->getNetworkId().getValueString().c_str(), gmPlayerObject->getStationId()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(parsedNetworkId, "C++UndeputizeWardenReq", @@ -8613,7 +8585,7 @@ static void commandFuncUndeputizeWarden(Command const &, NetworkId const &actor, //----------------------------------------------------------------------- -static void commandFuncRemoveBuff(Command const &, NetworkId const &actor, NetworkId const & , Unicode::String const ¶ms) +static void commandFuncRemoveBuff(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { CreatureObject * player = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (player) @@ -8679,7 +8651,7 @@ static void commandFuncOccupyUnlockedSlot(Command const &, NetworkId const &acto } // CS log the request - LOG("CustomerService",("JediUnlockedSlot:%s requesting OccupyUnlockedSlot", PlayerObject::getAccountDescription(gm).c_str())); + LOG("CustomerService", ("JediUnlockedSlot:%s requesting OccupyUnlockedSlot", PlayerObject::getAccountDescription(gm).c_str())); // send off request to LoginServer to make this character occupy the unlocked slot GenericValueTypeMessage, uint32> > const occupyUnlockedSlotReq("OccupyUnlockedSlotReq", std::make_pair(std::make_pair(static_cast(gmPlayerObject->getStationId()), actor), GameServer::getInstance().getProcessId())); @@ -8745,7 +8717,7 @@ static void commandFuncVacateUnlockedSlot(Command const &, NetworkId const &acto } // CS log the request - LOG("CustomerService",("JediUnlockedSlot:%s requesting VacateUnlockedSlot", PlayerObject::getAccountDescription(gm).c_str())); + LOG("CustomerService", ("JediUnlockedSlot:%s requesting VacateUnlockedSlot", PlayerObject::getAccountDescription(gm).c_str())); // send off request to LoginServer to make this character vacate the unlocked slot GenericValueTypeMessage, uint32> > const vacateUnlockedSlotReq("VacateUnlockedSlotReq", std::make_pair(std::make_pair(static_cast(gmPlayerObject->getStationId()), actor), GameServer::getInstance().getProcessId())); @@ -8833,7 +8805,7 @@ static void commandFuncSwapUnlockedSlot(Command const &, NetworkId const &actor, } // CS log the request - LOG("CustomerService",("JediUnlockedSlot:%s requesting SwapUnlockedSlot with %s (%s)", PlayerObject::getAccountDescription(gm).c_str(), parsedNetworkId.getValueString().c_str(), NameManager::getInstance().getPlayerFullName(parsedNetworkId).c_str())); + LOG("CustomerService", ("JediUnlockedSlot:%s requesting SwapUnlockedSlot with %s (%s)", PlayerObject::getAccountDescription(gm).c_str(), parsedNetworkId.getValueString().c_str(), NameManager::getInstance().getPlayerFullName(parsedNetworkId).c_str())); // send off request to LoginServer to make this character normal and the target characer unlocked GenericValueTypeMessage, std::pair > > const swapUnlockedSlotReq("SwapUnlockedSlotReq", std::make_pair(std::make_pair(static_cast(gmPlayerObject->getStationId()), actor), std::make_pair(GameServer::getInstance().getProcessId(), parsedNetworkId))); @@ -9580,114 +9552,114 @@ static void commandFuncRoomPickRandomPlayer(Command const &, NetworkId const &ac void CommandCppFuncs::install() { // console style commands - CommandTable::addCppFunction("console_all", commandFuncConsoleAll); - CommandTable::addCppFunction("console_combat", commandFuncConsoleCombat); - CommandTable::addCppFunction("console_craft", commandFuncConsoleCraft); - CommandTable::addCppFunction("console_database", commandFuncConsoleDatabase); - CommandTable::addCppFunction("console_manufacture", commandFuncConsoleManufacture); - CommandTable::addCppFunction("console_money", commandFuncConsoleMoney); - CommandTable::addCppFunction("console_npc", commandFuncConsoleNpc); - CommandTable::addCppFunction("console_object", commandFuncConsoleObject); - CommandTable::addCppFunction("console_objvar", commandFuncConsoleObjvar); - CommandTable::addCppFunction("console_resource", commandFuncConsoleResource); - CommandTable::addCppFunction("console_script", commandFuncConsoleScript); - CommandTable::addCppFunction("console_server", commandFuncConsoleServer); - CommandTable::addCppFunction("console_skill", commandFuncConsoleSkill); + CommandTable::addCppFunction("console_all", commandFuncConsoleAll); + CommandTable::addCppFunction("console_combat", commandFuncConsoleCombat); + CommandTable::addCppFunction("console_craft", commandFuncConsoleCraft); + CommandTable::addCppFunction("console_database", commandFuncConsoleDatabase); + CommandTable::addCppFunction("console_manufacture", commandFuncConsoleManufacture); + CommandTable::addCppFunction("console_money", commandFuncConsoleMoney); + CommandTable::addCppFunction("console_npc", commandFuncConsoleNpc); + CommandTable::addCppFunction("console_object", commandFuncConsoleObject); + CommandTable::addCppFunction("console_objvar", commandFuncConsoleObjvar); + CommandTable::addCppFunction("console_resource", commandFuncConsoleResource); + CommandTable::addCppFunction("console_script", commandFuncConsoleScript); + CommandTable::addCppFunction("console_server", commandFuncConsoleServer); + CommandTable::addCppFunction("console_skill", commandFuncConsoleSkill); // communication commands - CommandTable::addCppFunction("social", commandFuncSocial); - CommandTable::addCppFunction("socialInternal", commandFuncSocialInternal); - CommandTable::addCppFunction("spatialChat", commandFuncSpatialChat); - CommandTable::addCppFunction("spatialChatInternal", commandFuncSpatialChatInternal); - CommandTable::addCppFunction("setMood", commandFuncSetMood); - CommandTable::addCppFunction("setMoodInternal", commandFuncSetMoodInternal); - CommandTable::addCppFunction("systemMessage", commandFuncSystemMessage); -// CommandTable::addCppFunction("combatSpam", commandFuncCombatSpam); + CommandTable::addCppFunction("social", commandFuncSocial); + CommandTable::addCppFunction("socialInternal", commandFuncSocialInternal); + CommandTable::addCppFunction("spatialChat", commandFuncSpatialChat); + CommandTable::addCppFunction("spatialChatInternal", commandFuncSpatialChatInternal); + CommandTable::addCppFunction("setMood", commandFuncSetMood); + CommandTable::addCppFunction("setMoodInternal", commandFuncSetMoodInternal); + CommandTable::addCppFunction("systemMessage", commandFuncSystemMessage); + // CommandTable::addCppFunction("combatSpam", commandFuncCombatSpam); - // admin commands - CommandTable::addCppFunction("admin_setGodMode", commandFuncAdminSetGodMode); - CommandTable::addCppFunction("admin_kick", commandFuncAdminKick); - CommandTable::addCppFunction("admin_planetwarp", commandFuncAdminPlanetwarp); - CommandTable::addCppFunction("admin_teleport", commandFuncAdminTeleport); - CommandTable::addCppFunction("admin_teleportTo", commandFuncAdminTeleportTo); - CommandTable::addCppFunction("admin_listGuilds", commandFuncAdminListGuilds); - CommandTable::addCppFunction("editBank", commandFuncAdminEditBank); - CommandTable::addCppFunction("editStats", commandFuncAdminEditStats); - CommandTable::addCppFunction("editAppearance", commandFuncAdminEditAppearance); - CommandTable::addCppFunction("grantTitle", commandFuncAdminGrantTitle); - CommandTable::addCppFunction("credits", commandFuncAdminCredits); - CommandTable::addCppFunction("getStationName", commandFuncAdminGetStationName); - CommandTable::addCppFunction("emptyMailTarget", commandFuncEmptyMailTarget); - CommandTable::addCppFunction("setPlayerAppearance", commandFuncSetPlayerAppearance); + // admin commands + CommandTable::addCppFunction("admin_setGodMode", commandFuncAdminSetGodMode); + CommandTable::addCppFunction("admin_kick", commandFuncAdminKick); + CommandTable::addCppFunction("admin_planetwarp", commandFuncAdminPlanetwarp); + CommandTable::addCppFunction("admin_teleport", commandFuncAdminTeleport); + CommandTable::addCppFunction("admin_teleportTo", commandFuncAdminTeleportTo); + CommandTable::addCppFunction("admin_listGuilds", commandFuncAdminListGuilds); + CommandTable::addCppFunction("editBank", commandFuncAdminEditBank); + CommandTable::addCppFunction("editStats", commandFuncAdminEditStats); + CommandTable::addCppFunction("editAppearance", commandFuncAdminEditAppearance); + CommandTable::addCppFunction("grantTitle", commandFuncAdminGrantTitle); + CommandTable::addCppFunction("credits", commandFuncAdminCredits); + CommandTable::addCppFunction("getStationName", commandFuncAdminGetStationName); + CommandTable::addCppFunction("emptyMailTarget", commandFuncEmptyMailTarget); + CommandTable::addCppFunction("setPlayerAppearance", commandFuncSetPlayerAppearance); CommandTable::addCppFunction("revertPlayerAppearance", commandFuncRevertPlayerAppearance); // auction commands - CommandTable::addCppFunction("auction_create", commandFuncAuctionCreate); - CommandTable::addCppFunction("auction_create_immediate", commandFuncAuctionCreateImmediate); - CommandTable::addCppFunction("auction_bid", commandFuncAuctionBid); - CommandTable::addCppFunction("auction_cancel", commandFuncAuctionCancel); - CommandTable::addCppFunction("auction_accept", commandFuncAuctionAccept); - CommandTable::addCppFunction("auction_query", commandFuncAuctionQuery); - CommandTable::addCppFunction("auction_retrieve", commandFuncAuctionRetrieve); + CommandTable::addCppFunction("auction_create", commandFuncAuctionCreate); + CommandTable::addCppFunction("auction_create_immediate", commandFuncAuctionCreateImmediate); + CommandTable::addCppFunction("auction_bid", commandFuncAuctionBid); + CommandTable::addCppFunction("auction_cancel", commandFuncAuctionCancel); + CommandTable::addCppFunction("auction_accept", commandFuncAuctionAccept); + CommandTable::addCppFunction("auction_query", commandFuncAuctionQuery); + CommandTable::addCppFunction("auction_retrieve", commandFuncAuctionRetrieve); // cell/building permissions commands - CommandTable::addCppFunction("addBannedPlayer", commandFuncAddBannedPlayer); - CommandTable::addCppFunction("removeBannedPlayer", commandFuncRemoveBannedPlayer); - CommandTable::addCppFunction("addAllowedPlayer", commandFuncAddAllowedPlayer); - CommandTable::addCppFunction("removeAllowedPlayer", commandFuncRemoveAllowedPlayer); - CommandTable::addCppFunction("setPublicState", commandFuncSetPublicState); - CommandTable::addCppFunction("setOwner", commandFuncSetOwner); + CommandTable::addCppFunction("addBannedPlayer", commandFuncAddBannedPlayer); + CommandTable::addCppFunction("removeBannedPlayer", commandFuncRemoveBannedPlayer); + CommandTable::addCppFunction("addAllowedPlayer", commandFuncAddAllowedPlayer); + CommandTable::addCppFunction("removeAllowedPlayer", commandFuncRemoveAllowedPlayer); + CommandTable::addCppFunction("setPublicState", commandFuncSetPublicState); + CommandTable::addCppFunction("setOwner", commandFuncSetOwner); - CommandTable::addCppFunction("setPosture", commandSetPosture); - CommandTable::addCppFunction("duel", commandFuncDuel); - CommandTable::addCppFunction("endDuel", commandFuncEndDuel); + CommandTable::addCppFunction("setPosture", commandSetPosture); + CommandTable::addCppFunction("duel", commandFuncDuel); + CommandTable::addCppFunction("endDuel", commandFuncEndDuel); // ui CommandTable::addCppFunction("setWaypointActiveStatus", commandFuncSetWaypointActiveStatus); - CommandTable::addCppFunction("setWaypointName", commandFuncSetWaypointName); + CommandTable::addCppFunction("setWaypointName", commandFuncSetWaypointName); // harvester - CommandTable::addCppFunction("harvesterActivate", commandFuncHarvesterActivate); - CommandTable::addCppFunction("harvesterDeactivate", commandFuncHarvesterDeactivate); - CommandTable::addCppFunction("harvesterHarvest", commandFuncHarvesterHarvest); - CommandTable::addCppFunction("harvesterSelectResource", commandFuncHarvesterSelectResource); - CommandTable::addCppFunction("harvesterDiscardHopper", commandFuncHarvesterDiscardHopper); - CommandTable::addCppFunction("harvesterMakeCrate", commandFuncHarvesterMakeCrate); - CommandTable::addCppFunction("harvesterGetResourceData", commandFuncHarvesterGetResourceData); + CommandTable::addCppFunction("harvesterActivate", commandFuncHarvesterActivate); + CommandTable::addCppFunction("harvesterDeactivate", commandFuncHarvesterDeactivate); + CommandTable::addCppFunction("harvesterHarvest", commandFuncHarvesterHarvest); + CommandTable::addCppFunction("harvesterSelectResource", commandFuncHarvesterSelectResource); + CommandTable::addCppFunction("harvesterDiscardHopper", commandFuncHarvesterDiscardHopper); + CommandTable::addCppFunction("harvesterMakeCrate", commandFuncHarvesterMakeCrate); + CommandTable::addCppFunction("harvesterGetResourceData", commandFuncHarvesterGetResourceData); // syncronized ui - CommandTable::addCppFunction("synchronizedUiListen" , commandFuncSynchronizedUiListen); - CommandTable::addCppFunction("synchronizedUiStopListening", commandFuncSynchronizedUiStopListening); + CommandTable::addCppFunction("synchronizedUiListen", commandFuncSynchronizedUiListen); + CommandTable::addCppFunction("synchronizedUiStopListening", commandFuncSynchronizedUiStopListening); // resource - CommandTable::addCppFunction("resourceSetName", commandFuncResourceSetName); + CommandTable::addCppFunction("resourceSetName", commandFuncResourceSetName); // resource container CommandTable::addCppFunction("resourceContainerTransfer", commandFuncResourceContainerTransfer); - CommandTable::addCppFunction("resourceContainerSplit", commandFuncResourceContainerSplit); + CommandTable::addCppFunction("resourceContainerSplit", commandFuncResourceContainerSplit); // survey - CommandTable::addCppFunction("makeSurvey", commandFuncMakeSurvey); - CommandTable::addCppFunction("requestSurvey", commandFuncRequestSurvey); - CommandTable::addCppFunction("requestCoreSample", commandFuncRequestCoreSample); + CommandTable::addCppFunction("makeSurvey", commandFuncMakeSurvey); + CommandTable::addCppFunction("requestSurvey", commandFuncRequestSurvey); + CommandTable::addCppFunction("requestCoreSample", commandFuncRequestCoreSample); - CommandTable::addCppFunction("transferItemWeapon", commandFuncTransferWeapon); - CommandTable::addCppFunction("transferItemArmor", commandFuncTransferArmor); - CommandTable::addCppFunction("transferItemMisc", commandFuncTransferMisc); - CommandTable::addCppFunction("openContainer", commandFuncOpenContainer); - CommandTable::addCppFunction("closeContainer", commandFuncCloseContainer); - CommandTable::addCppFunction("openLotteryContainer", commandFuncOpenLotteryContainer); + CommandTable::addCppFunction("transferItemWeapon", commandFuncTransferWeapon); + CommandTable::addCppFunction("transferItemArmor", commandFuncTransferArmor); + CommandTable::addCppFunction("transferItemMisc", commandFuncTransferMisc); + CommandTable::addCppFunction("openContainer", commandFuncOpenContainer); + CommandTable::addCppFunction("closeContainer", commandFuncCloseContainer); + CommandTable::addCppFunction("openLotteryContainer", commandFuncOpenLotteryContainer); CommandTable::addCppFunction("closeLotteryContainer", commandFuncCloseLotteryContainer); - CommandTable::addCppFunction("giveItem", commandFuncGiveItem); + CommandTable::addCppFunction("giveItem", commandFuncGiveItem); // grouping - CommandTable::addCppFunction("groupInvite", commandFuncGroupInvite); - CommandTable::addCppFunction("groupUninvite", commandFuncGroupUninvite); - CommandTable::addCppFunction("groupJoin", commandFuncGroupJoin); - CommandTable::addCppFunction("groupDecline", commandFuncGroupDecline); - CommandTable::addCppFunction("groupDisband", commandFuncGroupDisband); - CommandTable::addCppFunction("kickFromShip", commandFuncKickFromShip); - CommandTable::addCppFunction("groupChat", commandFuncGroupChat); + CommandTable::addCppFunction("groupInvite", commandFuncGroupInvite); + CommandTable::addCppFunction("groupUninvite", commandFuncGroupUninvite); + CommandTable::addCppFunction("groupJoin", commandFuncGroupJoin); + CommandTable::addCppFunction("groupDecline", commandFuncGroupDecline); + CommandTable::addCppFunction("groupDisband", commandFuncGroupDisband); + CommandTable::addCppFunction("kickFromShip", commandFuncKickFromShip); + CommandTable::addCppFunction("groupChat", commandFuncGroupChat); CommandTable::addCppFunction("groupMakeLeader", commandFuncGroupMakeLeader); CommandTable::addCppFunction("groupMakeMasterLooter", commandFuncGroupMakeMasterLooter); CommandTable::addCppFunction("createGroupPickup", commandFuncCreateGroupPickup); @@ -9696,102 +9668,102 @@ void CommandCppFuncs::install() CommandTable::addCppFunction("groupPickRandomGroupMember", commandFuncGroupPickRandomGroupMember); // guilds - CommandTable::addCppFunction("guildChat", commandFuncGuildChat); + CommandTable::addCppFunction("guildChat", commandFuncGuildChat); CommandTable::addCppFunction("guildTextChatRoomRejoin", commandFuncGuildTextChatRoomRejoin); CommandTable::addCppFunction("guildPickRandomGuildMember", commandFuncGuildPickRandomGuildMember); // city - CommandTable::addCppFunction("cityChat", commandFuncCityChat); + CommandTable::addCppFunction("cityChat", commandFuncCityChat); CommandTable::addCppFunction("cityTextChatRoomRejoin", commandFuncCityTextChatRoomRejoin); CommandTable::addCppFunction("cityPickRandomCitizen", commandFuncCityPickRandomCitizen); //chat - CommandTable::addCppFunction("auctionChat", commandFuncAuctionChat); - CommandTable::addCppFunction("planetChat", commandFuncPlanetChat); - + CommandTable::addCppFunction("auctionChat", commandFuncAuctionChat); + CommandTable::addCppFunction("planetChat", commandFuncPlanetChat); + // crafting - CommandTable::addCppFunction("requestResourceWeights", commandFuncRequestResourceWeights); + CommandTable::addCppFunction("requestResourceWeights", commandFuncRequestResourceWeights); CommandTable::addCppFunction("requestResourceWeightsBatch", commandFuncRequestResourceWeightsBatch); - CommandTable::addCppFunction("requestDraftSlots", commandFuncRequestDraftSlots); - CommandTable::addCppFunction("requestDraftSlotsBatch", commandFuncRequestDraftSlotsBatch); + CommandTable::addCppFunction("requestDraftSlots", commandFuncRequestDraftSlots); + CommandTable::addCppFunction("requestDraftSlotsBatch", commandFuncRequestDraftSlotsBatch); CommandTable::addCppFunction("requestManfSchematicSlots", commandFuncRequestManfSchematicSlots); - CommandTable::addCppFunction("requestCraftingSession", commandFuncRequestCraftingSession); - CommandTable::addCppFunction("requestCraftingSessionFail",commandFuncRequestCraftingSessionFail); - CommandTable::addCppFunction("selectDraftSchematic", commandFuncSelectDraftSchematic); - CommandTable::addCppFunction("nextCraftingStage", commandFuncNextCraftingStage); - CommandTable::addCppFunction("createPrototype", commandFuncCreatePrototype); - CommandTable::addCppFunction("createManfSchematic", commandFuncCreateManfSchematic); - CommandTable::addCppFunction("cancelCraftingSession", commandFuncCancelCraftingSession); - CommandTable::addCppFunction("stopCraftingSession", commandFuncStopCraftingSession); - CommandTable::addCppFunction("restartCraftingSession", commandFuncRestartCraftingSession); - CommandTable::addCppFunction("extractObject", commandFuncExtractObject); - CommandTable::addCppFunction("repair", commandFuncRepair); - CommandTable::addCppFunction("factoryCrateSplit", commandFuncFactoryCrateSplit); + CommandTable::addCppFunction("requestCraftingSession", commandFuncRequestCraftingSession); + CommandTable::addCppFunction("requestCraftingSessionFail", commandFuncRequestCraftingSessionFail); + CommandTable::addCppFunction("selectDraftSchematic", commandFuncSelectDraftSchematic); + CommandTable::addCppFunction("nextCraftingStage", commandFuncNextCraftingStage); + CommandTable::addCppFunction("createPrototype", commandFuncCreatePrototype); + CommandTable::addCppFunction("createManfSchematic", commandFuncCreateManfSchematic); + CommandTable::addCppFunction("cancelCraftingSession", commandFuncCancelCraftingSession); + CommandTable::addCppFunction("stopCraftingSession", commandFuncStopCraftingSession); + CommandTable::addCppFunction("restartCraftingSession", commandFuncRestartCraftingSession); + CommandTable::addCppFunction("extractObject", commandFuncExtractObject); + CommandTable::addCppFunction("repair", commandFuncRepair); + CommandTable::addCppFunction("factoryCrateSplit", commandFuncFactoryCrateSplit); // misc - CommandTable::addCppFunction("showDanceVisuals", commandFuncShowDanceVisuals); - CommandTable::addCppFunction("showMusicianVisuals", commandFuncShowMusicianVisuals); - CommandTable::addCppFunction("placeStructure", commandFuncPlaceStructure); - CommandTable::addCppFunction("getAttributes", commandFuncGetAttributes); - CommandTable::addCppFunction("getAttributesBatch", commandFuncGetAttributesBatch); - CommandTable::addCppFunction("sitServer", commandFuncSitServer); - CommandTable::addCppFunction("jumpServer", commandFuncJumpServer); - CommandTable::addCppFunction("purchaseTicket", commandFuncPurchaseTicket); - CommandTable::addCppFunction("addFriend", commandFuncAddFriend); - CommandTable::addCppFunction("removeFriend", commandFuncRemoveFriend); - CommandTable::addCppFunction("getFriendList", commandFuncGetFriendList); - CommandTable::addCppFunction("addIgnore", commandFuncAddIgnore); - CommandTable::addCppFunction("removeIgnore", commandFuncRemoveIgnore); - CommandTable::addCppFunction("getIgnoreList", commandFuncGetIgnoreList); - CommandTable::addCppFunction("requestBiography", commandFuncRequestBiography); - CommandTable::addCppFunction("setBiography", commandFuncSetBiography); + CommandTable::addCppFunction("showDanceVisuals", commandFuncShowDanceVisuals); + CommandTable::addCppFunction("showMusicianVisuals", commandFuncShowMusicianVisuals); + CommandTable::addCppFunction("placeStructure", commandFuncPlaceStructure); + CommandTable::addCppFunction("getAttributes", commandFuncGetAttributes); + CommandTable::addCppFunction("getAttributesBatch", commandFuncGetAttributesBatch); + CommandTable::addCppFunction("sitServer", commandFuncSitServer); + CommandTable::addCppFunction("jumpServer", commandFuncJumpServer); + CommandTable::addCppFunction("purchaseTicket", commandFuncPurchaseTicket); + CommandTable::addCppFunction("addFriend", commandFuncAddFriend); + CommandTable::addCppFunction("removeFriend", commandFuncRemoveFriend); + CommandTable::addCppFunction("getFriendList", commandFuncGetFriendList); + CommandTable::addCppFunction("addIgnore", commandFuncAddIgnore); + CommandTable::addCppFunction("removeIgnore", commandFuncRemoveIgnore); + CommandTable::addCppFunction("getIgnoreList", commandFuncGetIgnoreList); + CommandTable::addCppFunction("requestBiography", commandFuncRequestBiography); + CommandTable::addCppFunction("setBiography", commandFuncSetBiography); CommandTable::addCppFunction("requestWaypointAtPosition", commandFuncRequestWaypointAtPosition); - CommandTable::addCppFunction("serverDestroyObject", commandFuncServerDestroyObject); - CommandTable::addCppFunction("setSpokenLanguage", commandFuncSetSpokenLanguage); - CommandTable::addCppFunction("applyPowerup", commandFuncApplyPowerup); - CommandTable::addCppFunction("report", commandFuncReport); - CommandTable::addCppFunction("resetCooldowns", commandFuncResetCooldowns); - CommandTable::addCppFunction("spewCommandQueue", commandFuncSpewCommandQueue); - CommandTable::addCppFunction("locateStructure", commandFuncLocateStructure); - CommandTable::addCppFunction("locateVendor", commandFuncLocateVendor); - CommandTable::addCppFunction("showCtsHistory", commandFuncShowCtsHistory); + CommandTable::addCppFunction("serverDestroyObject", commandFuncServerDestroyObject); + CommandTable::addCppFunction("setSpokenLanguage", commandFuncSetSpokenLanguage); + CommandTable::addCppFunction("applyPowerup", commandFuncApplyPowerup); + CommandTable::addCppFunction("report", commandFuncReport); + CommandTable::addCppFunction("resetCooldowns", commandFuncResetCooldowns); + CommandTable::addCppFunction("spewCommandQueue", commandFuncSpewCommandQueue); + CommandTable::addCppFunction("locateStructure", commandFuncLocateStructure); + CommandTable::addCppFunction("locateVendor", commandFuncLocateVendor); + CommandTable::addCppFunction("showCtsHistory", commandFuncShowCtsHistory); CommandTable::addCppFunction("pickupAllRoomItemsIntoInventory", commandFuncPickupAllRoomItemsIntoInventory); CommandTable::addCppFunction("dropAllInventoryItemsIntoRoom", commandFuncDropAllInventoryItemsIntoRoom); - CommandTable::addCppFunction("saveDecorationLayout", commandFuncSaveDecorationLayout); - CommandTable::addCppFunction("restoreDecorationLayout", commandFuncRestoreDecorationLayout); - CommandTable::addCppFunction("areaPickRandomPlayer", commandFuncAreaPickRandomPlayer); - CommandTable::addCppFunction("roomPickRandomPlayer", commandFuncRoomPickRandomPlayer); + CommandTable::addCppFunction("saveDecorationLayout", commandFuncSaveDecorationLayout); + CommandTable::addCppFunction("restoreDecorationLayout", commandFuncRestoreDecorationLayout); + CommandTable::addCppFunction("areaPickRandomPlayer", commandFuncAreaPickRandomPlayer); + CommandTable::addCppFunction("roomPickRandomPlayer", commandFuncRoomPickRandomPlayer); // match making - CommandTable::addCppFunction("setMatchMakingPersonalId", commandFuncSetMatchMakingPersonalId); + CommandTable::addCppFunction("setMatchMakingPersonalId", commandFuncSetMatchMakingPersonalId); CommandTable::addCppFunction("setMatchMakingCharacterId", commandFuncSetMatchMakingCharacterId); - CommandTable::addCppFunction("requestCharacterMatch", commandFuncRequestCharacterMatch); + CommandTable::addCppFunction("requestCharacterMatch", commandFuncRequestCharacterMatch); CommandTable::addCppFunction("toggleSearchableByCtsSourceGalaxy", commandFuncToggleSearchableByCtsSourceGalaxy); CommandTable::addCppFunction("toggleDisplayLocationInSearchResults", commandFuncToggleDisplayLocationInSearchResults); - CommandTable::addCppFunction("toggleAnonymous", commandFuncToggleAnonymous); - CommandTable::addCppFunction("toggleHelper", commandFuncToggleHelper); - CommandTable::addCppFunction("toggleRolePlay", commandFuncToggleRolePlay); - CommandTable::addCppFunction("toggleLookingForGroup", commandFuncToggleLookingForGroup); - CommandTable::addCppFunction("toggleAwayFromKeyBoard", commandFuncToggleAwayFromKeyBoard); + CommandTable::addCppFunction("toggleAnonymous", commandFuncToggleAnonymous); + CommandTable::addCppFunction("toggleHelper", commandFuncToggleHelper); + CommandTable::addCppFunction("toggleRolePlay", commandFuncToggleRolePlay); + CommandTable::addCppFunction("toggleLookingForGroup", commandFuncToggleLookingForGroup); + CommandTable::addCppFunction("toggleAwayFromKeyBoard", commandFuncToggleAwayFromKeyBoard); CommandTable::addCppFunction("toggleDisplayingFactionRank", commandFuncToggleDisplayingFactionRank); - CommandTable::addCppFunction("toggleOutOfCharacter", commandFuncToggleOutOfCharacter); - CommandTable::addCppFunction("toggleLookingForWork", commandFuncToggleLookingForWork); + CommandTable::addCppFunction("toggleOutOfCharacter", commandFuncToggleOutOfCharacter); + CommandTable::addCppFunction("toggleLookingForWork", commandFuncToggleLookingForWork); //skill - CommandTable::addCppFunction("revokeSkill", commandFuncRevokeSkill); - CommandTable::addCppFunction("setCurrentSkillTitle", commandFuncSetCurrentSkillTitle); + CommandTable::addCppFunction("revokeSkill", commandFuncRevokeSkill); + CommandTable::addCppFunction("setCurrentSkillTitle", commandFuncSetCurrentSkillTitle); //misc ui - CommandTable::addCppFunction("permissionListModify", commandFuncPermissionListModify); - CommandTable::addCppFunction("requestCharacterSheetInfo", commandFuncRequestCharacterSheetInfo); - CommandTable::addCppFunction("removeBuff", commandFuncRemoveBuff); + CommandTable::addCppFunction("permissionListModify", commandFuncPermissionListModify); + CommandTable::addCppFunction("requestCharacterSheetInfo", commandFuncRequestCharacterSheetInfo); + CommandTable::addCppFunction("removeBuff", commandFuncRemoveBuff); // npc conversation - CommandTable::addCppFunction("npcConversationStart", commandFuncNpcConversationStart); - CommandTable::addCppFunction("npcConversationStop", commandFuncNpcConversationStop); + CommandTable::addCppFunction("npcConversationStart", commandFuncNpcConversationStart); + CommandTable::addCppFunction("npcConversationStop", commandFuncNpcConversationStop); CommandTable::addCppFunction("npcConversationSelect", commandFuncNpcConversationSelect); - CommandTable::addCppFunction("handleUnstick", commandFuncUnstick); - CommandTable::addCppFunction("getAccountInfo", commandFuncGetAccountInfo); + CommandTable::addCppFunction("handleUnstick", commandFuncUnstick); + CommandTable::addCppFunction("getAccountInfo", commandFuncGetAccountInfo); CommandTable::addCppFunction("lag", commandFuncLag); //knowledgebase (i.e. holocron) @@ -9809,8 +9781,8 @@ void CommandCppFuncs::install() CommandTable::addCppFunction("associateDroidControlDeviceWithShip", commandFuncAssociateDroidControlDeviceWithShip); CommandTable::addCppFunction("unassociateDroidControlDeviceWithShip", commandFuncAssociateDroidControlDeviceWithShip); - CommandTable::addCppFunction("serverAsteroidDataListen" , commandFuncServerAsteroidDataListen); - CommandTable::addCppFunction("serverAsteroidDataStopListening", commandFuncServerAsteroidDataStopListening); + CommandTable::addCppFunction("serverAsteroidDataListen", commandFuncServerAsteroidDataListen); + CommandTable::addCppFunction("serverAsteroidDataStopListening", commandFuncServerAsteroidDataStopListening); CommandTable::addCppFunction("boosterOn", commandFuncBoosterOn); CommandTable::addCppFunction("boosterOff", commandFuncBoosterOff); @@ -9824,7 +9796,7 @@ void CommandCppFuncs::install() CommandTable::addCppFunction("abandonQuest", commandFuncAbandonQuest); // exchange - CommandTable::addCppFunction("exchangeListCredits", commandFuncExchangeListCredits); + CommandTable::addCppFunction("exchangeListCredits", commandFuncExchangeListCredits); // squelch CommandTable::addCppFunction("squelch", commandFuncSquelch); @@ -9850,4 +9822,4 @@ void CommandCppFuncs::remove() { } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/command/CommandQueueEntry.cpp b/engine/server/library/serverGame/src/shared/command/CommandQueueEntry.cpp index 4473f70f..b13330b9 100755 --- a/engine/server/library/serverGame/src/shared/command/CommandQueueEntry.cpp +++ b/engine/server/library/serverGame/src/shared/command/CommandQueueEntry.cpp @@ -6,7 +6,6 @@ // // ====================================================================== - #include "serverGame/FirstServerGame.h" #include "serverGame/CommandQueueEntry.h" #include "serverGame/CreatureObject.h" @@ -14,15 +13,15 @@ #include "Archive/ByteStream.h" #include "sharedGame/CommandTable.h" - // ====================================================================== CommandQueueEntry::CommandQueueEntry() : - m_command(&CommandTable::getNullCommand ()), + m_command(&CommandTable::getNullCommand()), m_targetId(NetworkId::cms_invalid), m_params(), m_sequenceId(0), - m_clearable(true) + m_clearable(true), + m_priority() { } @@ -35,8 +34,8 @@ CommandQueueEntry::CommandQueueEntry( uint32 sequenceId, bool clearable, Command::Priority priority, - bool autoAttack ) : - + bool autoAttack) : + m_command(&command), m_targetId(targetId), m_params(params), @@ -64,12 +63,12 @@ CommandQueueEntry &CommandQueueEntry::operator=(CommandQueueEntry const &rhs) { if (&rhs != this) { - m_command = rhs.m_command; //lint !e1555 - m_targetId = rhs.m_targetId; - m_params = rhs.m_params; + m_command = rhs.m_command; //lint !e1555 + m_targetId = rhs.m_targetId; + m_params = rhs.m_params; m_sequenceId = rhs.m_sequenceId; - m_clearable = rhs.m_clearable; - m_priority = rhs.m_priority; + m_clearable = rhs.m_clearable; + m_priority = rhs.m_priority; } return *this; } @@ -78,35 +77,30 @@ CommandQueueEntry &CommandQueueEntry::operator=(CommandQueueEntry const &rhs) namespace Archive { + // ---------------------------------------------------------------------- -// ---------------------------------------------------------------------- + void get(ReadIterator &source, CommandQueueEntry &target) + { + uint32 commandHash; -void get(ReadIterator &source, CommandQueueEntry &target) -{ - uint32 commandHash; + Archive::get(source, commandHash); + Archive::get(source, target.m_targetId); + Archive::get(source, target.m_params); + Archive::get(source, target.m_sequenceId); + Archive::get(source, target.m_clearable); + target.m_command = &CommandTable::getCommand(commandHash); + } - Archive::get(source, commandHash); - Archive::get(source, target.m_targetId); - Archive::get(source, target.m_params); - Archive::get(source, target.m_sequenceId); - Archive::get(source, target.m_clearable); - target.m_command = &CommandTable::getCommand(commandHash); -} + // ---------------------------------------------------------------------- -// ---------------------------------------------------------------------- + void put(ByteStream &target, CommandQueueEntry const &source) + { + Archive::put(target, source.m_command->m_commandHash); + Archive::put(target, source.m_targetId); + Archive::put(target, source.m_params); + Archive::put(target, source.m_sequenceId); + Archive::put(target, source.m_clearable); + } -void put(ByteStream &target, CommandQueueEntry const &source) -{ - Archive::put(target, source.m_command->m_commandHash); - Archive::put(target, source.m_targetId); - Archive::put(target, source.m_params); - Archive::put(target, source.m_sequenceId); - Archive::put(target, source.m_clearable); -} - - - -// ---------------------------------------------------------------------- - - -} // namespace Archive + // ---------------------------------------------------------------------- +} // namespace Archive \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/controller/AiShipController.cpp b/engine/server/library/serverGame/src/shared/controller/AiShipController.cpp index 3fe9a88f..a08e1ad0 100755 --- a/engine/server/library/serverGame/src/shared/controller/AiShipController.cpp +++ b/engine/server/library/serverGame/src/shared/controller/AiShipController.cpp @@ -136,7 +136,7 @@ AiShipController * AiShipController::asAiShipController(Controller * const contr { ShipController * const shipController = (controller != nullptr) ? controller->asShipController() : nullptr; AiShipController * const aiShipController = (shipController != nullptr) ? shipController->asAiShipController() : nullptr; - + return aiShipController; } @@ -146,7 +146,7 @@ AiShipController const * AiShipController::asAiShipController(Controller const * { ShipController const * const shipController = (controller != nullptr) ? controller->asShipController() : nullptr; AiShipController const * const aiShipController = (shipController != nullptr) ? shipController->asAiShipController() : nullptr; - + return aiShipController; } @@ -253,8 +253,8 @@ float AiShipController::realAlter(float const elapsedTime) #ifdef _DEBUG AiDebugString * aiDebugString = nullptr; - if ( s_spaceAiClientDebugEnabled - && !getShipOwner()->getObservers().empty()) + if (s_spaceAiClientDebugEnabled + && !getShipOwner()->getObservers().empty()) { aiDebugString = new AiDebugString; } @@ -277,8 +277,8 @@ float AiShipController::realAlter(float const elapsedTime) m_pendingDockingBehavior = nullptr; } - if ( (m_dockingBehavior != nullptr) - && (m_dockingBehavior->isDockFinished())) + if ((m_dockingBehavior != nullptr) + && (m_dockingBehavior->isDockFinished())) { delete m_dockingBehavior; m_dockingBehavior = nullptr; @@ -319,8 +319,8 @@ float AiShipController::realAlter(float const elapsedTime) m_dockingBehavior->unDock(); } - if ( isAttackSquadLeader() - || !getAttackSquad().isInFormation()) + if (isAttackSquadLeader() + || !getAttackSquad().isInFormation()) { m_attackBehavior->alter(elapsedTime); @@ -394,8 +394,8 @@ float AiShipController::realAlter(float const elapsedTime) // Check for enemies periodically - if ( !m_enemyCheckQueued - && shouldCheckForEnemies()) + if (!m_enemyCheckQueued + && shouldCheckForEnemies()) { m_enemyCheckQueued = true; ShipAiEnemySearchManager::add(*shipOwner); @@ -435,7 +435,7 @@ float AiShipController::realAlter(float const elapsedTime) { ShipController * const followedUnitShipController = squadLeader->getController()->asShipController(); AiShipController * const followedUnitAiShipController = (followedUnitShipController != nullptr) ? followedUnitShipController->asAiShipController() : nullptr; - + if (followedUnitAiShipController != nullptr) { followedUnitAiShipController->requestSlowDown(); @@ -485,8 +485,8 @@ float AiShipController::realAlter(float const elapsedTime) if (isSquadLeader()) { PROFILER_AUTO_BLOCK_DEFINE("check squadLeader"); - if ( isAttacking() - || !hasFunctionalEngines()) + if (isAttacking() + || !hasFunctionalEngines()) { getSquad().assignNewLeader(); } @@ -508,28 +508,28 @@ float AiShipController::realAlter(float const elapsedTime) PROFILER_AUTO_BLOCK_DEFINE("Manage countermeasures"); switch (m_countermeasureState) { - case CS_reacting: - if (m_reactToMissileTimer->updateZero(elapsedTime)) - m_countermeasureState = CS_launching; - break; + case CS_reacting: + if (m_reactToMissileTimer->updateZero(elapsedTime)) + m_countermeasureState = CS_launching; + break; - case CS_launching: - if (MissileManager::getInstance().isTargetedByMissile(getOwner()->getNetworkId())) + case CS_launching: + if (MissileManager::getInstance().isTargetedByMissile(getOwner()->getNetworkId())) + { + for (int weaponIndex = 0; weaponIndex < ShipChassisSlotType::cms_numWeaponIndices; ++weaponIndex) { - for (int weaponIndex = 0; weaponIndex < ShipChassisSlotType::cms_numWeaponIndices; ++weaponIndex) - { - PROFILER_AUTO_BLOCK_DEFINE("countermeasures missile loop"); - if (NON_NULL(getShipOwner())->isCountermeasure(weaponIndex)) - getShipOwner()->fireShotNonTurretServer(weaponIndex, NetworkId::cms_invalid, ShipChassisSlotType::SCST_invalid); - } + PROFILER_AUTO_BLOCK_DEFINE("countermeasures missile loop"); + if (NON_NULL(getShipOwner())->isCountermeasure(weaponIndex)) + getShipOwner()->fireShotNonTurretServer(weaponIndex, NetworkId::cms_invalid, ShipChassisSlotType::SCST_invalid); } - else - m_countermeasureState = CS_none; - break; - - case CS_none: - default: - break; + } + else + m_countermeasureState = CS_none; + break; + + case CS_none: + default: + break; } } @@ -551,8 +551,8 @@ float AiShipController::realAlter(float const elapsedTime) } #ifdef _DEBUG - if ( (m_attackBehavior != nullptr) - && (aiDebugString != nullptr)) + if ((m_attackBehavior != nullptr) + && (aiDebugString != nullptr)) { PROFILER_AUTO_BLOCK_DEFINE("sendDebugAiToClients"); sendDebugAiToClients(*aiDebugString); @@ -574,9 +574,9 @@ void AiShipController::moveTo(Vector const & position_w, float const throttle, f // If we are not following a unit, see if we need to slow down for someone - if ( (m_nonAttackBehavior != nullptr) - && (m_nonAttackBehavior->getBehaviorType() != ASBT_follow) - && m_requestedSlowDown + if ((m_nonAttackBehavior != nullptr) + && (m_nonAttackBehavior->getBehaviorType() != ASBT_follow) + && m_requestedSlowDown && !isAttacking()) { slowDown = true; @@ -599,7 +599,7 @@ void AiShipController::moveTo(Vector const & position_w, float const throttle, f Vector resultAvoidancePosition_w; Vector const & shipVelocity = getShipOwner()->getCurrentVelocity_p(); - + if (SpaceAvoidanceManager::getAvoidancePosition(*getOwner(), shipVelocity, position_w, resultAvoidancePosition_w)) { IGNORE_RETURN(face(resultAvoidancePosition_w, deltaTime)); @@ -649,7 +649,7 @@ bool AiShipController::addDamageTaken(NetworkId const & attackingUnit, float con { CreatureObject const * const attackingPilotCreatureObject = attackingShipObject->getPilot(); - if ( (attackingPilotCreatureObject != nullptr) + if ((attackingPilotCreatureObject != nullptr) && attackingPilotCreatureObject->isPlayerControlled()) { GroupObject * const groupObject = attackingPilotCreatureObject->getGroup(); @@ -760,7 +760,7 @@ void AiShipController::follow(NetworkId const & followedUnit, Vector const & dir CollisionProperty const * const ownerCollisionProperty = getOwner()->getCollisionProperty(); CollisionProperty const * const followedObjectCollisionProperty = followedObject->getCollisionProperty(); - + if (ownerCollisionProperty != nullptr) { appearanceRadius += ownerCollisionProperty->getBoundingSphere_l().getRadius(); @@ -768,7 +768,7 @@ void AiShipController::follow(NetworkId const & followedUnit, Vector const & dir if (followedObjectCollisionProperty != nullptr) { - appearanceRadius += followedObjectCollisionProperty ->getBoundingSphere_l().getRadius(); + appearanceRadius += followedObjectCollisionProperty->getBoundingSphere_l().getRadius(); } } @@ -790,7 +790,7 @@ int AiShipController::getBehaviorType() const { result = m_nonAttackBehavior->getBehaviorType(); } - + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "debug_ai", ("AiShipController::getBehaviorType() owner(%s) behavior(%s)", getOwner()->getNetworkId().getValueString().c_str(), AiShipBehaviorBase::getBehaviorString(static_cast(result)))); return static_cast(result); @@ -831,7 +831,7 @@ void AiShipController::track(Object const & target) void AiShipController::moveTo(SpacePath * const path) { LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "debug_ai", ("AiShipController::moveTo() owner(%s) path(0x%p)", getOwner()->getNetworkId().getValueString().c_str(), path)); - + if (path != m_path) { SpacePathManager::release(m_path, getOwner()); @@ -959,7 +959,7 @@ void AiShipController::setPilotType(std::string const & pilotType) if (pilotType.empty()) { - DEBUG_WARNING(true, ("AiShipController::setPilotType empty pilotType for ship [%s]", + DEBUG_WARNING(true, ("AiShipController::setPilotType empty pilotType for ship [%s]", shipObject ? shipObject->getDebugInformation().c_str() : "NONE")); return; } @@ -992,23 +992,23 @@ void AiShipController::setPilotType(std::string const & pilotType) switch (m_shipClass) { - case ShipAiReactionManager::SC_invalid: - default: { FATAL(true, ("Invalid ship name(%s)", m_shipName.getString())); } - case ShipAiReactionManager::SC_fighter: { m_attackBehavior = new AiShipBehaviorAttackFighter(*this); } break; - case ShipAiReactionManager::SC_bomber: { m_attackBehavior = new AiShipBehaviorAttackBomber(*this); } break; - case ShipAiReactionManager::SC_capitalShip: { m_attackBehavior = new AiShipBehaviorAttackCapitalShip(*this); } break; - case ShipAiReactionManager::SC_transport: { m_attackBehavior = new AiShipBehaviorAttackFighter(*this); } break; + case ShipAiReactionManager::SC_invalid: + default: { FATAL(true, ("Invalid ship name(%s)", m_shipName.getString())); } + case ShipAiReactionManager::SC_fighter: { m_attackBehavior = new AiShipBehaviorAttackFighter(*this); } break; + case ShipAiReactionManager::SC_bomber: { m_attackBehavior = new AiShipBehaviorAttackBomber(*this); } break; + case ShipAiReactionManager::SC_capitalShip: { m_attackBehavior = new AiShipBehaviorAttackCapitalShip(*this); } break; + case ShipAiReactionManager::SC_transport: { m_attackBehavior = new AiShipBehaviorAttackFighter(*this); } break; } // Create the turreting target system, if appropriate - + if (shipObject && shipObject->hasTurrets()) addTurretTargetingSystem(new AiShipTurretTargetingSystem(*this)); // Set the default aggro distance setAggroRadius(m_pilotData->m_aggroRadius); - + FATAL((m_attackBehavior == nullptr), ("The attack behavior can not be nullptr.")); } @@ -1097,8 +1097,8 @@ void AiShipController::setSquad(SpaceSquad * const squad) { // Remove the unit from its previous squad - if ( (m_squad != nullptr) - && !m_squad->isEmpty()) + if ((m_squad != nullptr) + && !m_squad->isEmpty()) { m_squad->removeUnit(getOwner()->getNetworkId()); } @@ -1209,7 +1209,7 @@ float AiShipController::getShipRadius() const float result = 1.0f; ShipObject const * const shipObject = getShipOwner(); CollisionProperty const * const shipCollision = shipObject->getCollisionProperty(); - + if (shipCollision != nullptr) { result = shipCollision->getBoundingSphere_l().getRadius(); @@ -1280,7 +1280,7 @@ bool AiShipController::shouldCheckForEnemies() const } } } - + return result; } @@ -1290,8 +1290,8 @@ void AiShipController::setCurrentPathIndex(unsigned int const index) { //LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "debug_ai", ("AiShipController::setCurrentPathIndex() unit(%s) pathIndex(%u) pathSize(%u)", getOwner()->getNetworkId().getValueString().c_str(), index, (m_path != nullptr) ? m_path->getTransformList().size() : 0)); - if ( (m_path != nullptr) - && !m_path->isEmpty()) + if ((m_path != nullptr) + && !m_path->isEmpty()) { m_currentPathIndex = index; } @@ -1314,21 +1314,21 @@ unsigned int AiShipController::getCurrentPathIndex() const float AiShipController::calculateThrottleToPosition_w(Vector const & position_w, float const slowDownDistance) const { float result = 0.0f; - + Object const * const object = getOwner(); if (object != nullptr) { float const distanceToGoalSquared = object->getPosition_w().magnitudeBetweenSquared(position_w); - if ( (distanceToGoalSquared < sqr(slowDownDistance)) + if ((distanceToGoalSquared < sqr(slowDownDistance)) && (slowDownDistance > 0.0f)) { static float scale = 0.5f; float const distanceToGoal = sqrt(distanceToGoalSquared); result = clamp(0.0f, (distanceToGoal / slowDownDistance) * scale, 1.0f); - if ( (result < 0.5f) + if ((result < 0.5f) && (distanceToGoal < getGoalStopDistance())) { result = 0.0f; @@ -1397,7 +1397,7 @@ float AiShipController::getPilotAggression() const */ void AiShipController::switchToFighterAttack() { - DEBUG_FATAL(dynamic_cast(m_attackBehavior),("Programmer bug: called switchToFighterAttack() when already using a fighter attack")); + DEBUG_FATAL(dynamic_cast(m_attackBehavior), ("Programmer bug: called switchToFighterAttack() when already using a fighter attack")); delete m_pendingAttackBehavior; // in case we tried to switch twice m_pendingAttackBehavior = new AiShipBehaviorAttackFighter(*NON_NULL(m_attackBehavior)); } @@ -1410,7 +1410,7 @@ void AiShipController::switchToFighterAttack() */ void AiShipController::switchToBomberAttack() { - DEBUG_FATAL(dynamic_cast(m_attackBehavior),("Programmer bug: called switchToBomberAttack() when already using a bomber attack")); + DEBUG_FATAL(dynamic_cast(m_attackBehavior), ("Programmer bug: called switchToBomberAttack() when already using a bomber attack")); delete m_pendingAttackBehavior; // in case we tried to switch twice m_pendingAttackBehavior = new AiShipBehaviorAttackBomber(*NON_NULL(m_attackBehavior)); } @@ -1496,8 +1496,8 @@ void AiShipController::onAttackTargetListEmpty() SpaceSquad::SpaceSquadList const & guardedByList = getSquad().getGuardedByList(); - if ( !guardedByList.empty() - && getSquad().isAttackTargetListEmpty()) + if (!guardedByList.empty() + && getSquad().isAttackTargetListEmpty()) { SpaceSquad::SpaceSquadList::const_iterator iterGuardedByList = guardedByList.begin(); @@ -1561,7 +1561,7 @@ void AiShipController::sendDebugAiToClients(AiDebugString & aiDebugString) // // aiDebugString.addText(guardString, PackedRgb::solidYellow); //} - + // Are my engines functional? if (!shipOwner->isComponentFunctional(ShipChassisSlotType::SCST_engine)) @@ -1651,14 +1651,14 @@ void AiShipController::sendDebugAiToClients(AiDebugString & aiDebugString) aiDebugString.addText(formattedString.sprintf("turret miss(%.0f%% @ %.0f)\n", turretMissChance, turretMissAngleDegrees)); } } - + //int ammoCurrent = 0; //int ammoMax = 0; // //for (int chassisSlot = ShipChassisSlotType::SCST_weapon_first; chassisSlot < ShipChassisSlotType::SCST_weapon_last; ++chassisSlot) //{ // int const weaponIndex = ShipChassisSlotType::getWeaponIndex(chassisSlot); - // + // // if (parentShipObject->isMissile(weaponIndex)) // { // ammoCurrent += parentShipObject->getWeaponAmmoCurrent(static_cast(chassisSlot)); @@ -1687,14 +1687,14 @@ void AiShipController::sendDebugAiToClients(AiDebugString & aiDebugString) // Only send to the client if the objvar is set int temp = 0; - if ( (characterObject != nullptr) - && characterObject->getObjVars().getItem("ai_debug_string", temp)) + if ((characterObject != nullptr) + && characterObject->getObjVars().getItem("ai_debug_string", temp)) { if (temp > 0) { bool const reliable = true; GenericValueTypeMessage > message("AiDebugString", std::make_pair(getOwner()->getNetworkId(), finalString)); - + client->send(message, reliable); } } @@ -1714,7 +1714,7 @@ bool AiShipController::debug_forceFighterAttackManeuver(int const maneuverType) { aiFighterBehavior->debug_forceManeuver(maneuverType); success = true; - } + } return success; } @@ -1741,11 +1741,11 @@ char const * AiShipController::getAttackOrdersString(AttackOrders const attackOr { switch (attackOrders) { - case AO_holdFire: { return "HOLD FIRE"; } - case AO_returnFire: { return "RETURN FIRE"; } - case AO_attackFreely: { return "ATTACK FREELY"; } - case AO_count: - default: break; + case AO_holdFire: { return "HOLD FIRE"; } + case AO_returnFire: { return "RETURN FIRE"; } + case AO_attackFreely: { return "ATTACK FREELY"; } + case AO_count: + default: break; } return "INVALID ATTACK ORDER"; @@ -1771,8 +1771,8 @@ void AiShipController::addExclusiveAggro(NetworkId const & unit) ServerObject * const unitServerObject = (unitObject != nullptr) ? unitObject->asServerObject() : nullptr; CreatureObject * const unitCreatureObject = (unitServerObject != nullptr) ? unitServerObject->asCreatureObject() : nullptr; - if ( !unitCreatureObject - || !unitCreatureObject->isPlayerControlled()) + if (!unitCreatureObject + || !unitCreatureObject->isPlayerControlled()) { DEBUG_WARNING(true, ("debug_ai: AiShipController::addExclusiveAggro() owner(%s) ERROR: The unit(%s) must be a player.", getOwner()->getDebugInformation().c_str(), unit.getValueString().c_str())); return; @@ -1922,4 +1922,4 @@ float AiShipController::getTurretMissAngle() const return m_pilotData->m_turretMissAngle; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/controller/CellController.cpp b/engine/server/library/serverGame/src/shared/controller/CellController.cpp index 7737ee55..7b8366f8 100755 --- a/engine/server/library/serverGame/src/shared/controller/CellController.cpp +++ b/engine/server/library/serverGame/src/shared/controller/CellController.cpp @@ -1,5 +1,5 @@ // CellController.cpp -// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. // Author: Justin Randall //----------------------------------------------------------------------- @@ -12,7 +12,7 @@ //----------------------------------------------------------------------- CellController::CellController(CellObject * newOwner) : -ServerController(newOwner) + ServerController(newOwner) { } @@ -24,50 +24,49 @@ CellController::~CellController() //----------------------------------------------------------------------- - -void CellController::handleMessage (int message, float value, const MessageQueue::Data* data, uint32 flags) +void CellController::handleMessage(int message, float value, const MessageQueue::Data* data, uint32 flags) { CellObject * owner = dynamic_cast(getOwner()); NOT_NULL(owner); - + switch (message) { case CM_addAllowed: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->addAllowed(msg->getValue()); - } + owner->addAllowed(msg->getValue()); } - break; + } + break; case CM_removeAllowed: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->removeAllowed(msg->getValue()); - } + owner->removeAllowed(msg->getValue()); } - break; + } + break; case CM_addBanned: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->addBanned(msg->getValue()); - } + owner->addBanned(msg->getValue()); } - break; + } + break; case CM_removeBanned: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->removeBanned(msg->getValue()); - } + owner->removeBanned(msg->getValue()); } - break; + } + break; default: ServerController::handleMessage(message, value, data, flags); break; @@ -76,9 +75,9 @@ void CellController::handleMessage (int message, float value, const MessageQueue //----------------------------------------------------------------------- -void CellController::setGoal(Transform const & , ServerObject * ) +void CellController::setGoal(Transform const &, ServerObject *, bool teleport = false) { - DEBUG_WARNING(true, ("Cell setGoal was called for CellObject %s. Cells may not have goals!",getOwner()->getNetworkId().getValueString().c_str())); + DEBUG_WARNING(true, ("Cell setGoal was called for CellObject %s. Cells may not have goals!", getOwner()->getNetworkId().getValueString().c_str())); } -//----------------------------------------------------------------------- +//----------------------------------------------------------------------- \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/controller/CellController.h b/engine/server/library/serverGame/src/shared/controller/CellController.h index 996e4f99..533a6179 100755 --- a/engine/server/library/serverGame/src/shared/controller/CellController.h +++ b/engine/server/library/serverGame/src/shared/controller/CellController.h @@ -1,5 +1,5 @@ // CellController.h -// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. // Author: Justin Randall #ifndef _INCLUDED_CellController_H @@ -20,13 +20,12 @@ public: ~CellController(); protected: - virtual void handleMessage (int message, float value, const MessageQueue::Data* data, uint32 flags); - virtual void setGoal (Transform const & newGoal, ServerObject * goalCellObject ); - + virtual void handleMessage(int message, float value, const MessageQueue::Data* data, uint32 flags); + virtual void setGoal(Transform const & newGoal, ServerObject * goalCellObject, bool teleport); + private: CellController & operator = (const CellController & rhs); CellController(const CellController & source); - }; //----------------------------------------------------------------------- diff --git a/engine/server/library/serverGame/src/shared/controller/CreatureController.cpp b/engine/server/library/serverGame/src/shared/controller/CreatureController.cpp index f25d0fb1..e0563d26 100755 --- a/engine/server/library/serverGame/src/shared/controller/CreatureController.cpp +++ b/engine/server/library/serverGame/src/shared/controller/CreatureController.cpp @@ -82,13 +82,12 @@ #include "Unicode.h" #include "UnicodeUtils.h" - //----------------------------------------------------------------------- -namespace CreatureControllerNamespace +namespace CreatureControllerNamespace { template - ObjectType & getOwner(Controller * controller) + ObjectType & getOwner(Controller * controller) { NOT_NULL(controller); NOT_NULL(controller->getOwner()); @@ -119,705 +118,703 @@ CreatureController::~CreatureController() //----------------------------------------------------------------------- -void CreatureController::handleMessage (const int message, const float value, const MessageQueue::Data* const data, const uint32 flags) +void CreatureController::handleMessage(const int message, const float value, const MessageQueue::Data* const data, const uint32 flags) { CreatureObject * const owner = static_cast(getOwner()); DEBUG_FATAL(!owner, ("Owner is nullptr in CreatureController::handleMessage\n")); - switch(message) + switch (message) { case CM_netUpdateTransform: + { + // if the auth server sent this to us, forward it to clients + const MessageQueueDataTransform * const msg = NON_NULL(dynamic_cast(data)); + owner->setLookAtYaw(msg->getLookAtYaw(), msg->getUseLookAtYaw()); + if (flags&GameControllerMessageFlags::SOURCE_REMOTE_SERVER) { - // if the auth server sent this to us, forward it to clients - const MessageQueueDataTransform * const msg = NON_NULL (dynamic_cast(data)); - owner->setLookAtYaw(msg->getLookAtYaw(), msg->getUseLookAtYaw()); - if (flags&GameControllerMessageFlags::SOURCE_REMOTE_SERVER) + // If we're not contained by what we are attached to, then transform + // updates are not relevant to clients because our position is + // dictated purely by our containing object. + if (owner->getAttachedTo() == ContainerInterface::getContainedByObject(*owner)) { - // If we're not contained by what we are attached to, then transform - // updates are not relevant to clients because our position is - // dictated purely by our containing object. - if (owner->getAttachedTo() == ContainerInterface::getContainedByObject(*owner)) - { - UpdateTransformMessage utm(owner->getNetworkId(), msg->getSequenceNumber(), msg->getTransform(), static_cast(msg->getSpeed()), msg->getLookAtYaw(), msg->getUseLookAtYaw()); - owner->sendToClientsInUpdateRange(utm, flags & GameControllerMessageFlags::RELIABLE, false); - } + UpdateTransformMessage utm(owner->getNetworkId(), msg->getSequenceNumber(), msg->getTransform(), static_cast(msg->getSpeed()), msg->getLookAtYaw(), msg->getUseLookAtYaw()); + owner->sendToClientsInUpdateRange(utm, flags & GameControllerMessageFlags::RELIABLE, false); } - TangibleController::handleMessage(message, value, data, flags); } - break; + TangibleController::handleMessage(message, value, data, flags); + } + break; case CM_netUpdateTransformWithParent: + { + // if the auth server sent this to us, forward it to clients + const MessageQueueDataTransformWithParent * const msg = NON_NULL(dynamic_cast(data)); + owner->setLookAtYaw(msg->getLookAtYaw(), msg->getUseLookAtYaw()); + if (flags&GameControllerMessageFlags::SOURCE_REMOTE_SERVER) { - // if the auth server sent this to us, forward it to clients - const MessageQueueDataTransformWithParent * const msg = NON_NULL (dynamic_cast(data)); - owner->setLookAtYaw(msg->getLookAtYaw(), msg->getUseLookAtYaw()); - if (flags&GameControllerMessageFlags::SOURCE_REMOTE_SERVER) + // If we're not contained by what we are attached to, then transform + // updates are not relevant to clients because our position is + // dictated purely by our containing object. + if (owner->getAttachedTo() == ContainerInterface::getContainedByObject(*owner)) { - // If we're not contained by what we are attached to, then transform - // updates are not relevant to clients because our position is - // dictated purely by our containing object. - if (owner->getAttachedTo() == ContainerInterface::getContainedByObject(*owner)) - { - UpdateTransformWithParentMessage utm(owner->getNetworkId(), msg->getSequenceNumber(), msg->getParent(), msg->getTransform(), static_cast(msg->getSpeed()), msg->getLookAtYaw(), msg->getUseLookAtYaw()); - owner->sendToClientsInUpdateRange(utm, flags & GameControllerMessageFlags::RELIABLE, false); - } + UpdateTransformWithParentMessage utm(owner->getNetworkId(), msg->getSequenceNumber(), msg->getParent(), msg->getTransform(), static_cast(msg->getSpeed()), msg->getLookAtYaw(), msg->getUseLookAtYaw()); + owner->sendToClientsInUpdateRange(utm, flags & GameControllerMessageFlags::RELIABLE, false); } - TangibleController::handleMessage(message, value, data, flags); } - break; - + TangibleController::handleMessage(message, value, data, flags); + } + break; + case CM_clientResourceHarvesterActivate: - { - const MessageQueueNetworkId * const msg = NON_NULL (dynamic_cast(data)); - - InstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId (msg->getNetworkId ())); - - UNREF (harvester); - - if (harvester && harvester->isOnAdminList(*owner)) - harvester->activate (owner->getNetworkId()); - } - break; - + { + const MessageQueueNetworkId * const msg = NON_NULL(dynamic_cast(data)); + + InstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId(msg->getNetworkId())); + + UNREF(harvester); + + if (harvester && harvester->isOnAdminList(*owner)) + harvester->activate(owner->getNetworkId()); + } + break; + case CM_clientResourceHarvesterDeactivate: - { - const MessageQueueNetworkId * const msg = NON_NULL (dynamic_cast(data)); - - InstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId (msg->getNetworkId ())); - - if (harvester && harvester->isOnAdminList(*owner)) - harvester->deactivate (); - } - break; - + { + const MessageQueueNetworkId * const msg = NON_NULL(dynamic_cast(data)); + + InstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId(msg->getNetworkId())); + + if (harvester && harvester->isOnAdminList(*owner)) + harvester->deactivate(); + } + break; + case CM_clientResourceHarvesterListen: - { - const MessageQueueNetworkId * const msg = NON_NULL (dynamic_cast(data)); - - HarvesterInstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId (msg->getNetworkId ())); - - if (harvester && owner) - harvester->addSynchronizedUiClient (*owner); - } - break; - + { + const MessageQueueNetworkId * const msg = NON_NULL(dynamic_cast(data)); + + HarvesterInstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId(msg->getNetworkId())); + + if (harvester && owner) + harvester->addSynchronizedUiClient(*owner); + } + break; + case CM_clientResourceHarvesterStopListening: - { - const MessageQueueNetworkId * const msg = NON_NULL (dynamic_cast(data)); - - HarvesterInstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId (msg->getNetworkId ())); - - if (harvester && owner) - harvester->removeSynchronizedUiClient (owner->getNetworkId ()); - } - break; - + { + const MessageQueueNetworkId * const msg = NON_NULL(dynamic_cast(data)); + + HarvesterInstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId(msg->getNetworkId())); + + if (harvester && owner) + harvester->removeSynchronizedUiClient(owner->getNetworkId()); + } + break; + case CM_clientResourceHarvesterResourceSelect: - { - const MessageQueueNetworkIdPair * const msg = NON_NULL (dynamic_cast(data)); - - HarvesterInstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId (msg->getFirstNetworkId ())); - - harvester->selectResource (msg->getSecondNetworkId (), owner->getNetworkId()); - } - break; - + { + const MessageQueueNetworkIdPair * const msg = NON_NULL(dynamic_cast(data)); + + HarvesterInstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId(msg->getFirstNetworkId())); + + harvester->selectResource(msg->getSecondNetworkId(), owner->getNetworkId()); + } + break; + case CM_clientResourceHarvesterGetResourceData: + { + const MessageQueueNetworkId * const msg = NON_NULL(dynamic_cast(data)); + + typedef stdvector::fwd DataVector; + DataVector dv; + + HarvesterInstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId(msg->getNetworkId())); + ServerObject * const player = owner; + + if (harvester && player) { - const MessageQueueNetworkId * const msg = NON_NULL (dynamic_cast(data)); - - typedef stdvector::fwd DataVector; - DataVector dv; - - HarvesterInstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId (msg->getNetworkId ())); - ServerObject * const player = owner; - - if (harvester && player) + harvester->getResourceData(dv); + + if (!dv.empty()) { - harvester->getResourceData (dv); - - if (!dv.empty ()) - { - MessageQueueHarvesterResourceData * const newData = new MessageQueueHarvesterResourceData (msg->getNetworkId (), dv); - appendMessage(static_cast(CM_clientResourceHarvesterResourceData), 0.0f, newData, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); - } + MessageQueueHarvesterResourceData * const newData = new MessageQueueHarvesterResourceData(msg->getNetworkId(), dv); + appendMessage(static_cast(CM_clientResourceHarvesterResourceData), 0.0f, newData, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); } } - break; - + } + break; + case CM_clientResourceHarvesterEmptyHopper: - { - const MessageQueueResourceEmptyHopper * const msg = NON_NULL (dynamic_cast(data)); - - HarvesterInstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId (msg->getHarvesterId ())); - - if (harvester && owner && harvester->isOnHopperList(*owner)) - harvester->emptyHopper (msg->getPlayerId(),msg->getResourceId(), msg->getAmount(),msg->getDiscard(),msg->getSequenceId()); - } - break; + { + const MessageQueueResourceEmptyHopper * const msg = NON_NULL(dynamic_cast(data)); + + HarvesterInstallationObject * const harvester = dynamic_cast(ServerWorld::findObjectByNetworkId(msg->getHarvesterId())); + + if (harvester && owner && harvester->isOnHopperList(*owner)) + harvester->emptyHopper(msg->getPlayerId(), msg->getResourceId(), msg->getAmount(), msg->getDiscard(), msg->getSequenceId()); + } + break; case CM_getTokenForObject: - { - WARNING_STRICT_FATAL(true, ("Received CM_getTokenForObject controller message. This message is depracated")); - } - break; + { + WARNING_STRICT_FATAL(true, ("Received CM_getTokenForObject controller message. This message is depracated")); + } + break; case CM_getWaypointForObject: + { + const MessageQueueNetworkId * const msg = NON_NULL(dynamic_cast(data)); + if (msg) { - const MessageQueueNetworkId * const msg = NON_NULL (dynamic_cast(data)); - if(msg) + if (owner) { - if(owner) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) + const ServerObject * target = ServerWorld::findObjectByNetworkId(msg->getNetworkId()); + if (target) { - const ServerObject * target = ServerWorld::findObjectByNetworkId(msg->getNetworkId()); - if(target) + const Object * topMost = ContainerInterface::getFirstParentInWorld(*target); + if (topMost) { - const Object * topMost = ContainerInterface::getFirstParentInWorld(*target); - if(topMost) - { - const Vector pos = topMost->getPosition_w(); - IGNORE_RETURN(player->createWaypoint(Location(pos, NetworkId::cms_invalid, Location::getCrcBySceneName(ServerWorld::getSceneId())), true)); - } + const Vector pos = topMost->getPosition_w(); + IGNORE_RETURN(player->createWaypoint(Location(pos, NetworkId::cms_invalid, Location::getCrcBySceneName(ServerWorld::getSceneId())), true)); } } } } } - break; + } + break; case CM_secureTrade: + { + if (owner->isAuthoritative()) { - if (owner->isAuthoritative()) - { - handleSecureTradeMessage(dynamic_cast(data)); - } - // @todo else - //resend to auth - + handleSecureTradeMessage(dynamic_cast(data)); } - break; + // @todo else + //resend to auth + } + break; case CM_clientLookAtTarget: - { - const MessageQueueNetworkId * const msg = NON_NULL (dynamic_cast(data)); - owner->setLookAtTarget (msg->getNetworkId ()); - } - break; + { + const MessageQueueNetworkId * const msg = NON_NULL(dynamic_cast(data)); + owner->setLookAtTarget(msg->getNetworkId()); + } + break; case CM_clientIntendedTarget: - { - const MessageQueueNetworkId * const msg = NON_NULL (dynamic_cast(data)); - owner->setIntendedTarget (msg->getNetworkId ()); - } - break; + { + const MessageQueueNetworkId * const msg = NON_NULL(dynamic_cast(data)); + owner->setIntendedTarget(msg->getNetworkId()); + } + break; case CM_clientMoodChange: - if (value < 0.0f || value > 255.0f) - WARNING (true, ("Out of range mood: %f", value)); + if (value < 0.0f || value > 255.0f) + WARNING(true, ("Out of range mood: %f", value)); else - owner->setMood (static_cast(value)); - + owner->setMood(static_cast(value)); + break; - + case CM_setState: + { + if (!(flags&GameControllerMessageFlags::SOURCE_REMOTE_CLIENT)) { - if (!(flags&GameControllerMessageFlags::SOURCE_REMOTE_CLIENT)) - { - MessageQueueSetState const *msg = safe_cast(data); - owner->setState(static_cast(msg->getState()), msg->getValue()); - } + MessageQueueSetState const *msg = safe_cast(data); + owner->setState(static_cast(msg->getState()), msg->getValue()); } - break; + } + break; case CM_setAttribute: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (owner) { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if(owner) + if (msg) { const std::pair & attributePair = msg->getValue(); - if(msg) - { - owner->setAttribute(attributePair.first, attributePair.second); - } - DEBUG_WARNING(! msg, ("CreatureController (%s:%s) received a CM_setAttribute message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + owner->setAttribute(attributePair.first, attributePair.second); } + DEBUG_WARNING(!msg, ("CreatureController (%s:%s) received a CM_setAttribute message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); } - break; + } + break; case CM_setMaxAttribute: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + // set the object value and send a message to all it's proxies + if (msg) { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - // set the object value and send a message to all it's proxies - if(msg) - { - owner->setMaxAttribute(msg->getValue().first, msg->getValue().second); - } - DEBUG_WARNING(! msg, ("CreatureController (%s:%s) received a CM_setMaxAttribute message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + owner->setMaxAttribute(msg->getValue().first, msg->getValue().second); } - break; + DEBUG_WARNING(!msg, ("CreatureController (%s:%s) received a CM_setMaxAttribute message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + } + break; case CM_setMentalState: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + // set the object value and send a message to all it's proxies + if (msg) { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - // set the object value and send a message to all it's proxies - if(msg) - { - owner->setMentalState(msg->getValue().first, msg->getValue().second); - } - DEBUG_WARNING(! msg, ("CreatureController (%s:%s) received a CM_setMentalState message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + owner->setMentalState(msg->getValue().first, msg->getValue().second); } - break; + DEBUG_WARNING(!msg, ("CreatureController (%s:%s) received a CM_setMentalState message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + } + break; case CM_setMentalStateToward: + { + const MessageQueueGenericValueType > > * const msg = safe_cast > > *>(data); + if (msg) { - const MessageQueueGenericValueType > > * const msg = safe_cast > > *>(data); - if(msg) - { - owner->setMentalStateToward(msg->getValue().first, msg->getValue().second.first, msg->getValue().second.second); - } - DEBUG_WARNING(! msg, ("CreatureController (%s:%s) received a CM_setMentalStateToward message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + owner->setMentalStateToward(msg->getValue().first, msg->getValue().second.first, msg->getValue().second.second); } - break; + DEBUG_WARNING(!msg, ("CreatureController (%s:%s) received a CM_setMentalStateToward message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + } + break; case CM_setCover: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setCover(msg->getValue()); - } - DEBUG_WARNING(! msg, ("CreatureController (%s:%s) received a CM_setCover message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + owner->setCover(msg->getValue()); } - break; + DEBUG_WARNING(!msg, ("CreatureController (%s:%s) received a CM_setCover message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + } + break; case CM_setMentalStateTowardClampBehavior: + { + const MessageQueueGenericValueType > > > * const msg = safe_cast > > > *>(data); + if (msg) { - const MessageQueueGenericValueType > > > * const msg = safe_cast > > > *>(data); - if(msg) - { - owner->setMentalStateTowardClampBehavior( - msg->getValue().first, - msg->getValue().second.first, - msg->getValue().second.second.first, - msg->getValue().second.second.second); - } - DEBUG_WARNING(! msg, ("CreatureController (%s:%s) received a CM_setMentalStateTowardClampBehavior message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + owner->setMentalStateTowardClampBehavior( + msg->getValue().first, + msg->getValue().second.first, + msg->getValue().second.second.first, + msg->getValue().second.second.second); } - break; + DEBUG_WARNING(!msg, ("CreatureController (%s:%s) received a CM_setMentalStateTowardClampBehavior message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + } + break; case CM_setMaxMentalState: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (msg) { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if(msg) - { - owner->setMaxMentalState(msg->getValue().first, msg->getValue().second); - } - DEBUG_WARNING(! msg, ("CreatureController (%s:%s) received a CM_setMaxMentalState message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + owner->setMaxMentalState(msg->getValue().first, msg->getValue().second); } - break; + DEBUG_WARNING(!msg, ("CreatureController (%s:%s) received a CM_setMaxMentalState message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + } + break; case CM_setMentalStateDecay: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (msg) { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if(msg) - { - owner->setMentalStateDecay(msg->getValue().first, msg->getValue().second); - } - DEBUG_WARNING(! msg, ("CreatureController (%s:%s) received a CM_setMentalStateDecay message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + owner->setMentalStateDecay(msg->getValue().first, msg->getValue().second); } - break; + DEBUG_WARNING(!msg, ("CreatureController (%s:%s) received a CM_setMentalStateDecay message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + } + break; case CM_setPosture: - { - const MessageQueuePosture * const msg = safe_cast(data); - - if(msg) - { - owner->setPosture(msg->getPosture(), msg->isClientImmediate()); - } - DEBUG_WARNING(! msg, ("CreatureController (%s:%s) received a CM_setPosture message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); - } - break; - case CM_setLocomotion: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setLocomotion(msg->getValue()); - } - DEBUG_WARNING(! msg, ("CreatureController (%s:%s) received a CM_setLocomotion message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); - } - break; - case CM_setGroupInviter: - { - const MessageQueueGenericValueType > > * const msg = safe_cast > > *>(data); - if (msg) - { - owner->setGroupInviter(msg->getValue().second.first, msg->getValue().first, msg->getValue().second.second); - } - } - break; - case CM_setPerformanceType: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if (msg) - { - owner->setPerformanceType(msg->getValue()); - } - } - break; - case CM_setPerformanceStartTime: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if (msg) - { - owner->setPerformanceStartTime(msg->getValue()); - } - } - break; - case CM_setPerformanceListenTarget: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if (msg) - { - owner->setPerformanceListenTarget(msg->getValue()); - } - } - break; - case CM_setPerformanceWatchTarget: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if (msg) - { - owner->setPerformanceWatchTarget(msg->getValue()); - } - } - break; - case CM_setModValue: - { - const - MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if(msg) - { - owner->setModValue(msg->getValue().first, msg->getValue().second); - } - } - break; - case CM_grantCommand: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->grantCommand(msg->getValue(), false); - } - } - break; - case CM_grantExperiencePoints: - { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if(msg) - { - owner->grantExperiencePoints(msg->getValue().first, msg->getValue().second); - } - } - break; - case CM_incrementKillMeter: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->incrementKillMeter(msg->getValue()); - } - } - break; - case CM_grantSkill: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - const SkillObject * newSkill = SkillManager::getInstance().getSkill(msg->getValue()); - if(newSkill) - { - owner->grantSkill(*newSkill); - } - } - } - break; - case CM_revokeCommand: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->revokeCommand(msg->getValue(), false); - } - } - break; - case CM_revokeSkill: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - const SkillObject * oldSkill = SkillManager::getInstance().getSkill(msg->getValue()); - if(oldSkill) - { - LOG("CustomerService", ("Skill: Removing skill %s from character %s via controller message.", - msg->getValue().c_str(), owner->getNetworkId().getValueString().c_str())); - owner->revokeSkill(*oldSkill); - } - } - } - break; - case CM_alterAttribute: - { - const MessageQueueAlterAttribute * const msg = safe_cast(data); - if(msg) - { - owner->alterAttribute(msg->getAttrib(), - msg->getDelta(), - msg->getCheckIncapacitation(), - msg->getSource() - ); - } - } - break; - case CM_addAttributeModifier: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->addAttributeModifier(msg->getValue()); - } - } - break; - case CM_removeAttributeModifiers: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->removeAttributeModifiers(msg->getValue()); - } - } - break; - case CM_removeAllAttributeModifiers: - { - owner->removeAllAttributeModifiers(); - } - break; - case CM_removeAllAttributeAndSkillmodModifiers: - { - owner->removeAllAttributeAndSkillmodMods(); - } - break; - case CM_setCurrentWeapon: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - WeaponObject * weapon = safe_cast(NetworkIdManager::getObjectById(msg->getValue())); - if(weapon) - owner->setCurrentWeapon(*weapon); - } - } - break; - case CM_setGroup: - { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if(msg) - { - GroupObject * group = safe_cast(NetworkIdManager::getObjectById(msg->getValue().second)); + { + const MessageQueuePosture * const msg = safe_cast(data); - if (group) - { - owner->setGroup(group, msg->getValue().first); - } - else if (!msg->getValue().second.isValid()) - { - if (owner->getGroup()) - owner->getGroup()->onGroupMemberRemoved(owner->getNetworkId(), msg->getValue().first); - } + if (msg) + { + owner->setPosture(msg->getPosture(), msg->isClientImmediate()); + } + DEBUG_WARNING(!msg, ("CreatureController (%s:%s) received a CM_setPosture message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + } + break; + case CM_setLocomotion: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->setLocomotion(msg->getValue()); + } + DEBUG_WARNING(!msg, ("CreatureController (%s:%s) received a CM_setLocomotion message but could not retrieve data from the message supplied", owner->getObjectTemplateName(), owner->getNetworkId().getValueString().c_str())); + } + break; + case CM_setGroupInviter: + { + const MessageQueueGenericValueType > > * const msg = safe_cast > > *>(data); + if (msg) + { + owner->setGroupInviter(msg->getValue().second.first, msg->getValue().first, msg->getValue().second.second); + } + } + break; + case CM_setPerformanceType: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->setPerformanceType(msg->getValue()); + } + } + break; + case CM_setPerformanceStartTime: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->setPerformanceStartTime(msg->getValue()); + } + } + break; + case CM_setPerformanceListenTarget: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->setPerformanceListenTarget(msg->getValue()); + } + } + break; + case CM_setPerformanceWatchTarget: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->setPerformanceWatchTarget(msg->getValue()); + } + } + break; + case CM_setModValue: + { + const + MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (msg) + { + owner->setModValue(msg->getValue().first, msg->getValue().second); + } + } + break; + case CM_grantCommand: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->grantCommand(msg->getValue(), false); + } + } + break; + case CM_grantExperiencePoints: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (msg) + { + owner->grantExperiencePoints(msg->getValue().first, msg->getValue().second); + } + } + break; + case CM_incrementKillMeter: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->incrementKillMeter(msg->getValue()); + } + } + break; + case CM_grantSkill: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + const SkillObject * newSkill = SkillManager::getInstance().getSkill(msg->getValue()); + if (newSkill) + { + owner->grantSkill(*newSkill); } } - break; + } + break; + case CM_revokeCommand: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->revokeCommand(msg->getValue(), false); + } + } + break; + case CM_revokeSkill: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + const SkillObject * oldSkill = SkillManager::getInstance().getSkill(msg->getValue()); + if (oldSkill) + { + LOG("CustomerService", ("Skill: Removing skill %s from character %s via controller message.", + msg->getValue().c_str(), owner->getNetworkId().getValueString().c_str())); + owner->revokeSkill(*oldSkill); + } + } + } + break; + case CM_alterAttribute: + { + const MessageQueueAlterAttribute * const msg = safe_cast(data); + if (msg) + { + owner->alterAttribute(msg->getAttrib(), + msg->getDelta(), + msg->getCheckIncapacitation(), + msg->getSource() + ); + } + } + break; + case CM_addAttributeModifier: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->addAttributeModifier(msg->getValue()); + } + } + break; + case CM_removeAttributeModifiers: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->removeAttributeModifiers(msg->getValue()); + } + } + break; + case CM_removeAllAttributeModifiers: + { + owner->removeAllAttributeModifiers(); + } + break; + case CM_removeAllAttributeAndSkillmodModifiers: + { + owner->removeAllAttributeAndSkillmodMods(); + } + break; + case CM_setCurrentWeapon: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + WeaponObject * weapon = safe_cast(NetworkIdManager::getObjectById(msg->getValue())); + if (weapon) + owner->setCurrentWeapon(*weapon); + } + } + break; + case CM_setGroup: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (msg) + { + GroupObject * group = safe_cast(NetworkIdManager::getObjectById(msg->getValue().second)); + + if (group) + { + owner->setGroup(group, msg->getValue().first); + } + else if (!msg->getValue().second.isValid()) + { + if (owner->getGroup()) + owner->getGroup()->onGroupMemberRemoved(owner->getNetworkId(), msg->getValue().first); + } + } + } + break; case CM_setIncapacitated: - { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if (msg != nullptr) - owner->setIncapacitated(msg->getValue().first, msg->getValue().second); - } - break; + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (msg != nullptr) + owner->setIncapacitated(msg->getValue().first, msg->getValue().second); + } + break; case CM_setSayMode: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setSayMode(msg->getValue()); - } + owner->setSayMode(msg->getValue()); } - break; + } + break; case CM_setAnimationMood: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setAnimationMood(msg->getValue()); - } + owner->setAnimationMood(msg->getValue()); } - break; + } + break; case CM_setScaleFactor: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setScaleFactor(msg->getValue()); - } + owner->setScaleFactor(msg->getValue()); } - break; + } + break; case CM_setShockWounds: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setShockWounds(msg->getValue()); - } + owner->setShockWounds(msg->getValue()); } - break; + } + break; case CM_setLookAtTarget: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setLookAtTarget(msg->getValue()); - } + owner->setLookAtTarget(msg->getValue()); } - break; + } + break; case CM_setIntendedTarget: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setIntendedTarget(msg->getValue()); - } + owner->setIntendedTarget(msg->getValue()); } - break; + } + break; case CM_setMovementStationary: - { - owner->setMovementStationary(); - } - break; + { + owner->setMovementStationary(); + } + break; case CM_setMovementWalk: - { - owner->setMovementWalk(); - } - break; + { + owner->setMovementWalk(); + } + break; case CM_setMovementRun: - { - owner->setMovementRun(); - } - break; + { + owner->setMovementRun(); + } + break; case CM_setSlopeModAngle: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setSlopeModAngle(msg->getValue()); - } + owner->setSlopeModAngle(msg->getValue()); } - break; + } + break; case CM_setSlopeModPercent: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setSlopeModPercent(msg->getValue()); - } + owner->setSlopeModPercent(msg->getValue()); } - break; + } + break; case CM_setWaterModPercent: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setWaterModPercent(msg->getValue()); - } + owner->setWaterModPercent(msg->getValue()); } - break; + } + break; case CM_setMovementScale: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setMovementScale(msg->getValue()); - } + owner->setMovementScale(msg->getValue()); } - break; + } + break; case CM_setMovementPercent: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setMovementPercent(msg->getValue()); - } + owner->setMovementPercent(msg->getValue()); } - break; + } + break; case CM_setTurnPercent: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setTurnPercent(msg->getValue()); - } + owner->setTurnPercent(msg->getValue()); } - break; + } + break; case CM_setAccelScale: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setAccelScale(msg->getValue()); - } + owner->setAccelScale(msg->getValue()); } - break; + } + break; case CM_setAccelPercent: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - owner->setAccelPercent(msg->getValue()); - } + owner->setAccelPercent(msg->getValue()); } - break; + } + break; case CM_sitOnObject: + { + const MessageQueueSitOnObject * const msg = safe_cast(data); + if (msg) { - const MessageQueueSitOnObject * const msg = safe_cast(data); - if(msg) - { - owner->sitOnObject(msg->getChairCellId(), msg->getChairPosition_p()); - } + owner->sitOnObject(msg->getChairCellId(), msg->getChairPosition_p()); } - break; + } + break; case CM_setMasterId: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if (msg) - { - owner->setMasterId(msg->getValue()); - } + owner->setMasterId(msg->getValue()); } - break; + } + break; case CM_setHouse: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if (msg) - { - owner->setHouse(CachedNetworkId(msg->getValue())); - } + owner->setHouse(CachedNetworkId(msg->getValue())); } - break; + } + break; case CM_setDifficulty: case CM_setLevel: - { - MessageQueueGenericValueType const *msg = safe_cast const *>(data); - if (msg) - owner->setLevel(static_cast(msg->getValue())); - } - break; + { + MessageQueueGenericValueType const *msg = safe_cast const *>(data); + if (msg) + owner->setLevel(static_cast(msg->getValue())); + } + break; case CM_recalculateLevel: - { - MessageQueueGenericValueType const *msg = safe_cast const *>(data); - if (msg) - owner->recalculateLevel(); - } - break; - + { + MessageQueueGenericValueType const *msg = safe_cast const *>(data); + if (msg) + owner->recalculateLevel(); + } + break; case CM_creatureSetBaseWalkSpeed: owner->setBaseWalkSpeed(value); @@ -832,518 +829,518 @@ void CreatureController::handleMessage (const int message, const float value, co break; case CM_detachRiderForMount: - { - typedef MessageQueueGenericValueType Message; - Message const * const msg = safe_cast(data); + { + typedef MessageQueueGenericValueType Message; + Message const * const msg = safe_cast(data); - if (msg != 0) - { - owner->detachRider(msg->getValue()); - } - break; + if (msg != 0) + { + owner->detachRider(msg->getValue()); } + break; + } case CM_detachAllRidersForMount: owner->detachAllRiders(); break; case CM_setAppearanceFromObjectTemplate: - { - MessageQueueGenericValueType const *const msg = dynamic_cast const *>(data); - if (owner && msg) - owner->setAlternateAppearance(msg->getValue()); - else - WARNING(true, ("CreatureController: received CM_setAppearanceFromObjectTemplate but owner or message was nullptr.")); - } - break; + { + MessageQueueGenericValueType const *const msg = dynamic_cast const *>(data); + if (owner && msg) + owner->setAlternateAppearance(msg->getValue()); + else + WARNING(true, ("CreatureController: received CM_setAppearanceFromObjectTemplate but owner or message was nullptr.")); + } + break; case CM_makeDead: + { + const MessageQueueGenericValueType > * msg = dynamic_cast > *>(data); + if (msg) { - const MessageQueueGenericValueType > * msg = dynamic_cast > *>(data); - if (msg) - { - owner->makeDead(msg->getValue().first, msg->getValue().second); - } + owner->makeDead(msg->getValue().first, msg->getValue().second); } - break; + } + break; case CM_pushCreature: + { + const MessageQueuePushCreature * const msg = safe_cast(data); + if (msg) { - const MessageQueuePushCreature * const msg = safe_cast(data); - if (msg) + ServerObject * defender = safe_cast(NetworkIdManager::getObjectById(msg->getDefender())); + if (defender != nullptr) { - ServerObject * defender = safe_cast(NetworkIdManager::getObjectById(msg->getDefender())); - if (defender != nullptr) + if (defender->asCreatureObject() != nullptr) { - if (defender->asCreatureObject() != nullptr) - { - defender->asCreatureObject()->pushedMe(msg->getAttacker(), msg->getAttackerPos(), msg->getDefenderPos(), msg->getDistance()); - } - else - { - WARNING(true, ("Received MessageQueuePushCreature for non-creature defender %s", msg->getDefender().getValueString().c_str())); - } + defender->asCreatureObject()->pushedMe(msg->getAttacker(), msg->getAttackerPos(), msg->getDefenderPos(), msg->getDistance()); + } + else + { + WARNING(true, ("Received MessageQueuePushCreature for non-creature defender %s", msg->getDefender().getValueString().c_str())); } } } - break; + } + break; case CM_slowDownEffect: + { + const MessageQueueSlowDownEffect * const msg = safe_cast(data); + if (msg) { - const MessageQueueSlowDownEffect * const msg = safe_cast(data); - if (msg) + ServerObject * target = safe_cast(NetworkIdManager::getObjectById(msg->getTarget())); + if (target != nullptr && target->asTangibleObject() != nullptr) { - ServerObject * target = safe_cast(NetworkIdManager::getObjectById(msg->getTarget())); - if (target != nullptr && target->asTangibleObject() != nullptr) - { - if (owner->isAuthoritative()) - owner->addSlowDownEffect(*(target->asTangibleObject()), msg->getConeLength(), msg->getConeAngle(), msg->getSlopeAngle(), msg->getExpireTime()); - else - owner->addSlowDownEffectProxy(*(target->asTangibleObject()), msg->getConeLength(), msg->getConeAngle(), msg->getSlopeAngle(), msg->getExpireTime()); - } + if (owner->isAuthoritative()) + owner->addSlowDownEffect(*(target->asTangibleObject()), msg->getConeLength(), msg->getConeAngle(), msg->getSlopeAngle(), msg->getExpireTime()); else - { - WARNING(true, ("Received slow down effect messge for creature %s " - "with unknown target %s", - owner->getNetworkId().getValueString().c_str(), - msg->getTarget().getValueString().c_str())); - } + owner->addSlowDownEffectProxy(*(target->asTangibleObject()), msg->getConeLength(), msg->getConeAngle(), msg->getSlopeAngle(), msg->getExpireTime()); + } + else + { + WARNING(true, ("Received slow down effect messge for creature %s " + "with unknown target %s", + owner->getNetworkId().getValueString().c_str(), + msg->getTarget().getValueString().c_str())); } } - break; + } + break; case CM_removeSlowDownEffect: + { + if (owner->isAuthoritative()) + owner->removeSlowDownEffect(); + else { - if (owner->isAuthoritative()) - owner->removeSlowDownEffect(); - else - { - WARNING(true, ("CM_removeSlowDownEffect message recieved by proxy object %s", owner->getNetworkId().getValueString().c_str())); - } + WARNING(true, ("CM_removeSlowDownEffect message recieved by proxy object %s", owner->getNetworkId().getValueString().c_str())); } - break; + } + break; case CM_removeSlowDownEffectProxy: + { + if (!owner->isAuthoritative()) + owner->removeSlowDownEffectProxy(); + else { - if (!owner->isAuthoritative()) - owner->removeSlowDownEffectProxy(); - else - { - WARNING(true, ("CM_removeSlowDownEffectProxy message recieved by authoritative object %s", owner->getNetworkId().getValueString().c_str())); - } + WARNING(true, ("CM_removeSlowDownEffectProxy message recieved by authoritative object %s", owner->getNetworkId().getValueString().c_str())); } - break; + } + break; case CM_groupLotteryWindowCloseResults: + { + typedef std::pair > Payload; + + MessageQueueGenericValueType const * const msg = safe_cast const *>(data); + if (msg != 0) { - typedef std::pair > Payload; + Payload const & incomingPayload = msg->getValue(); - MessageQueueGenericValueType const * const msg = safe_cast const *>(data); - if (msg != 0) + typedef std::vector Ids; + + NetworkId const & player = incomingPayload.first; + Ids const & selectedItems = incomingPayload.second; + + GameScriptObject * const scriptObject = owner->getScriptObject(); + if (scriptObject != 0) { - Payload const & incomingPayload = msg->getValue(); - - typedef std::vector Ids; - - NetworkId const & player = incomingPayload.first; - Ids const & selectedItems = incomingPayload.second; - - GameScriptObject * const scriptObject = owner->getScriptObject(); - if (scriptObject != 0) - { - ScriptParams params; - params.addParam(player); - params.addParam(selectedItems); - IGNORE_RETURN(scriptObject->trigAllScripts(Scripting::TRIG_LOOT_LOTTERY_SELECTED, params)); - } + ScriptParams params; + params.addParam(player); + params.addParam(selectedItems); + IGNORE_RETURN(scriptObject->trigAllScripts(Scripting::TRIG_LOOT_LOTTERY_SELECTED, params)); } } - break; + } + break; case CM_cyberneticsChangeRequestToNPC: + { + MessageQueueCyberneticsChangeRequest const * const msg = safe_cast(data); + NOT_NULL(msg); + if (msg != nullptr) { - MessageQueueCyberneticsChangeRequest const * const msg = safe_cast(data); - NOT_NULL(msg); - if (msg != nullptr) + NetworkId const & playerId = msg->getTarget(); + GameScriptObject * const scriptObject = owner->getScriptObject(); + if (scriptObject) { - NetworkId const & playerId = msg->getTarget(); - GameScriptObject * const scriptObject = owner->getScriptObject(); - if (scriptObject) - { - ScriptParams params; - params.addParam(playerId); - params.addParam(static_cast(msg->getChangeType())); - params.addParam(msg->getCyberneticPiece()); - - IGNORE_RETURN(scriptObject->trigAllScripts(Scripting::TRIG_CYBERNETIC_CHANGE_REQUEST, params)); - } + ScriptParams params; + params.addParam(playerId); + params.addParam(static_cast(msg->getChangeType())); + params.addParam(msg->getCyberneticPiece()); + + IGNORE_RETURN(scriptObject->trigAllScripts(Scripting::TRIG_CYBERNETIC_CHANGE_REQUEST, params)); } } - break; + } + break; case CM_setCurrentQuest: + { + MessageQueueGenericValueType const * const msg = safe_cast const *>(data); + if (msg != nullptr) { - MessageQueueGenericValueType const * const msg = safe_cast const *>(data); - if (msg != nullptr) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player != nullptr) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if (player != nullptr) - { - player->setCurrentQuest(msg->getValue()); - } - else - { - DEBUG_WARNING(true, ("Non-player creature %s sent CM_setCurrentQuest message (%u)", - owner->getNetworkId().getValueString().c_str(), msg->getValue())); - } + player->setCurrentQuest(msg->getValue()); + } + else + { + DEBUG_WARNING(true, ("Non-player creature %s sent CM_setCurrentQuest message (%u)", + owner->getNetworkId().getValueString().c_str(), msg->getValue())); } } - break; + } + break; case CM_setRegenRate: + { + MessageQueueGenericValueType > const * const msg = safe_cast > const *>(data); + if (msg != nullptr) { - MessageQueueGenericValueType > const * const msg = safe_cast > const *>(data); - if (msg != nullptr) - { - owner->setRegenRate(static_cast(msg->getValue().first), msg->getValue().second); - } + owner->setRegenRate(static_cast(msg->getValue().first), msg->getValue().second); } - break; + } + break; case CM_modifyCurrentGcwPoints: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (msg) { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if(msg) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->modifyCurrentGcwPoints(msg->getValue().first, (msg->getValue().second != 0)); - } + player->modifyCurrentGcwPoints(msg->getValue().first, (msg->getValue().second != 0)); } } - break; + } + break; case CM_modifyCurrentGcwRating: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (msg) { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if(msg) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->modifyCurrentGcwRating(msg->getValue().first, (msg->getValue().second != 0)); - } + player->modifyCurrentGcwRating(msg->getValue().first, (msg->getValue().second != 0)); } } - break; + } + break; case CM_modifyCurrentPvpKills: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (msg) { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if(msg) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->modifyCurrentPvpKills(msg->getValue().first, (msg->getValue().second != 0)); - } + player->modifyCurrentPvpKills(msg->getValue().first, (msg->getValue().second != 0)); } } - break; + } + break; case CM_modifyLifetimeGcwPoints: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->modifyLifetimeGcwPoints(msg->getValue()); - } + player->modifyLifetimeGcwPoints(msg->getValue()); } } - break; + } + break; case CM_modifyMaxGcwImperialRating: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->modifyMaxGcwImperialRating(msg->getValue()); - } + player->modifyMaxGcwImperialRating(msg->getValue()); } } - break; + } + break; case CM_modifyMaxGcwRebelRating: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->modifyMaxGcwRebelRating(msg->getValue()); - } + player->modifyMaxGcwRebelRating(msg->getValue()); } } - break; + } + break; case CM_modifyLifetimePvpKills: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->modifyLifetimePvpKills(msg->getValue()); - } + player->modifyLifetimePvpKills(msg->getValue()); } } - break; + } + break; case CM_modifyNextGcwRatingCalcTime: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->modifyNextGcwRatingCalcTime(msg->getValue()); - } + player->modifyNextGcwRatingCalcTime(msg->getValue()); } } - break; + } + break; case CM_customizeFinished: + { + typedef std::pair Payload; + + MessageQueueGenericValueType const * const msg = safe_cast const *>(data); + if (msg != 0) { - typedef std::pair Payload; + Payload const & incomingPayload = msg->getValue(); - MessageQueueGenericValueType const * const msg = safe_cast const *>(data); - if (msg != 0) + NetworkId const & object = incomingPayload.first; + std::string const & msgValue = incomingPayload.second; + + GameScriptObject * const scriptObject = owner->getScriptObject(); + if (scriptObject != 0) { - Payload const & incomingPayload = msg->getValue(); - - NetworkId const & object = incomingPayload.first; - std::string const & msgValue = incomingPayload.second; - - GameScriptObject * const scriptObject = owner->getScriptObject(); - if (scriptObject != 0) - { - ScriptParams params; - params.addParam(object); - params.addParam(msgValue.c_str()); - IGNORE_RETURN(scriptObject->trigAllScripts(Scripting::TRIG_ON_CUSTOMIZE_FINISHED, params)); - } + ScriptParams params; + params.addParam(object); + params.addParam(msgValue.c_str()); + IGNORE_RETURN(scriptObject->trigAllScripts(Scripting::TRIG_ON_CUSTOMIZE_FINISHED, params)); } } - break; + } + break; case CM_clearSessionActivity: + { + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->clearSessionActivity(); - } + player->clearSessionActivity(); } - break; + } + break; case CM_addSessionActivity: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->addSessionActivity(static_cast(msg->getValue())); - } - } - } - break; - - case CM_modifyHologramType: - { - MessageQueueGenericValueType const *msg = safe_cast const *>(data); - if (msg) - owner->setHologramType(msg->getValue()); - } - break; - - case CM_modifyVisibleOnMapAndRadar: - { - MessageQueueGenericValueType const *msg = safe_cast const *>(data); - if (msg) - owner->setVisibleOnMapAndRadar(msg->getValue()); - } - break; - - case CM_setCoverVisibility: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if (msg) - { - owner->setCoverVisibility(msg->getValue()); - } - } - break; - - case CM_incubatorCancel: - { - IncubatorCommitMessage const * const msg = safe_cast(data); - if (msg) - { - ServerObject * incubatorSo = ServerWorld::findObjectByNetworkId(msg->getTerminalId()); - if (incubatorSo) - { - TangibleObject * incubatorTo = incubatorSo->asTangibleObject(); - - if (incubatorTo) - incubatorTo->handleIncubatorCancel(*owner); - } - } - } - break; - - case CM_incubatorCommit: - { - IncubatorCommitMessage const * const msg = safe_cast(data); - if (msg) - { - ServerObject * incubatorSo = ServerWorld::findObjectByNetworkId(msg->getTerminalId()); - if (incubatorSo) - { - TangibleObject * incubatorTo = incubatorSo->asTangibleObject(); - - if (incubatorTo) - incubatorTo->handleIncubatorCommit(*owner, *msg); - } - } - } - break; - - case CM_modifyCollectionSlotValue: - { - const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); - if(msg) - { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->modifyCollectionSlotValue(msg->getValue().first, msg->getValue().second); - } - } - } - break; - - case CM_adjustLotCount: - { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) - { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->adjustLotCount(msg->getValue()); - } - } - } - break; - - case CM_squelch: - { - const MessageQueueGenericValueType > > * const msg = safe_cast > > *>(data); - if(msg) - { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->squelch(msg->getValue().second.first, msg->getValue().first, msg->getValue().second.second); - } - } - } - break; - - case CM_unsquelch: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) + if (player) { - player->unsquelch(); + player->addSessionActivity(static_cast(msg->getValue())); } } - break; + } + break; + + case CM_modifyHologramType: + { + MessageQueueGenericValueType const *msg = safe_cast const *>(data); + if (msg) + owner->setHologramType(msg->getValue()); + } + break; + + case CM_modifyVisibleOnMapAndRadar: + { + MessageQueueGenericValueType const *msg = safe_cast const *>(data); + if (msg) + owner->setVisibleOnMapAndRadar(msg->getValue()); + } + break; + + case CM_setCoverVisibility: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + owner->setCoverVisibility(msg->getValue()); + } + } + break; + + case CM_incubatorCancel: + { + IncubatorCommitMessage const * const msg = safe_cast(data); + if (msg) + { + ServerObject * incubatorSo = ServerWorld::findObjectByNetworkId(msg->getTerminalId()); + if (incubatorSo) + { + TangibleObject * incubatorTo = incubatorSo->asTangibleObject(); + + if (incubatorTo) + incubatorTo->handleIncubatorCancel(*owner); + } + } + } + break; + + case CM_incubatorCommit: + { + IncubatorCommitMessage const * const msg = safe_cast(data); + if (msg) + { + ServerObject * incubatorSo = ServerWorld::findObjectByNetworkId(msg->getTerminalId()); + if (incubatorSo) + { + TangibleObject * incubatorTo = incubatorSo->asTangibleObject(); + + if (incubatorTo) + incubatorTo->handleIncubatorCommit(*owner, *msg); + } + } + } + break; + + case CM_modifyCollectionSlotValue: + { + const MessageQueueGenericValueType > * const msg = safe_cast > *>(data); + if (msg) + { + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) + { + player->modifyCollectionSlotValue(msg->getValue().first, msg->getValue().second); + } + } + } + break; + + case CM_adjustLotCount: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) + { + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) + { + player->adjustLotCount(msg->getValue()); + } + } + } + break; + + case CM_squelch: + { + const MessageQueueGenericValueType > > * const msg = safe_cast > > *>(data); + if (msg) + { + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) + { + player->squelch(msg->getValue().second.first, msg->getValue().first, msg->getValue().second.second); + } + } + } + break; + + case CM_unsquelch: + { + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) + { + player->unsquelch(); + } + } + break; case CM_setPriviledgedTitle: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast *>(data); - if(msg) + PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); + if (player) { - PlayerObject * player = PlayerCreatureController::getPlayerObject(owner); - if(player) - { - player->setPriviledgedTitle(static_cast(msg->getValue())); - } + player->setPriviledgedTitle(static_cast(msg->getValue())); } } - break; + } + break; case CM_addBuff: + { + const MessageQueueGenericValueType > > > > * const msg = safe_cast > > > > *>(data); + if (msg) { - const MessageQueueGenericValueType > > > > * const msg = safe_cast > > > > *>(data); - if(msg) - { - owner->addBuff (static_cast(msg->getValue ().first), msg->getValue ().second.first, msg->getValue ().second.second.first, msg->getValue ().second.second.second.first, msg->getValue ().second.second.second.second); - } + owner->addBuff(static_cast(msg->getValue().first), msg->getValue().second.first, msg->getValue().second.second.first, msg->getValue().second.second.second.first, msg->getValue().second.second.second.second); } - break; + } + break; case CM_removeBuff: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast * >(data); - if(msg) - { - owner->removeBuff (static_cast(msg->getValue ())); - } + owner->removeBuff(static_cast(msg->getValue())); } - break; + } + break; case CM_ratingFinished: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast * >(data); - if(msg) + if (owner->getScriptObject()) { - if(owner->getScriptObject()) - { - ScriptParams params; - params.addParam(msg->getValue()); - IGNORE_RETURN(owner->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_RATING_FINISHED, params)); - } + ScriptParams params; + params.addParam(msg->getValue()); + IGNORE_RETURN(owner->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_RATING_FINISHED, params)); } } - break; + } + break; case CM_abandonPlayerQuest: + { + const MessageQueueGenericValueType * const msg = safe_cast *>(data); + if (msg) { - const MessageQueueGenericValueType * const msg = safe_cast * >(data); - if(msg) + if (owner->getScriptObject()) { - if(owner->getScriptObject()) - { - ScriptParams params; - params.addParam(msg->getValue()); - IGNORE_RETURN(owner->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_ABANDON_PLAYER_QUEST, params)); - } - } + ScriptParams params; + params.addParam(msg->getValue()); + IGNORE_RETURN(owner->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_ABANDON_PLAYER_QUEST, params)); + } } - break; + } + break; default: TangibleController::handleMessage(message, value, data, flags); @@ -1361,12 +1358,12 @@ float CreatureController::realAlter(float time) CreatureObject * const owner = NON_NULL(getCreature()); - if(getHibernate()) + if (getHibernate()) return alterResult; if (owner->isAuthoritative()) owner->decayAttributes(time); - + if (owner->isInWorld()) { bool isBurning = false; @@ -1381,23 +1378,23 @@ float CreatureController::realAlter(float time) bool const currentSwimState = owner->getState(States::Swimming); bool newSwimState = false; float waterHeight = 0.0f; - calculateWaterState(newSwimState,isBurning,lavaResistance,waterHeight); + calculateWaterState(newSwimState, isBurning, lavaResistance, waterHeight); - bool const isVehicle = GameObjectTypes::isTypeOf (owner->getGameObjectType (), static_cast(SharedObjectTemplate::GOT_vehicle)); - if(!isVehicle) // make everything but vehicles walk on lava + bool const isVehicle = GameObjectTypes::isTypeOf(owner->getGameObjectType(), static_cast(SharedObjectTemplate::GOT_vehicle)); + if (!isVehicle) // make everything but vehicles walk on lava { - const Vector & position = owner->getPosition_w (); + const Vector & position = owner->getPosition_w(); Footprint *const footprint = owner->getFootprint(); - if(footprint) + if (footprint) { - if(isBurning) + if (isBurning) { footprint->setSwimHeight(owner->getSwimHeight() * 0.2f); owner->move_p(Vector::unitY * (waterHeight - position.y)); } else { - footprint->setSwimHeight(owner->getSwimHeight()); + footprint->setSwimHeight(owner->getSwimHeight()); } } } @@ -1425,7 +1422,7 @@ float CreatureController::realAlter(float time) // update the rider's CollisionProperty extent causes line of sight // to fail (line of sight ends up using the value present in CollisionProperty // at the time of mounting). - + if (collisionProperty) collisionProperty->updateExtents(); } @@ -1433,43 +1430,43 @@ float CreatureController::realAlter(float time) const bool isPlayerControlled = (collisionProperty && collisionProperty->isPlayerControlled()); // lava damage - if(WaterTypeManager::getCausesDamage(TGWT_lava) - && isBurning + if (WaterTypeManager::getCausesDamage(TGWT_lava) + && isBurning && (isPlayerControlled || owner->isBeast()) - ) + ) { const unsigned long serverTime = ServerClock::getInstance().getGameTimeSeconds(); const unsigned long lastBurnTime = owner->getLastWaterDamageTime(); const unsigned long waterDamageInterval = WaterTypeManager::getDamageInterval(TGWT_lava); - if(serverTime - lastBurnTime > (waterDamageInterval*3)) // skip the first lava damage frame + if (serverTime - lastBurnTime > (waterDamageInterval * 3)) // skip the first lava damage frame { owner->setLastWaterDamageTime(serverTime - waterDamageInterval); //DEBUG_WARNING(true,("LAVA DAMAGE SLUSH TIME- serverTime=%ul, lastBurnTime=%ul, diff=%d",serverTime,lastBurnTime,serverTime-lastBurnTime)); - } - else if(serverTime - lastBurnTime > waterDamageInterval && !owner->isDead()) + } + else if (serverTime - lastBurnTime > waterDamageInterval && !owner->isDead()) { owner->setLastWaterDamageTime(serverTime); - const float percentWaterDamagePerInterval = WaterTypeManager::getDamagePerInterval(TGWT_lava)/100.0f; - const float lavaResistanceModifier = 1.0f - lavaResistance/100.0f; - - const int damageValue = + const float percentWaterDamagePerInterval = WaterTypeManager::getDamagePerInterval(TGWT_lava) / 100.0f; + const float lavaResistanceModifier = 1.0f - lavaResistance / 100.0f; + + const int damageValue = static_cast ( - -( owner->getMaxAttribute(Attributes::Health) - * percentWaterDamagePerInterval + -(owner->getMaxAttribute(Attributes::Health) + * percentWaterDamagePerInterval * lavaResistanceModifier - ) - ); - + ) + ); + StringId stringId = StringId("combat_effects", "environment_damage_lava"); - owner->showFlyText(stringId,5.0f,255,0,0); - - if(WaterTypeManager::getDamageKills(TGWT_lava) + owner->showFlyText(stringId, 5.0f, 255, 0, 0); + + if (WaterTypeManager::getDamageKills(TGWT_lava) && (owner->getAttribute(Attributes::Health) + damageValue) <= 0) { - owner->makeDead(NetworkId::cms_invalid, NetworkId::cms_invalid); + owner->makeDead(NetworkId::cms_invalid, NetworkId::cms_invalid); ScriptParams params; - owner->getScriptObject()->trigAllScripts(Scripting::TRIG_ENVIRONMENTAL_DEATH,params); + owner->getScriptObject()->trigAllScripts(Scripting::TRIG_ENVIRONMENTAL_DEATH, params); } else { @@ -1496,7 +1493,7 @@ float CreatureController::realAlter(float time) void CreatureController::conclude() { PROFILER_AUTO_BLOCK_DEFINE("CreatureController::conclude"); - + MessageQueue::Data* data; int message; @@ -1505,12 +1502,12 @@ void CreatureController::conclude() NetworkId networkId; int const messageCount = getNumberOfMessages(); - for(int i = 0; i < messageCount; ++i) + for (int i = 0; i < messageCount; ++i) { //-- Get the message. getMessage(i, &message, &value, &data, &flags); //@todo why does getMessage need a signed size? - if(message == CM_combatAction) + if (message == CM_combatAction) { //-- Check if it's a combat action message. If so, the message's end postures for the // combatants must be adjusted to reflect the server's idea of the post-alter end posture. @@ -1519,23 +1516,23 @@ void CreatureController::conclude() if (combatMessage != nullptr) { //-- Fix up end postures in messages. - + // @todo: change postures to locomotion // set the attacker's posture - MessageQueueCombatAction::AttackerData & attackerData = + MessageQueueCombatAction::AttackerData & attackerData = const_cast( combatMessage->getAttacker()); const CreatureObject * attacker = dynamic_cast( NetworkIdManager::getObjectById(attackerData.id)); attackerData.endPosture = (attacker != nullptr) ? attacker->getPosture() : static_cast(0); - + // set the defenders' posture - const MessageQueueCombatAction::DefenderDataVector & defenderData = + const MessageQueueCombatAction::DefenderDataVector & defenderData = combatMessage->getDefenders(); - for (MessageQueueCombatAction::DefenderDataVector::const_iterator - iter(defenderData.begin()); iter != defenderData.end(); ++iter) + for (MessageQueueCombatAction::DefenderDataVector::const_iterator + iter(defenderData.begin()); iter != defenderData.end(); ++iter) { - MessageQueueCombatAction::DefenderData & defenderData = + MessageQueueCombatAction::DefenderData & defenderData = const_cast(*iter); const CreatureObject * defender = dynamic_cast( NetworkIdManager::getObjectById(defenderData.id)); @@ -1546,7 +1543,7 @@ void CreatureController::conclude() } CreatureObject * const owner = static_cast(getOwner()); - if(owner) + if (owner) { owner->checkNotifyRegions(); } @@ -1605,159 +1602,156 @@ void CreatureController::handleSecureTradeMessage(const MessageQueueSecureTrade switch (data->getTradeMessageId()) { case MessageQueueSecureTrade::TMI_RequestTrade: + { + if (data->getRecipient() == owner->getNetworkId()) { - if (data->getRecipient() == owner->getNetworkId()) - { - DEBUG_REPORT_LOG(true, ("Creature %s tried to trade with himself.", getOwner()->getNetworkId().getValueString().c_str())); - return; - } - if (m_secureTrade) - { - DEBUG_REPORT_LOG(true, ("Creature %s is already trading\n", getOwner()->getNetworkId().getValueString().c_str())); - return; - } - - CreatureObject * recipient = dynamic_cast(ServerWorld::findObjectByNetworkId(data->getRecipient())); - if (!recipient) - { - DEBUG_REPORT_LOG(true, ("Could not find recipient for secure trade message\n")); - MessageQueueSecureTrade * m = new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_DeniedPlayerUnreachable, owner->getNetworkId(), data->getRecipient()); - appendMessage(static_cast(CM_secureTrade), 0.0f, m, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); - return; - } - - if (owner->isIncapacitated() || owner->isDead()) - { - DEBUG_REPORT_LOG(true, ("Owner creature %s is incapacitated or dead.\n", getOwner()->getNetworkId().getValueString().c_str())); - MessageQueueSecureTrade * m = new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_DeniedPlayerUnreachable, owner->getNetworkId(), data->getRecipient()); - appendMessage(static_cast(CM_secureTrade), 0.0f, m, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); - return; - } - else if (recipient->isIncapacitated() || recipient->isDead()) - { - DEBUG_REPORT_LOG(true, ("Recipient creature %s is incapacitated or dead.\n", getOwner()->getNetworkId().getValueString().c_str())); - MessageQueueSecureTrade * m = new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_DeniedPlayerUnreachable, owner->getNetworkId(), data->getRecipient()); - appendMessage(static_cast(CM_secureTrade), 0.0f, m, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); - return; - } - - if (! recipient->isAuthoritative()) - { - if (owner->isInWorldCell()) - { - // transfer player to authoritative server - owner->transferAuthority(recipient->getAuthServerProcessId(), true, false, true); - owner->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTrade, owner->getNetworkId(), data->getRecipient())); - } - else if (recipient->isInWorldCell()) - { - recipient->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTradeReversed, owner->getNetworkId(), data->getRecipient())); - } - else - { - DEBUG_REPORT_LOG(true, ("Player %s tried to trade with player " - "%s, but both were in interiors that are on different " - "servers. Cell/server= (%s/%lu), (%s/%lu)", - owner->getNetworkId().getValueString().c_str(), - recipient->getNetworkId().getValueString().c_str(), - ContainerInterface::getTopmostContainer(*owner)->getNetworkId().getValueString().c_str(), - owner->getAuthServerProcessId(), - ContainerInterface::getTopmostContainer(*recipient)->getNetworkId().getValueString().c_str(), - recipient->getAuthServerProcessId() - )); - } - } - else if (recipient->getClient() == nullptr) - { -// GameServer::getInstance().sendToPlanetServer( -// GenericValueTypeMessage >( -// "RequestSameServer", -// std::make_pair( -// ContainerInterface::getTopmostContainer(*owner)->getNetworkId(), -// ContainerInterface::getTopmostContainer(*recipient)->getNetworkId())), -// true); - - // transfer player to authoritative server - //owner->transferAuthority(recipient->getAuthServerProcessId(), true, false); - //owner->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTrade, owner->getNetworkId(), data->getRecipient())); - - // try again next frame - owner->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTrade, owner->getNetworkId(), data->getRecipient())); - } - else if (!ServerSecureTradeManager::requestTradeWith(*owner, *recipient)) - { - MessageQueueSecureTrade * m = new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_DeniedPlayerBusy, owner->getNetworkId(), recipient->getNetworkId()); - appendMessage(static_cast(CM_secureTrade), 0.0f, m, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); - - } - } - break; - - // we get this when the traders are on different servers, but the trade - // initiator can't be moved to our server - case MessageQueueSecureTrade::TMI_RequestTradeReversed: - { - CreatureObject * initiator = dynamic_cast(ServerWorld::findObjectByNetworkId(data->getInitiator())); - if (!initiator) - { - DEBUG_REPORT_LOG(true, ("Could not find initiator for reversed secure trade message\n")); - return; - } - if (! initiator->isAuthoritative()) - { - if (owner->isInWorldCell()) - { - // transfer player to authoritative server - owner->transferAuthority(initiator->getAuthServerProcessId(), true, false, true); - owner->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTradeReversed, initiator->getNetworkId(), owner->getNetworkId())); - } - else - { - WARNING(true, ("Got TMI_RequestTradeReversed, but we are not in the world! Trade request abandoned.")); - return; - } - } - else - initiator->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTrade, initiator->getNetworkId(), owner->getNetworkId())); - } - break; - - case MessageQueueSecureTrade::TMI_TradeRequested: - { - WARNING_STRICT_FATAL(true, ("Server should not receive this message\n")); + DEBUG_REPORT_LOG(true, ("Creature %s tried to trade with himself.", getOwner()->getNetworkId().getValueString().c_str())); return; } - break; + if (m_secureTrade) + { + DEBUG_REPORT_LOG(true, ("Creature %s is already trading\n", getOwner()->getNetworkId().getValueString().c_str())); + return; + } + + CreatureObject * recipient = dynamic_cast(ServerWorld::findObjectByNetworkId(data->getRecipient())); + if (!recipient) + { + DEBUG_REPORT_LOG(true, ("Could not find recipient for secure trade message\n")); + MessageQueueSecureTrade * m = new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_DeniedPlayerUnreachable, owner->getNetworkId(), data->getRecipient()); + appendMessage(static_cast(CM_secureTrade), 0.0f, m, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); + return; + } + + if (owner->isIncapacitated() || owner->isDead()) + { + DEBUG_REPORT_LOG(true, ("Owner creature %s is incapacitated or dead.\n", getOwner()->getNetworkId().getValueString().c_str())); + MessageQueueSecureTrade * m = new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_DeniedPlayerUnreachable, owner->getNetworkId(), data->getRecipient()); + appendMessage(static_cast(CM_secureTrade), 0.0f, m, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); + return; + } + else if (recipient->isIncapacitated() || recipient->isDead()) + { + DEBUG_REPORT_LOG(true, ("Recipient creature %s is incapacitated or dead.\n", getOwner()->getNetworkId().getValueString().c_str())); + MessageQueueSecureTrade * m = new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_DeniedPlayerUnreachable, owner->getNetworkId(), data->getRecipient()); + appendMessage(static_cast(CM_secureTrade), 0.0f, m, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); + return; + } + + if (!recipient->isAuthoritative()) + { + if (owner->isInWorldCell()) + { + // transfer player to authoritative server + owner->transferAuthority(recipient->getAuthServerProcessId(), true, false, true); + owner->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTrade, owner->getNetworkId(), data->getRecipient())); + } + else if (recipient->isInWorldCell()) + { + recipient->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTradeReversed, owner->getNetworkId(), data->getRecipient())); + } + else + { + DEBUG_REPORT_LOG(true, ("Player %s tried to trade with player " + "%s, but both were in interiors that are on different " + "servers. Cell/server= (%s/%lu), (%s/%lu)", + owner->getNetworkId().getValueString().c_str(), + recipient->getNetworkId().getValueString().c_str(), + ContainerInterface::getTopmostContainer(*owner)->getNetworkId().getValueString().c_str(), + owner->getAuthServerProcessId(), + ContainerInterface::getTopmostContainer(*recipient)->getNetworkId().getValueString().c_str(), + recipient->getAuthServerProcessId() + )); + } + } + else if (recipient->getClient() == nullptr) + { + // GameServer::getInstance().sendToPlanetServer( + // GenericValueTypeMessage >( + // "RequestSameServer", + // std::make_pair( + // ContainerInterface::getTopmostContainer(*owner)->getNetworkId(), + // ContainerInterface::getTopmostContainer(*recipient)->getNetworkId())), + // true); + + // transfer player to authoritative server + //owner->transferAuthority(recipient->getAuthServerProcessId(), true, false); + //owner->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTrade, owner->getNetworkId(), data->getRecipient())); + + // try again next frame + owner->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTrade, owner->getNetworkId(), data->getRecipient())); + } + else if (!ServerSecureTradeManager::requestTradeWith(*owner, *recipient)) + { + MessageQueueSecureTrade * m = new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_DeniedPlayerBusy, owner->getNetworkId(), recipient->getNetworkId()); + appendMessage(static_cast(CM_secureTrade), 0.0f, m, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); + } + } + break; + + // we get this when the traders are on different servers, but the trade + // initiator can't be moved to our server + case MessageQueueSecureTrade::TMI_RequestTradeReversed: + { + CreatureObject * initiator = dynamic_cast(ServerWorld::findObjectByNetworkId(data->getInitiator())); + if (!initiator) + { + DEBUG_REPORT_LOG(true, ("Could not find initiator for reversed secure trade message\n")); + return; + } + if (!initiator->isAuthoritative()) + { + if (owner->isInWorldCell()) + { + // transfer player to authoritative server + owner->transferAuthority(initiator->getAuthServerProcessId(), true, false, true); + owner->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTradeReversed, initiator->getNetworkId(), owner->getNetworkId())); + } + else + { + WARNING(true, ("Got TMI_RequestTradeReversed, but we are not in the world! Trade request abandoned.")); + return; + } + } + else + initiator->sendControllerMessageToAuthServer(CM_secureTrade, new MessageQueueSecureTrade(MessageQueueSecureTrade::TMI_RequestTrade, initiator->getNetworkId(), owner->getNetworkId())); + } + break; + + case MessageQueueSecureTrade::TMI_TradeRequested: + { + WARNING_STRICT_FATAL(true, ("Server should not receive this message\n")); + return; + } + break; case MessageQueueSecureTrade::TMI_AcceptTrade: + { + if (m_secureTrade || !m_secureTradeInitiator) { - if (m_secureTrade || !m_secureTradeInitiator) - { - DEBUG_REPORT_LOG(true, ("Trade acceptance denied because of previous trade or failed startup steps\n")); - return; - } - ServerSecureTradeManager::acceptTradeRequest(*m_secureTradeInitiator, *(static_cast(getOwner()))); - m_secureTradeInitiator = 0; - + DEBUG_REPORT_LOG(true, ("Trade acceptance denied because of previous trade or failed startup steps\n")); + return; } - break; + ServerSecureTradeManager::acceptTradeRequest(*m_secureTradeInitiator, *(static_cast(getOwner()))); + m_secureTradeInitiator = 0; + } + break; case MessageQueueSecureTrade::TMI_DeniedTrade: + { + if (m_secureTrade || !m_secureTradeInitiator) { - if (m_secureTrade || !m_secureTradeInitiator) - { - DEBUG_REPORT_LOG(true, ("Trade acceptance denied because of previous trade or failed startup steps\n")); - return; - } - ServerSecureTradeManager::refuseTrade(*m_secureTradeInitiator, *(static_cast(getOwner()))); - m_secureTradeInitiator = 0; - + DEBUG_REPORT_LOG(true, ("Trade acceptance denied because of previous trade or failed startup steps\n")); + return; } - break; + ServerSecureTradeManager::refuseTrade(*m_secureTradeInitiator, *(static_cast(getOwner()))); + m_secureTradeInitiator = 0; + } + break; default: - { - DEBUG_REPORT_LOG(true, ("Unhandled secure trade message type\n")); - } - break; + { + DEBUG_REPORT_LOG(true, ("Unhandled secure trade message type\n")); + } + break; } } @@ -1779,10 +1773,10 @@ bool CreatureController::tradeRequested(CreatureObject & initiator) //---------------------------------------------------------------------- -void CreatureController::sendGenericResponse (int responseType, int requestType, bool success, uint8 sequenceId) +void CreatureController::sendGenericResponse(int responseType, int requestType, bool success, uint8 sequenceId) { // send result back to player - MessageQueueGenericResponse * response = new MessageQueueGenericResponse (requestType, success, sequenceId); + MessageQueueGenericResponse * response = new MessageQueueGenericResponse(requestType, success, sequenceId); appendMessage(responseType, 0.0f, response, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); } @@ -1907,23 +1901,23 @@ void CreatureController::updateHibernate() bool CreatureController::shouldHibernate() const { - if(!ConfigServerGame::getHibernateEnabled()) + if (!ConfigServerGame::getHibernateEnabled()) return false; // ---------- CreatureObject const * creature = getCreature(); NOT_NULL(creature); - + // If the creature is static, it hibernates. - if(creature->getIsStatic()) + if (creature->getIsStatic()) return true; // If proxied creatures aren't allowed to hibernate and this creature is proxied, // it's not hibernating. - if(!ConfigServerGame::getHibernateProxies() && (creature->getProxyCount() > 0)) + if (!ConfigServerGame::getHibernateProxies() && (creature->getProxyCount() > 0)) return false; // if any players are observing me, don't hibernate @@ -1944,7 +1938,7 @@ bool CreatureController::getHibernate() const void CreatureController::setHibernate(bool newHibernate) { bool oldHibernate = getHibernate(); - if (oldHibernate == newHibernate) + if (oldHibernate == newHibernate) return; CreatureObject * owner = static_cast(getOwner()); @@ -1955,34 +1949,34 @@ void CreatureController::setHibernate(bool newHibernate) bool transitionOk = true; - if(newHibernate) + if (newHibernate) { ScriptParams params; int result = getServerOwner()->getScriptObject()->trigAllScripts(Scripting::TRIG_HIBERNATE_BEGIN, params); - if(result == SCRIPT_OVERRIDE) transitionOk = false; + if (result == SCRIPT_OVERRIDE) transitionOk = false; } else { ScriptParams params; int result = getServerOwner()->getScriptObject()->trigAllScripts(Scripting::TRIG_HIBERNATE_END, params); - if(result == SCRIPT_OVERRIDE) transitionOk = false; + if (result == SCRIPT_OVERRIDE) transitionOk = false; } // ---------- - if(transitionOk) + if (transitionOk) { - if(newHibernate) + if (newHibernate) { -// DEBUG_REPORT_LOG(true, ("[aitest] Hibernating %s\n", owner->getNetworkId().getValueString().c_str())); + // DEBUG_REPORT_LOG(true, ("[aitest] Hibernating %s\n", owner->getNetworkId().getValueString().c_str())); owner->setCondition(ServerTangibleObjectTemplate::C_hibernating); owner->setDefaultAlterTime(AlterResult::cms_keepNoAlter); } else { -// DEBUG_REPORT_LOG(true, ("[aitest] Waking up %s\n", owner->getNetworkId().getValueString().c_str())); + // DEBUG_REPORT_LOG(true, ("[aitest] Waking up %s\n", owner->getNetworkId().getValueString().c_str())); owner->clearCondition(ServerTangibleObjectTemplate::C_hibernating); if (owner->isPlayerControlled()) owner->setDefaultAlterTime(0); @@ -2013,70 +2007,70 @@ void CreatureController::calculateWaterState(bool& isSwimming, bool &isBurning, // Note: we do the real computation for the mount here because the rider gets // an alter prior to the mount. If we just checked the mount's swim state here, // we would be a frame behind on determining the player's swim state. - mountCreatureController->calculateWaterState(isSwimming,isBurning,lavaResistance,waterHeight); + mountCreatureController->calculateWaterState(isSwimming, isBurning, lavaResistance, waterHeight); return; } } //-- Determine if the owner is swimming. - CollisionProperty const * const collisionProperty = ownerCreature->getCollisionProperty (); + CollisionProperty const * const collisionProperty = ownerCreature->getCollisionProperty(); if (!collisionProperty) return; -// JU_TODO: disabled - possibly make burning a persistant state + // JU_TODO: disabled - possibly make burning a persistant state #if 0 //-- Don't recompute if we're idle --- it shouldn't have changed. bool const isIdle = collisionProperty && collisionProperty->isIdle(); if (isIdle) return ownerCreature->getState(States::Swimming); #endif -// JU_TODO: end disabled + // JU_TODO: end disabled - TerrainObject const * const terrainObject = TerrainObject::getConstInstance (); - bool const isOnSolidFloor = collisionProperty && collisionProperty->getFootprint () && collisionProperty->getFootprint ()->isOnSolidFloor (); + TerrainObject const * const terrainObject = TerrainObject::getConstInstance(); + bool const isOnSolidFloor = collisionProperty && collisionProperty->getFootprint() && collisionProperty->getFootprint()->isOnSolidFloor(); isSwimming = false; - - if (collisionProperty && ownerCreature->isInWorldCell () && !isOnSolidFloor) + + if (collisionProperty && ownerCreature->isInWorldCell() && !isOnSolidFloor) { - Vector const position = ownerCreature->getPosition_w (); + Vector const position = ownerCreature->getPosition_w(); float terrainHeight; Footprint const * foot = collisionProperty->getFootprint(); - + lavaResistance = ownerCreature->getLavaResistance(); bool const isImmuneToLava = (lavaResistance == 100.0f); - + TerrainGeneratorWaterType waterType = terrainObject->getWaterType(position); - if(!foot || !foot->getTerrainHeight(terrainHeight)) + if (!foot || !foot->getTerrainHeight(terrainHeight)) { - if(!terrainObject->getHeight(position,terrainHeight)) + if (!terrainObject->getHeight(position, terrainHeight)) { - if(!terrainObject->getHeightForceChunkCreation(position,terrainHeight)) + if (!terrainObject->getHeightForceChunkCreation(position, terrainHeight)) { return; } } } - + //-- see if the object is swimming and/or burning - if (terrainObject->getWaterHeight (position, waterHeight)) + if (terrainObject->getWaterHeight(position, waterHeight)) { - if(position.y - waterHeight < 1.0f && waterHeight >= terrainHeight) + if (position.y - waterHeight < 1.0f && waterHeight >= terrainHeight) { - float const swimHeight = ownerCreature->getSwimHeight (); + float const swimHeight = ownerCreature->getSwimHeight(); isSwimming = (terrainHeight + swimHeight) < waterHeight; - if(waterType == TGWT_lava) + if (waterType == TGWT_lava) { isSwimming = false; - if(!isImmuneToLava) + if (!isImmuneToLava) { isBurning = true; } } } } - } + } } // ---------------------------------------------------------------------- @@ -2089,10 +2083,10 @@ void CreatureController::onEnterSwimming() CreatureObject *const owner = safe_cast(getOwner()); if (!owner) return; - + //-- Set the state to swimming. owner->setState(States::Swimming, true); - + //-- Fire off the script trigger indicating that the owner is now swimming. ScriptParams params; IGNORE_RETURN(owner->getScriptObject()->trigAllScripts(Scripting::TRIG_ENTER_SWIMMING, params)); @@ -2108,10 +2102,10 @@ void CreatureController::onExitSwimming() CreatureObject *const owner = safe_cast(getOwner()); if (!owner) return; - + //-- Clear the state to swimming. owner->setState(States::Swimming, false); - + //-- Fire off the script trigger indicating that the owner is no longer swimming. ScriptParams params; IGNORE_RETURN(owner->getScriptObject()->trigAllScripts(Scripting::TRIG_EXIT_SWIMMING, params)); @@ -2189,4 +2183,4 @@ CreatureController const * CreatureController::asCreatureController(Controller c return (controller != nullptr) ? controller->asCreatureController() : nullptr; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/core/ServerBuildoutManager.cpp b/engine/server/library/serverGame/src/shared/core/ServerBuildoutManager.cpp index cf247722..8c2617ad 100755 --- a/engine/server/library/serverGame/src/shared/core/ServerBuildoutManager.cpp +++ b/engine/server/library/serverGame/src/shared/core/ServerBuildoutManager.cpp @@ -45,7 +45,6 @@ namespace ServerBuildoutManagerNamespace { - const int cs_buildingObjIdOffset = 2000; // ---------------------------------------------------------------------- @@ -80,23 +79,21 @@ namespace ServerBuildoutManagerNamespace struct ServerEventAreaInfo { - ServerEventAreaInfo(): - buildOut(nullptr), - loadedObject(nullptr) + ServerEventAreaInfo() : + buildOut(nullptr), + loadedObject(nullptr) { - } - ServerEventAreaInfo(BuildoutRow const * _buildOut, ServerObject* _loadedObject): - buildOut(_buildOut), - loadedObject(_loadedObject) + ServerEventAreaInfo(BuildoutRow const * _buildOut, ServerObject* _loadedObject) : + buildOut(_buildOut), + loadedObject(_loadedObject) { - } BuildoutRow const * buildOut; ServerObject* loadedObject; }; - + typedef std::map< std::string, std::list< ServerEventAreaInfo > > ServerEventMap; // ---------------------------------------------------------------------- @@ -120,7 +117,6 @@ namespace ServerBuildoutManagerNamespace #else const int64 cs_dataBitStripMask = 0x80000000ffffffffLL; #endif - } using namespace ServerBuildoutManagerNamespace; @@ -152,10 +148,10 @@ void ServerBuildoutManager::onChunkComplete(int nodeX, int nodeZ) for (std::vector::iterator i = s_areas.begin(); i != s_areas.end(); ++i) { AreaInfo &areaInfo = *i; - if ( nodeX < areaInfo.buildoutArea.rect.x1 - && nodeX+100 > areaInfo.buildoutArea.rect.x0 - && nodeZ < areaInfo.buildoutArea.rect.y1 - && nodeZ+100 > areaInfo.buildoutArea.rect.y0) + if (nodeX < areaInfo.buildoutArea.rect.x1 + && nodeX + 100 > areaInfo.buildoutArea.rect.x0 + && nodeZ < areaInfo.buildoutArea.rect.y1 + && nodeZ + 100 > areaInfo.buildoutArea.rect.y0) { if (!areaInfo.loaded) loadArea(areaInfo); @@ -168,7 +164,7 @@ void ServerBuildoutManager::onChunkComplete(int nodeX, int nodeZ) void ServerBuildoutManager::saveArea(std::string const &serverFileName, std::string const &clientFileName, float x1, float z1, float x2, float z2) { - FATAL( true, ( "ServerBuildoutManager::saveArea\n" ) ); + FATAL(true, ("ServerBuildoutManager::saveArea\n")); if (!ConfigServerGame::getBuildoutAreaEditingEnabled()) { @@ -214,12 +210,12 @@ void ServerBuildoutManager::saveArea(std::string const &serverFileName, std::str { ConstCharCrcString const &serverTemplateName = ObjectTemplateList::lookUp((*i).serverTemplateCrc); char buf[512]; - IGNORE_RETURN(snprintf(buf, sizeof(buf)-1, "%s\t%d\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t", + IGNORE_RETURN(snprintf(buf, sizeof(buf) - 1, "%s\t%d\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t", serverTemplateName.getString(), (*i).cellIndex, (*i).position.x, (*i).position.y, (*i).position.z, (*i).orientation.w, (*i).orientation.x, (*i).orientation.y, (*i).orientation.z)); - buf[sizeof(buf)-1] = '\0'; + buf[sizeof(buf) - 1] = '\0'; serverOutputFile.write(strlen(buf), buf); serverOutputFile.write((*i).scripts.length(), (*i).scripts.c_str()); serverOutputFile.write(1, "\t"); @@ -234,14 +230,14 @@ void ServerBuildoutManager::saveArea(std::string const &serverFileName, std::str { ConstCharCrcString const &sharedTemplateName = ObjectTemplateList::lookUp((*i).sharedTemplateCrc); char buf[512]; - IGNORE_RETURN(snprintf(buf, sizeof(buf)-1, "%s\t%d\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%d\n", + IGNORE_RETURN(snprintf(buf, sizeof(buf) - 1, "%s\t%d\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%d\n", sharedTemplateName.getString(), (*i).cellIndex, (*i).position.x, (*i).position.y, (*i).position.z, (*i).orientation.w, (*i).orientation.x, (*i).orientation.y, (*i).orientation.z, (*i).radius, static_cast((*i).portalLayoutCrc))); - buf[sizeof(buf)-1] = '\0'; + buf[sizeof(buf) - 1] = '\0'; clientOutputFile.write(strlen(buf), buf); } } @@ -262,14 +258,13 @@ void ServerBuildoutManager::clientSaveArea(Client &client, std::string const &ar std::vector clientRows; generateBuildoutData(x1, z1, x2, z2, serverRows, clientRows); - // pass them to the client GenericValueTypeMessage< std::pair< - std::pair, // scene, area - std::pair, std::vector > // serverRows, clientRows - > - > const message( + std::pair, // scene, area + std::pair, std::vector > // serverRows, clientRows + > + > const message( "GodClientSaveBuildoutArea", std::make_pair( std::make_pair(std::string(ConfigServerGame::getSceneID()), areaName), @@ -317,12 +312,12 @@ void ServerBuildoutManager::destroyPersistedDuplicates() for (std::vector::const_iterator k = objectsToTest.begin(); k != objectsToTest.end(); ++k) { ServerObject * const so = *k; - if ( so - && so->getNetworkId().getValue() != buildoutRow.m_id - && so->isPersisted() - && so->getTemplateCrc() == buildoutRow.m_serverTemplate->getCrcName().getCrc() - && so->getPosition_p().magnitudeBetweenSquared(buildoutRow.m_transform_p.getPosition_p()) < 0.005f - && ContainerInterface::getContainedByObject(*so) == container) + if (so + && so->getNetworkId().getValue() != buildoutRow.m_id + && so->isPersisted() + && so->getTemplateCrc() == buildoutRow.m_serverTemplate->getCrcName().getCrc() + && so->getPosition_p().magnitudeBetweenSquared(buildoutRow.m_transform_p.getPosition_p()) < 0.005f + && ContainerInterface::getContainedByObject(*so) == container) so->permanentlyDestroy(DeleteReasons::Replaced); } } @@ -377,12 +372,12 @@ void ServerBuildoutManagerNamespace::remove() void ServerBuildoutManagerNamespace::generateBuildoutData(float x1, float z1, float x2, float z2, std::vector &serverRows, std::vector &clientRows) { -// int objIdBase = -1; + // int objIdBase = -1; - typedef std::map ObjIdMap; + typedef std::map ObjIdMap; ObjIdMap objIdMap; - + std::vector objectsToSave; // build vector of objects we need to save, in the appropriate order @@ -408,9 +403,8 @@ void ServerBuildoutManagerNamespace::generateBuildoutData(float x1, float z1, fl { ServerObject const * const obj = *i; - // check for unexported gold data - if ( obj->getIncludeInBuildout() == false && obj->getNetworkId().getValue() < 10000000 ) + if (obj->getIncludeInBuildout() == false && obj->getNetworkId().getValue() < 10000000) { continue; } @@ -428,7 +422,6 @@ void ServerBuildoutManagerNamespace::generateBuildoutData(float x1, float z1, fl serverOnly = false; } - Quaternion const q(obj->getTransform_o2p()); Vector p(obj->getPosition_p()); int cellIndex = 0; @@ -461,30 +454,29 @@ void ServerBuildoutManagerNamespace::generateBuildoutData(float x1, float z1, fl serverRows.push_back(ServerBuildoutAreaRow()); ServerBuildoutAreaRow &serverRow = serverRows.back(); - serverRow.id = static_cast< int >( obj->getNetworkId().getValue() ); - serverRow.container = containingObject ? static_cast< int >( containingObject->getNetworkId().getValue() ) : 0; + serverRow.id = static_cast(obj->getNetworkId().getValue()); + serverRow.container = containingObject ? static_cast(containingObject->getNetworkId().getValue()) : 0; serverRow.serverTemplateCrc = obj->getTemplateCrc(); - serverRow.cellIndex = cellIndex; - serverRow.position = p; - serverRow.orientation = q; - serverRow.scripts = packedScriptList; - serverRow.objvars = obj->getPackedObjVars(std::string()); + serverRow.cellIndex = cellIndex; + serverRow.position = p; + serverRow.orientation = q; + serverRow.scripts = packedScriptList; + serverRow.objvars = obj->getPackedObjVars(std::string()); - - if ( serverRow.id >= 10000000 ) + if (serverRow.id >= 10000000) { serverRow.id = Random::random() | 0x80000000; // generate a negative random number. - objIdMap[ obj->getNetworkId().getValue() ] = serverRow.id; + objIdMap[obj->getNetworkId().getValue()] = serverRow.id; } else { serverRow.id &= cs_dataBitStripMask; // strip data bits } - if ( serverRow.container >= 10000000 ) + if (serverRow.container >= 10000000) { - ObjIdMap::const_iterator it = objIdMap.find( serverRow.container ); - FATAL( it == objIdMap.end(), ( "Unable to find the container relative objid for object %d\n", serverRow.id ) ); + ObjIdMap::const_iterator it = objIdMap.find(serverRow.container); + FATAL(it == objIdMap.end(), ("Unable to find the container relative objid for object %d\n", serverRow.id)); serverRow.container = it->second; } else @@ -497,17 +489,17 @@ void ServerBuildoutManagerNamespace::generateBuildoutData(float x1, float z1, fl clientRows.push_back(ClientBuildoutAreaRow()); ClientBuildoutAreaRow &clientRow = clientRows.back(); - clientRow.id = serverRow.id; - clientRow.container = serverRow.container; - clientRow.type = serverTemplate ? serverTemplate->getId() : 0; + clientRow.id = serverRow.id; + clientRow.container = serverRow.container; + clientRow.type = serverTemplate ? serverTemplate->getId() : 0; clientRow.sharedTemplateCrc = ConstCharCrcString(obj->getSharedTemplateName()).getCrc(); - clientRow.cellIndex = cellIndex; - clientRow.position = p; - clientRow.orientation = q; - clientRow.radius = serverTemplate->getUpdateRanges(ServerObjectTemplate::UR_far); + clientRow.cellIndex = cellIndex; + clientRow.position = p; + clientRow.orientation = q; + clientRow.radius = serverTemplate->getUpdateRanges(ServerObjectTemplate::UR_far); int portalLayoutCrc = 0; obj->getObjVars().getItem("portalProperty.crc", portalLayoutCrc); - clientRow.portalLayoutCrc = static_cast(portalLayoutCrc); + clientRow.portalLayoutCrc = static_cast(portalLayoutCrc); } } } @@ -549,49 +541,50 @@ void ServerBuildoutManagerNamespace::buildObjectsToSave(std::vector(ContainerInterface::getContainedByObject(*obj)); - - // make sure that cells that should be included in the buildout have all their - // children included too! - if ( obj->getObjectTemplate()->getId() == ServerCellObjectTemplate::ServerCellObjectTemplate_tag && containingObject && containingObject->getIncludeInBuildout() ) + if (obj) { - ServerObject *tmpObj = const_cast< ServerObject * >( obj ); - tmpObj->setIncludeInBuildout( true ); - } + const ServerObject * const containingObject = safe_cast(ContainerInterface::getContainedByObject(*obj)); - if ( !obj || !obj->isInWorld() || (!obj->isPersisted() && !obj->getIncludeInBuildout() ) || obj->isPlayerControlled() ) - { - return true; - } + // make sure that cells that should be included in the buildout have all their + // children included too! + if (obj->getObjectTemplate()->getId() == ServerCellObjectTemplate::ServerCellObjectTemplate_tag && containingObject && containingObject->getIncludeInBuildout()) + { + ServerObject *tmpObj = const_cast(obj); + tmpObj->setIncludeInBuildout(true); + } + if (!obj || !obj->isInWorld() || (!obj->isPersisted() && !obj->getIncludeInBuildout()) || obj->isPlayerControlled()) + { + return true; + } + } return false; - } // ---------------------------------------------------------------------- void ServerBuildoutManagerNamespace::loadArea(AreaInfo &areaInfo) { - int64 buildingObjId = areaInfo.buildoutArea.getSharedBaseId(); - int64 objIdBase = buildingObjId + cs_buildingObjIdOffset; - int64 currentBuilding = 0; - int64 currentCell = 0; + int64 buildingObjId = areaInfo.buildoutArea.getSharedBaseId(); + int64 objIdBase = buildingObjId + cs_buildingObjIdOffset; + int64 currentBuilding = 0; + int64 currentCell = 0; - int serverIdBase = areaInfo.buildoutArea.getServerBaseId(); + int serverIdBase = areaInfo.buildoutArea.getServerBaseId(); const bool isBuildoutEditingEnabled = ConfigServerGame::getBuildoutAreaEditingEnabled(); - UNREF( isBuildoutEditingEnabled ); + UNREF(isBuildoutEditingEnabled); char filename[256]; - snprintf(filename, sizeof(filename)-1, "datatables/buildout/%s/%s.iff", ConfigServerGame::getSceneID(), areaInfo.buildoutArea.areaName.c_str()); - filename[sizeof(filename)-1] = '\0'; + snprintf(filename, sizeof(filename) - 1, "datatables/buildout/%s/%s.iff", ConfigServerGame::getSceneID(), areaInfo.buildoutArea.areaName.c_str()); + filename[sizeof(filename) - 1] = '\0'; std::string const & eventRequired = areaInfo.buildoutArea.getRequiredEventName(); - if(!eventRequired.empty()) + if (!eventRequired.empty()) { ServerEventMap::iterator iter = s_eventObjects.find(eventRequired); - if(iter != s_eventObjects.end()) + if (iter != s_eventObjects.end()) { // Nothing to do here. We've already setup a list for this event. //eventObjList = &(*iter).second; @@ -600,11 +593,10 @@ void ServerBuildoutManagerNamespace::loadArea(AreaInfo &areaInfo) { s_eventObjects.insert(std::pair >(eventRequired, std::list())); } - } Iff iff; - if (!areaInfo.buildoutArea.areaName.empty() && iff.open(filename, true) && !iff.atEndOfForm() ) + if (!areaInfo.buildoutArea.areaName.empty() && iff.open(filename, true) && !iff.atEndOfForm()) { DataTable areaBuildoutTable; areaBuildoutTable.load(iff); @@ -614,19 +606,19 @@ void ServerBuildoutManagerNamespace::loadArea(AreaInfo &areaInfo) { areaInfo.buildoutRows.reserve(buildoutRowCount); - int const objIdColumn = areaBuildoutTable.findColumnNumber( "objid" ); - int const containerColumn = areaBuildoutTable.findColumnNumber( "container" ); + int const objIdColumn = areaBuildoutTable.findColumnNumber("objid"); + int const containerColumn = areaBuildoutTable.findColumnNumber("container"); int const serverTemplateCrcColumn = areaBuildoutTable.findColumnNumber("server_template_crc"); - int const cellIndexColumn = areaBuildoutTable.findColumnNumber("cell_index"); - int const pxColumn = areaBuildoutTable.findColumnNumber("px"); - int const pyColumn = areaBuildoutTable.findColumnNumber("py"); - int const pzColumn = areaBuildoutTable.findColumnNumber("pz"); - int const qwColumn = areaBuildoutTable.findColumnNumber("qw"); - int const qxColumn = areaBuildoutTable.findColumnNumber("qx"); - int const qyColumn = areaBuildoutTable.findColumnNumber("qy"); - int const qzColumn = areaBuildoutTable.findColumnNumber("qz"); - int const scriptsColumn = areaBuildoutTable.findColumnNumber("scripts"); - int const objvarsColumn = areaBuildoutTable.findColumnNumber("objvars"); + int const cellIndexColumn = areaBuildoutTable.findColumnNumber("cell_index"); + int const pxColumn = areaBuildoutTable.findColumnNumber("px"); + int const pyColumn = areaBuildoutTable.findColumnNumber("py"); + int const pzColumn = areaBuildoutTable.findColumnNumber("pz"); + int const qwColumn = areaBuildoutTable.findColumnNumber("qw"); + int const qxColumn = areaBuildoutTable.findColumnNumber("qx"); + int const qyColumn = areaBuildoutTable.findColumnNumber("qy"); + int const qzColumn = areaBuildoutTable.findColumnNumber("qz"); + int const scriptsColumn = areaBuildoutTable.findColumnNumber("scripts"); + int const objvarsColumn = areaBuildoutTable.findColumnNumber("objvars"); FATAL(serverTemplateCrcColumn < 0, ("Unable to find serverTemplateCrcColumn in [%s]", filename)); FATAL(cellIndexColumn < 0, ("Unable to find cellIndexColumn in [%s]", filename)); @@ -642,20 +634,18 @@ void ServerBuildoutManagerNamespace::loadArea(AreaInfo &areaInfo) int buildOutFileVersion = 1; - if ( objIdColumn != -1 ) + if (objIdColumn != -1) { buildOutFileVersion = 2; } - + std::set< int64 > objects; for (int buildoutRow = 0; buildoutRow < buildoutRowCount; ++buildoutRow) { - - int64 objId = 0; + int64 objId = 0; int64 containerId = 0; - uint32 const serverTemplateCrc = static_cast(areaBuildoutTable.getIntValue(serverTemplateCrcColumn, buildoutRow)); unsigned int const cellIndex = areaBuildoutTable.getIntValue(cellIndexColumn, buildoutRow); @@ -673,7 +663,7 @@ void ServerBuildoutManagerNamespace::loadArea(AreaInfo &areaInfo) FATAL(!sharedTemplate, ("Bad shared template [%s] for [%s] in buildout table %s, row %d (line %d)", sharedTemplateName.c_str(), serverTemplateBase->getName(), areaInfo.buildoutArea.areaName.c_str(), buildoutRow, buildoutRow + 3)); bool const isPob = !sharedTemplate->getPortalLayoutFilename().empty(); sharedTemplateBase->releaseReference(); - + bool serverOnly = false; if (!isPob && dynamic_cast(serverTemplate)) { @@ -684,26 +674,25 @@ void ServerBuildoutManagerNamespace::loadArea(AreaInfo &areaInfo) serverOnly = false; } - - if ( buildOutFileVersion == 1 ) + if (buildOutFileVersion == 1) { - if ( isPob ) // if ( is a building ) + if (isPob) // if ( is a building ) { objId = buildingObjId++; currentBuilding = objId; } - else if ( serverTemplate->getId() == ServerCellObjectTemplate::ServerCellObjectTemplate_tag ) // if ( is a cell ) + else if (serverTemplate->getId() == ServerCellObjectTemplate::ServerCellObjectTemplate_tag) // if ( is a cell ) { objId = buildingObjId++; currentCell = objId; containerId = currentBuilding; } - else if ( cellIndex > 0 ) // if ( is an object in a cell ) + else if (cellIndex > 0) // if ( is an object in a cell ) { objId = objIdBase++; containerId = currentCell; } - else if ( serverOnly ) + else if (serverOnly) { objId = serverIdBase++; } @@ -712,34 +701,32 @@ void ServerBuildoutManagerNamespace::loadArea(AreaInfo &areaInfo) objId = objIdBase++; } - FATAL( buildingObjId >= areaInfo.buildoutArea.getSharedBaseId() + cs_buildingObjIdOffset, ( "building object id overflow" ) ); + FATAL(buildingObjId >= areaInfo.buildoutArea.getSharedBaseId() + cs_buildingObjIdOffset, ("building object id overflow")); } else { - objId = areaBuildoutTable.getIntValue(objIdColumn, buildoutRow); + objId = areaBuildoutTable.getIntValue(objIdColumn, buildoutRow); containerId = areaBuildoutTable.getIntValue(containerColumn, buildoutRow); - + // with new buildout files, the object id is a random 31-bit negative value // then we give the area index some bits in the upper part of the number // by shifting the area index value left 48 bits. const int64 areaIndex = areaInfo.buildoutArea.areaIndex + 1; - if ( objId < 0 ) + if (objId < 0) { - objId ^= areaIndex << 48; } - if ( containerId < 0 ) + if (containerId < 0) { containerId ^= areaIndex << 48; } - } - FATAL( isPob && ( cellIndex != 0 || containerId != 0 ), ( "tried to add a pob to a cell or other container. %s (objId=%d cellIndex=%d containerId=%d)", - serverTemplateBase->getName(), objId, cellIndex,containerId ) ); + FATAL(isPob && (cellIndex != 0 || containerId != 0), ("tried to add a pob to a cell or other container. %s (objId=%d cellIndex=%d containerId=%d)", + serverTemplateBase->getName(), objId, cellIndex, containerId)); Quaternion const q( areaBuildoutTable.getFloatValue(qwColumn, buildoutRow), @@ -751,7 +738,7 @@ void ServerBuildoutManagerNamespace::loadArea(AreaInfo &areaInfo) q.getTransform(&transform_p); - if ( cellIndex == 0 ) + if (cellIndex == 0) { transform_p.setPosition_p( areaBuildoutTable.getFloatValue(pxColumn, buildoutRow) + areaInfo.buildoutArea.rect.x0, @@ -766,7 +753,7 @@ void ServerBuildoutManagerNamespace::loadArea(AreaInfo &areaInfo) areaBuildoutTable.getFloatValue(pzColumn, buildoutRow)); } - if ( containerId == 0 || objects.find ( containerId ) != objects.end() ) + if (containerId == 0 || objects.find(containerId) != objects.end()) { areaInfo.buildoutRows.push_back( BuildoutRow( @@ -780,7 +767,7 @@ void ServerBuildoutManagerNamespace::loadArea(AreaInfo &areaInfo) eventRequired)); } - objects.insert( objId ); + objects.insert(objId); serverTemplateBase->releaseReference(); } @@ -810,13 +797,12 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf UNREF(nodeZ); UNREF(nodeX); - std::vector newObjects; int buildingId = 0; int cellIndex = 0; UNREF(cellIndex); - UNREF( buildingId ); + UNREF(buildingId); NetworkId controllerObjectId; @@ -824,8 +810,8 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf PlanetObject * const planetObject = ServerUniverse::getInstance().getTatooinePlanet(); std::vector events; - - if(planetObject) + + if (planetObject) planetObject->parseCurrentEventsList(events); for (std::vector::const_iterator rowIter = areaInfo.buildoutRows.begin(); rowIter != areaInfo.buildoutRows.end(); ++rowIter) @@ -836,7 +822,7 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf int64 const containerId = buildoutRow.m_containerId; - if ( containerId && discardContainedObjects ) + if (containerId && discardContainedObjects) { continue; } @@ -860,21 +846,21 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf } // reject object if it is out of bounds and is not the controller - if ( !containerId && objectId != controllerObjectId ) + if (!containerId && objectId != controllerObjectId) { const Vector &position_w = buildoutRow.m_transform_p.getPosition_p(); - if ( position_w.x < nodeX || position_w.x >= nodeX+100 || position_w.z < nodeZ || position_w.z >= nodeZ+100 ) + if (position_w.x < nodeX || position_w.x >= nodeX + 100 || position_w.z < nodeZ || position_w.z >= nodeZ + 100) { discardContainedObjects = true; continue; } } - if(!buildoutRow.m_eventRequired.empty()) + if (!buildoutRow.m_eventRequired.empty()) { ServerEventMap::iterator searchIter = s_eventObjects.find(buildoutRow.m_eventRequired); - if(searchIter != s_eventObjects.end()) + if (searchIter != s_eventObjects.end()) { ServerEventAreaInfo newEventObj(&buildoutRow, nullptr); (*searchIter).second.push_back(newEventObj); @@ -883,28 +869,27 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf { DEBUG_REPORT_LOG(true, ("ServerBuildoutManager: Tried to load an unknown event object. Event name: %s\n", buildoutRow.m_eventRequired.c_str())); } - - if(planetObject) // We have a valid Tatooine Planet Object which keeps track of our universe wide events. + + if (planetObject) // We have a valid Tatooine Planet Object which keeps track of our universe wide events. { bool eventCurrentlyRunning = false; - + std::vector::size_type i = 0; - for(; i < events.size(); ++i) + for (; i < events.size(); ++i) { - if(events[i] == buildoutRow.m_eventRequired) // Is our required event already running? + if (events[i] == buildoutRow.m_eventRequired) // Is our required event already running? eventCurrentlyRunning = true; } - if(!eventCurrentlyRunning) + if (!eventCurrentlyRunning) continue; // We found an event object but their event isn't started yet. Hold off on Object creation. } else continue; // No planet object. This should NEVER happen. Better hold off on any event object creation for now. - } - + ServerObject * const containingObject = containerId ? safe_cast(NetworkIdManager::getObjectById(NetworkId(static_cast(containerId)))) : 0; - FATAL(containerId && !containingObject, ("could not find containing object obj=%d container=%d", (int)objectId.getValue(), containerId )); + FATAL(containerId && !containingObject, ("could not find containing object obj=%d container=%d", (int)objectId.getValue(), containerId)); //-- object has already been created //-- this must be the controller object or one of its contents. @@ -921,7 +906,7 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf if (newCellObject) { - newCellObject->setCell( buildoutRow.m_cellIndex ); + newCellObject->setCell(buildoutRow.m_cellIndex); } if (!newObject->getController()) @@ -940,15 +925,15 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf // to client-cache any objects otherwise we will not be able to // move them around or delete them, etc. // - + const bool isEditing = ConfigServerGame::getBuildoutAreaEditingEnabled(); - - if ( isEditing == false ) + + if (isEditing == false) { // // cells and their parents should NOT BE CLIENT CACHED // - if ( newObject->asCellObject() ) + if (newObject->asCellObject()) { // by the time we get here the cache version on the POB has // already been set to non-zero, so we need to reset it back @@ -970,12 +955,12 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf // them in god mode!!! // const int vfCount = buildoutRow.m_serverTemplate->getVisibleFlagsCount(); - - for ( int index = 0; index < vfCount ; ++index ) + + for (int index = 0; index < vfCount; ++index) { - const ServerObjectTemplate::VisibleFlags vf = buildoutRow.m_serverTemplate->getVisibleFlags( index ); - - if ( vf == ServerObjectTemplate::VF_player && buildoutRow.m_eventRequired.empty()) // Event objects can never be client cached currently. + const ServerObjectTemplate::VisibleFlags vf = buildoutRow.m_serverTemplate->getVisibleFlags(index); + + if (vf == ServerObjectTemplate::VF_player && buildoutRow.m_eventRequired.empty()) // Event objects can never be client cached currently. { newObject->setCacheVersion(s_buildoutCacheVersion); break; @@ -983,8 +968,7 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf } } } - - + if (buildoutRow.m_transform_p != Transform::identity) { newObject->setTransform_o2p(buildoutRow.m_transform_p); @@ -1005,7 +989,7 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf { newObject->setPackedObjVars(buildoutRow.m_objvars); } - + int const count = buildoutRow.m_serverTemplate->getScriptsCount(); for (int j = 0; j < count; ++j) @@ -1027,7 +1011,7 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf while (scripts[pos] && scripts[pos] != ':') ++pos; - std::string const & scriptName = scripts.substr(oldPos, pos-oldPos); + std::string const & scriptName = scripts.substr(oldPos, pos - oldPos); if (!gso->hasScript(scriptName)) IGNORE_RETURN(gso->attachScript(scriptName, false)); @@ -1038,10 +1022,10 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf } newObjects.push_back(newObject); - if(!buildoutRow.m_eventRequired.empty()) + if (!buildoutRow.m_eventRequired.empty()) { ServerEventMap::iterator searchIter = s_eventObjects.find(buildoutRow.m_eventRequired); - if(searchIter != s_eventObjects.end()) + if (searchIter != s_eventObjects.end()) { ServerEventAreaInfo & newEventObj = (*searchIter).second.back(); newEventObj.loadedObject = newObject; @@ -1058,7 +1042,7 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf } // run through newly instantiated objects and notify the controller object - if ( controllerObjectId.isValid() ) + if (controllerObjectId.isValid()) { ServerObject * const controllerObject = safe_cast(NetworkIdManager::getObjectById(controllerObjectId)); if (nullptr != controllerObject) @@ -1070,12 +1054,12 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf ServerObject * const obj = *it; if (obj == controllerObject) continue; - + int registerWithController = 0; if (obj->getObjVars().getItem("registerWithController", registerWithController)) { if (registerWithController) - { + { if (nullptr != script) { ScriptParams p; @@ -1090,36 +1074,33 @@ void ServerBuildoutManagerNamespace::instantiateAreaNode(AreaInfo const &areaInf // initialize any theaters { - for (std::vector::reverse_iterator it = newObjects.rbegin(); it != newObjects.rend(); ++it) { ServerObject *obj = *it; - if ( obj && obj->isAuthoritative() ) + if (obj && obj->isAuthoritative()) { GameScriptObject *scripts = obj->getScriptObject(); - - if ( scripts ) //&& scripts->hasScript( "poi.template.scene.base.base_theater" ) ) + + if (scripts) //&& scripts->hasScript( "poi.template.scene.base.base_theater" ) ) { - scripts->handleMessage( "startTheaterFromBuildout", std::vector() ); + scripts->handleMessage("startTheaterFromBuildout", std::vector()); } - } } } - } // ---------------------------------------------------------------------- ServerBuildoutManagerNamespace::BuildoutRow::BuildoutRow() : -m_id(0), -m_containerId(0), -m_transform_p(), -m_serverTemplate(0), -m_scripts(), -m_objvars(), -m_cellIndex(0) + m_id(0), + m_containerId(0), + m_transform_p(), + m_serverTemplate(0), + m_scripts(), + m_objvars(), + m_cellIndex(0) { } @@ -1190,12 +1171,12 @@ ServerBuildoutManagerNamespace::BuildoutRow &ServerBuildoutManagerNamespace::Bui void ServerBuildoutManager::onEventStarted(std::string const & eventName) { - if(s_eventObjects.empty()) + if (s_eventObjects.empty()) return; ServerEventMap::iterator iter = s_eventObjects.find(eventName); - - if(iter == s_eventObjects.end()) + + if (iter == s_eventObjects.end()) return; // Perhaps we should print a warning here? Would we ever have an event with no server side event objects? std::list< ServerEventAreaInfo >* eventList = &(*iter).second; @@ -1204,7 +1185,7 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) NetworkId controllerObjectId; std::list< ServerEventAreaInfo >::iterator objIter = eventList->begin(); - for(; objIter != eventList->end(); ++objIter) + for (; objIter != eventList->end(); ++objIter) { // Object Creation @@ -1232,7 +1213,7 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) } ServerObject * const containingObject = containerId ? safe_cast(NetworkIdManager::getObjectById(NetworkId(static_cast(containerId)))) : 0; - FATAL(containerId && !containingObject, ("could not find containing object obj=%d container=%d", (int)objectId.getValue(), containerId )); + FATAL(containerId && !containingObject, ("could not find containing object obj=%d container=%d", (int)objectId.getValue(), containerId)); //-- object has already been created //-- this must be the controller object or one of its contents. @@ -1242,9 +1223,9 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) ServerObject * const newObject = safe_cast(buildoutRow.m_serverTemplate->createObject()); FATAL(!newObject, ("could not create buildout object")); - LOGC(ConfigServerGame::getLogEventObjectCreation(),"EventBuildout", ("Loading Object for Event [%s].\nTemplate Name[%s]\nNetwork ID[%s]\nCell[%d]\nPosition[%-4.3f %-4.3f %-4.3f]\n\n", - eventName.c_str(), buildoutRow.m_serverTemplate->getName(), objectId.getValueString().c_str(),buildoutRow.m_cellIndex, - buildoutRow.m_transform_p.getPosition_p().x, buildoutRow.m_transform_p.getPosition_p().y, buildoutRow.m_transform_p.getPosition_p().z)); + LOGC(ConfigServerGame::getLogEventObjectCreation(), "EventBuildout", ("Loading Object for Event [%s].\nTemplate Name[%s]\nNetwork ID[%s]\nCell[%d]\nPosition[%-4.3f %-4.3f %-4.3f]\n\n", + eventName.c_str(), buildoutRow.m_serverTemplate->getName(), objectId.getValueString().c_str(), buildoutRow.m_cellIndex, + buildoutRow.m_transform_p.getPosition_p().x, buildoutRow.m_transform_p.getPosition_p().y, buildoutRow.m_transform_p.getPosition_p().z)); newObject->setNetworkId(objectId); newObject->setIncludeInBuildout(true); @@ -1253,7 +1234,7 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) if (newCellObject) { - newCellObject->setCell( buildoutRow.m_cellIndex ); + newCellObject->setCell(buildoutRow.m_cellIndex); } if (!newObject->getController()) @@ -1275,12 +1256,12 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) const bool isEditing = ConfigServerGame::getBuildoutAreaEditingEnabled(); - if ( isEditing == false ) + if (isEditing == false) { // // cells and their parents should NOT BE CLIENT CACHED // - if ( newObject->asCellObject() ) + if (newObject->asCellObject()) { // by the time we get here the cache version on the POB has // already been set to non-zero, so we need to reset it back @@ -1303,11 +1284,11 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) // const int vfCount = buildoutRow.m_serverTemplate->getVisibleFlagsCount(); - for ( int index = 0; index < vfCount ; ++index ) + for (int index = 0; index < vfCount; ++index) { - const ServerObjectTemplate::VisibleFlags vf = buildoutRow.m_serverTemplate->getVisibleFlags( index ); + const ServerObjectTemplate::VisibleFlags vf = buildoutRow.m_serverTemplate->getVisibleFlags(index); - if ( vf == ServerObjectTemplate::VF_player ) + if (vf == ServerObjectTemplate::VF_player) { // Removing this code temporarily since we don't have a proper way to do client side, cached event build out objects. // All event objects are objects that are streamed down from the server. Until we have a way for the client to know @@ -1320,7 +1301,6 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) } } - if (buildoutRow.m_transform_p != Transform::identity) { newObject->setTransform_o2p(buildoutRow.m_transform_p); @@ -1363,7 +1343,7 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) while (scripts[pos] && scripts[pos] != ':') ++pos; - std::string const & scriptName = scripts.substr(oldPos, pos-oldPos); + std::string const & scriptName = scripts.substr(oldPos, pos - oldPos); if (!gso->hasScript(scriptName)) IGNORE_RETURN(gso->attachScript(scriptName, false)); @@ -1373,12 +1353,11 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) } } - (*objIter).loadedObject = newObject; + (*objIter).loadedObject = newObject; newObjects.push_back(newObject); } - // run through newly instantiated objects and initialize them { for (std::vector::reverse_iterator it = newObjects.rbegin(); it != newObjects.rend(); ++it) @@ -1388,7 +1367,7 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) } // run through newly instantiated objects and notify the controller object - if ( controllerObjectId.isValid() ) + if (controllerObjectId.isValid()) { ServerObject * const controllerObject = safe_cast(NetworkIdManager::getObjectById(controllerObjectId)); if (nullptr != controllerObject) @@ -1405,7 +1384,7 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) if (obj->getObjVars().getItem("registerWithController", registerWithController)) { if (registerWithController) - { + { if (nullptr != script) { ScriptParams p; @@ -1420,20 +1399,18 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) // initialize any theaters { - for (std::vector::reverse_iterator it = newObjects.rbegin(); it != newObjects.rend(); ++it) { ServerObject *obj = *it; - if ( obj && obj->isAuthoritative() ) + if (obj && obj->isAuthoritative()) { GameScriptObject *scripts = obj->getScriptObject(); - if ( scripts ) //&& scripts->hasScript( "poi.template.scene.base.base_theater" ) ) + if (scripts) //&& scripts->hasScript( "poi.template.scene.base.base_theater" ) ) { - scripts->handleMessage( "startTheaterFromBuildout", std::vector() ); + scripts->handleMessage("startTheaterFromBuildout", std::vector()); } - } } } @@ -1443,33 +1420,32 @@ void ServerBuildoutManager::onEventStarted(std::string const & eventName) void ServerBuildoutManager::onEventStopped(std::string const & eventName) { - if(s_eventObjects.empty()) + if (s_eventObjects.empty()) return; ServerEventMap::iterator iter = s_eventObjects.find(eventName); - if(iter == s_eventObjects.end()) + if (iter == s_eventObjects.end()) return; // We stopped an event with no objects? Warning? std::list< ServerEventAreaInfo >* eventList = &(*iter).second; std::list< ServerEventAreaInfo >::iterator objIter = eventList->begin(); - for(; objIter != eventList->end(); ++objIter) + for (; objIter != eventList->end(); ++objIter) { // Object clean up. - if((*objIter).loadedObject) + if ((*objIter).loadedObject) { ServerObject* object = (*objIter).loadedObject; - + LOGC(ConfigServerGame::getLogEventObjectDestruction(), "EventBuildout", ("Unloading Object for Event [%s].\nTemplate Name[%s]\nNetwork ID[%s]\nPosition[%-4.3f %-4.3f %-4.3f]\n\n", eventName.c_str(), object->getTemplateName(), object->getNetworkId().getValueString().c_str(), object->getTransform_o2p().getPosition_p().x, object->getTransform_o2p().getPosition_p().y, object->getTransform_o2p().getPosition_p().z)); - + object->unload(); - + (*objIter).loadedObject = nullptr; } } } -// ====================================================================== - +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/object/LineOfSightCache.cpp b/engine/server/library/serverGame/src/shared/object/LineOfSightCache.cpp index 3d3c72ff..d68143f2 100755 --- a/engine/server/library/serverGame/src/shared/object/LineOfSightCache.cpp +++ b/engine/server/library/serverGame/src/shared/object/LineOfSightCache.cpp @@ -56,7 +56,7 @@ void LineOfSightCache::update() while (!s_lineOfSightCacheExpireQueue.empty()) { LineOfSightCacheExpireQueueEntry const &entry = s_lineOfSightCacheExpireQueue.front(); - if (static_cast(entry.second-frameStartTime) > 0) + if (static_cast(entry.second - frameStartTime) > 0) break; IGNORE_RETURN(s_lineOfSightCacheMap.erase(entry.first)); s_lineOfSightCacheExpireQueue.pop(); @@ -64,7 +64,7 @@ void LineOfSightCache::update() while (!s_lineOfSightLocationCacheExpireQueue.empty()) { LineOfSightLocationCacheExpireQueueEntry const &entry = s_lineOfSightLocationCacheExpireQueue.front(); - if (static_cast(entry.second-frameStartTime) > 0) + if (static_cast(entry.second - frameStartTime) > 0) break; IGNORE_RETURN(s_lineOfSightLocationCacheMap.erase(entry.first)); s_lineOfSightLocationCacheExpireQueue.pop(); @@ -435,5 +435,4 @@ bool LineOfSightCache::checkLOS(Object const &a, Location const &b) return (*result.first).second; } -// ====================================================================== - +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerArmorTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerArmorTemplate.cpp index e5cac8d4..2e644ad9 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerArmorTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerArmorTemplate.cpp @@ -23,22 +23,22 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerArmorTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerArmorTemplate::ServerArmorTemplate(const std::string & filename) //@BEGIN TFD INIT : ObjectTemplate(filename) - ,m_specialProtectionLoaded(false) - ,m_specialProtectionAppend(false) - ,m_versionOk(true) -//@END TFD INIT + , m_specialProtectionLoaded(false) + , m_specialProtectionAppend(false) + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerArmorTemplate::ServerArmorTemplate @@ -47,7 +47,7 @@ ServerArmorTemplate::ServerArmorTemplate(const std::string & filename) */ ServerArmorTemplate::~ServerArmorTemplate() { -//@BEGIN TFD CLEANUP + //@BEGIN TFD CLEANUP { std::vector::iterator iter; for (iter = m_specialProtection.begin(); iter != m_specialProtection.end(); ++iter) @@ -57,7 +57,7 @@ ServerArmorTemplate::~ServerArmorTemplate() } m_specialProtection.clear(); } -//@END TFD CLEANUP + //@END TFD CLEANUP } // ServerArmorTemplate::~ServerArmorTemplate /** @@ -116,8 +116,6 @@ Tag ServerArmorTemplate::getHighestTemplateVersion(void) const //@BEGIN TFD ServerArmorTemplate::ArmorRating ServerArmorTemplate::getRating() const { - - const ServerArmorTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -145,8 +143,6 @@ ServerArmorTemplate::ArmorRating ServerArmorTemplate::getRating() const int ServerArmorTemplate::getIntegrity() const { - - const ServerArmorTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -196,8 +192,6 @@ int ServerArmorTemplate::getIntegrity() const int ServerArmorTemplate::getIntegrityMin() const { - - const ServerArmorTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -247,8 +241,6 @@ int ServerArmorTemplate::getIntegrityMin() const int ServerArmorTemplate::getIntegrityMax() const { - - const ServerArmorTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -298,8 +290,6 @@ int ServerArmorTemplate::getIntegrityMax() const int ServerArmorTemplate::getEffectiveness() const { - - const ServerArmorTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -349,8 +339,6 @@ int ServerArmorTemplate::getEffectiveness() const int ServerArmorTemplate::getEffectivenessMin() const { - - const ServerArmorTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -400,8 +388,6 @@ int ServerArmorTemplate::getEffectivenessMin() const int ServerArmorTemplate::getEffectivenessMax() const { - - const ServerArmorTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -462,7 +448,7 @@ void ServerArmorTemplate::getSpecialProtection(SpecialProtection &data, int inde if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter specialProtection in template %s", DataResource::getName())); - return ; + return; } else { @@ -476,10 +462,10 @@ void ServerArmorTemplate::getSpecialProtection(SpecialProtection &data, int inde { int baseCount = base->getSpecialProtectionCount(); if (index < baseCount) - { - base->getSpecialProtection(data, index); - return; - } + { + base->getSpecialProtection(data, index); + return; + } index -= baseCount; } @@ -505,7 +491,7 @@ void ServerArmorTemplate::getSpecialProtectionMin(SpecialProtection &data, int i if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter specialProtection in template %s", DataResource::getName())); - return ; + return; } else { @@ -519,10 +505,10 @@ void ServerArmorTemplate::getSpecialProtectionMin(SpecialProtection &data, int i { int baseCount = base->getSpecialProtectionCount(); if (index < baseCount) - { - base->getSpecialProtectionMin(data, index); - return; - } + { + base->getSpecialProtectionMin(data, index); + return; + } index -= baseCount; } @@ -548,7 +534,7 @@ void ServerArmorTemplate::getSpecialProtectionMax(SpecialProtection &data, int i if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter specialProtection in template %s", DataResource::getName())); - return ; + return; } else { @@ -562,10 +548,10 @@ void ServerArmorTemplate::getSpecialProtectionMax(SpecialProtection &data, int i { int baseCount = base->getSpecialProtectionCount(); if (index < baseCount) - { - base->getSpecialProtectionMax(data, index); - return; - } + { + base->getSpecialProtectionMax(data, index); + return; + } index -= baseCount; } @@ -604,8 +590,6 @@ size_t ServerArmorTemplate::getSpecialProtectionCount(void) const int ServerArmorTemplate::getVulnerability() const { - - const ServerArmorTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -655,8 +639,6 @@ int ServerArmorTemplate::getVulnerability() const int ServerArmorTemplate::getVulnerabilityMin() const { - - const ServerArmorTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -706,8 +688,6 @@ int ServerArmorTemplate::getVulnerabilityMin() const int ServerArmorTemplate::getVulnerabilityMax() const { - - const ServerArmorTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -902,7 +882,6 @@ int ServerArmorTemplate::getEncumbranceMax(int index) const return value; } // ServerArmorTemplate::getEncumbranceMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -911,8 +890,8 @@ int ServerArmorTemplate::getEncumbranceMax(int index) const */ void ServerArmorTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerArmorTemplate_tag) { @@ -921,7 +900,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -941,10 +920,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,1)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 1)) { - - m_versionOk = false; } @@ -1005,7 +982,6 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerArmorTemplate::load - //============================================================================= // class ServerArmorTemplate::_SpecialProtection @@ -1054,8 +1030,6 @@ Tag ServerArmorTemplate::_SpecialProtection::getId(void) const ServerArmorTemplate::DamageType ServerArmorTemplate::_SpecialProtection::getType(bool versionOk) const { - - const ServerArmorTemplate::_SpecialProtection * base = nullptr; if (m_baseData != nullptr) { @@ -1083,8 +1057,6 @@ ServerArmorTemplate::DamageType ServerArmorTemplate::_SpecialProtection::getType int ServerArmorTemplate::_SpecialProtection::getEffectiveness(bool versionOk) const { - - const ServerArmorTemplate::_SpecialProtection * base = nullptr; if (m_baseData != nullptr) { @@ -1134,8 +1106,6 @@ int ServerArmorTemplate::_SpecialProtection::getEffectiveness(bool versionOk) co int ServerArmorTemplate::_SpecialProtection::getEffectivenessMin(bool versionOk) const { - - const ServerArmorTemplate::_SpecialProtection * base = nullptr; if (m_baseData != nullptr) { @@ -1185,8 +1155,6 @@ int ServerArmorTemplate::_SpecialProtection::getEffectivenessMin(bool versionOk) int ServerArmorTemplate::_SpecialProtection::getEffectivenessMax(bool versionOk) const { - - const ServerArmorTemplate::_SpecialProtection * base = nullptr; if (m_baseData != nullptr) { @@ -1234,7 +1202,6 @@ int ServerArmorTemplate::_SpecialProtection::getEffectivenessMax(bool versionOk) return value; } // ServerArmorTemplate::_SpecialProtection::getEffectivenessMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -1243,8 +1210,8 @@ int ServerArmorTemplate::_SpecialProtection::getEffectivenessMax(bool versionOk) */ void ServerArmorTemplate::_SpecialProtection::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; file.enterForm(); @@ -1266,4 +1233,4 @@ char paramName[MAX_NAME_SIZE]; UNREF(file); } // ServerArmorTemplate::_SpecialProtection::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerBattlefieldMarkerObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerBattlefieldMarkerObjectTemplate.cpp index edd8194e..6560b6de 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerBattlefieldMarkerObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerBattlefieldMarkerObjectTemplate.cpp @@ -23,20 +23,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerBattlefieldMarkerObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerBattlefieldMarkerObjectTemplate::ServerBattlefieldMarkerObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerTangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerBattlefieldMarkerObjectTemplate::ServerBattlefieldMarkerObjectTemplate @@ -45,8 +45,8 @@ ServerBattlefieldMarkerObjectTemplate::ServerBattlefieldMarkerObjectTemplate(con */ ServerBattlefieldMarkerObjectTemplate::~ServerBattlefieldMarkerObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerBattlefieldMarkerObjectTemplate::~ServerBattlefieldMarkerObjectTemplate /** @@ -122,8 +122,8 @@ Object * ServerBattlefieldMarkerObjectTemplate::createObject(void) const */ void ServerBattlefieldMarkerObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerBattlefieldMarkerObjectTemplate_tag) { @@ -133,7 +133,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -153,10 +153,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -174,4 +172,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerBattlefieldMarkerObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerBuildingObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerBuildingObjectTemplate.cpp index 5fe4a003..df2091ee 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerBuildingObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerBuildingObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerBuildingObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerBuildingObjectTemplate::ServerBuildingObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerTangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerBuildingObjectTemplate::ServerBuildingObjectTemplate @@ -44,8 +44,8 @@ ServerBuildingObjectTemplate::ServerBuildingObjectTemplate(const std::string & f */ ServerBuildingObjectTemplate::~ServerBuildingObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerBuildingObjectTemplate::~ServerBuildingObjectTemplate /** @@ -114,8 +114,6 @@ Object * ServerBuildingObjectTemplate::createObject(void) const //@BEGIN TFD int ServerBuildingObjectTemplate::getMaintenanceCost() const { - - const ServerBuildingObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -165,8 +163,6 @@ int ServerBuildingObjectTemplate::getMaintenanceCost() const int ServerBuildingObjectTemplate::getMaintenanceCostMin() const { - - const ServerBuildingObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -216,8 +212,6 @@ int ServerBuildingObjectTemplate::getMaintenanceCostMin() const int ServerBuildingObjectTemplate::getMaintenanceCostMax() const { - - const ServerBuildingObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -267,8 +261,6 @@ int ServerBuildingObjectTemplate::getMaintenanceCostMax() const bool ServerBuildingObjectTemplate::getIsPublic() const { - - const ServerBuildingObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -294,7 +286,6 @@ bool ServerBuildingObjectTemplate::getIsPublic() const return value; } // ServerBuildingObjectTemplate::getIsPublic - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -303,8 +294,8 @@ bool ServerBuildingObjectTemplate::getIsPublic() const */ void ServerBuildingObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerBuildingObjectTemplate_tag) { @@ -314,7 +305,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -334,10 +325,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,1)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 1)) { - - m_versionOk = false; } @@ -363,4 +352,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerBuildingObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerCellObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerCellObjectTemplate.cpp index cd6cd28d..3690c159 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerCellObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerCellObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerCellObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerCellObjectTemplate::ServerCellObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerCellObjectTemplate::ServerCellObjectTemplate @@ -46,12 +46,12 @@ ServerCellObjectTemplate::~ServerCellObjectTemplate() { if (m_baseData) { - DEBUG_REPORT_LOG(true,("Released m_baseData.\n")); + DEBUG_REPORT_LOG(true, ("Released m_baseData.\n")); m_baseData->releaseReference(); - m_baseData=0; + m_baseData = 0; } -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerCellObjectTemplate::~ServerCellObjectTemplate /** @@ -127,8 +127,8 @@ Object * ServerCellObjectTemplate::createObject(void) const */ void ServerCellObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerCellObjectTemplate_tag) { @@ -138,7 +138,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -158,10 +158,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -179,4 +177,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerCellObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerCityObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerCityObjectTemplate.cpp index 82ba3562..6cf2743f 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerCityObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerCityObjectTemplate.cpp @@ -24,20 +24,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerCityObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerCityObjectTemplate::ServerCityObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerUniverseObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerCityObjectTemplate::ServerCityObjectTemplate @@ -46,8 +46,8 @@ ServerCityObjectTemplate::ServerCityObjectTemplate(const std::string & filename) */ ServerCityObjectTemplate::~ServerCityObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerCityObjectTemplate::~ServerCityObjectTemplate /** @@ -123,8 +123,8 @@ Object * ServerCityObjectTemplate::createObject(void) const */ void ServerCityObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerCityObjectTemplate_tag) { @@ -134,7 +134,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -154,10 +154,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -175,4 +173,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerCityObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerConstructionContractObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerConstructionContractObjectTemplate.cpp index 3d1d1fec..40fccb9d 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerConstructionContractObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerConstructionContractObjectTemplate.cpp @@ -23,20 +23,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerConstructionContractObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerConstructionContractObjectTemplate::ServerConstructionContractObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerIntangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerConstructionContractObjectTemplate::ServerConstructionContractObjectTemplate @@ -45,8 +45,8 @@ ServerConstructionContractObjectTemplate::ServerConstructionContractObjectTempla */ ServerConstructionContractObjectTemplate::~ServerConstructionContractObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerConstructionContractObjectTemplate::~ServerConstructionContractObjectTemplate /** @@ -112,8 +112,8 @@ Tag ServerConstructionContractObjectTemplate::getId(void) const */ void ServerConstructionContractObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerConstructionContractObjectTemplate_tag) { @@ -123,7 +123,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -143,10 +143,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -164,4 +162,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerConstructionContractObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerCreatureObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerCreatureObjectTemplate.cpp index c3d0f5b1..37e95c27 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerCreatureObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerCreatureObjectTemplate.cpp @@ -26,22 +26,22 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerCreatureObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerCreatureObjectTemplate::ServerCreatureObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerTangibleObjectTemplate(filename) - ,m_attribModsLoaded(false) - ,m_attribModsAppend(false) - ,m_versionOk(true) -//@END TFD INIT + , m_attribModsLoaded(false) + , m_attribModsAppend(false) + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerCreatureObjectTemplate::ServerCreatureObjectTemplate @@ -50,7 +50,7 @@ ServerCreatureObjectTemplate::ServerCreatureObjectTemplate(const std::string & f */ ServerCreatureObjectTemplate::~ServerCreatureObjectTemplate() { -//@BEGIN TFD CLEANUP + //@BEGIN TFD CLEANUP { std::vector::iterator iter; for (iter = m_attribMods.begin(); iter != m_attribMods.end(); ++iter) @@ -60,7 +60,7 @@ ServerCreatureObjectTemplate::~ServerCreatureObjectTemplate() } m_attribMods.clear(); } -//@END TFD CLEANUP + //@END TFD CLEANUP } // ServerCreatureObjectTemplate::~ServerCreatureObjectTemplate /** @@ -155,7 +155,7 @@ const ServerWeaponObjectTemplate * ServerCreatureObjectTemplate::getDefaultWeapo { returnValue = dynamic_cast(ObjectTemplateList::fetch(templateName)); if (returnValue == nullptr) - WARNING_STRICT_FATAL(true, ("Error loading template %s",templateName.c_str())); + WARNING_STRICT_FATAL(true, ("Error loading template %s", templateName.c_str())); } return returnValue; } // ServerCreatureObjectTemplate::getDefaultWeapon @@ -603,8 +603,6 @@ int ServerCreatureObjectTemplate::getMaxAttributesMax(Attributes index) const float ServerCreatureObjectTemplate::getMinDrainModifier() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -654,8 +652,6 @@ float ServerCreatureObjectTemplate::getMinDrainModifier() const float ServerCreatureObjectTemplate::getMinDrainModifierMin() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -705,8 +701,6 @@ float ServerCreatureObjectTemplate::getMinDrainModifierMin() const float ServerCreatureObjectTemplate::getMinDrainModifierMax() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -756,8 +750,6 @@ float ServerCreatureObjectTemplate::getMinDrainModifierMax() const float ServerCreatureObjectTemplate::getMaxDrainModifier() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -807,8 +799,6 @@ float ServerCreatureObjectTemplate::getMaxDrainModifier() const float ServerCreatureObjectTemplate::getMaxDrainModifierMin() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -858,8 +848,6 @@ float ServerCreatureObjectTemplate::getMaxDrainModifierMin() const float ServerCreatureObjectTemplate::getMaxDrainModifierMax() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -909,8 +897,6 @@ float ServerCreatureObjectTemplate::getMaxDrainModifierMax() const float ServerCreatureObjectTemplate::getMinFaucetModifier() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -960,8 +946,6 @@ float ServerCreatureObjectTemplate::getMinFaucetModifier() const float ServerCreatureObjectTemplate::getMinFaucetModifierMin() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1011,8 +995,6 @@ float ServerCreatureObjectTemplate::getMinFaucetModifierMin() const float ServerCreatureObjectTemplate::getMinFaucetModifierMax() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1062,8 +1044,6 @@ float ServerCreatureObjectTemplate::getMinFaucetModifierMax() const float ServerCreatureObjectTemplate::getMaxFaucetModifier() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1113,8 +1093,6 @@ float ServerCreatureObjectTemplate::getMaxFaucetModifier() const float ServerCreatureObjectTemplate::getMaxFaucetModifierMin() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1164,8 +1142,6 @@ float ServerCreatureObjectTemplate::getMaxFaucetModifierMin() const float ServerCreatureObjectTemplate::getMaxFaucetModifierMax() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1226,7 +1202,7 @@ void ServerCreatureObjectTemplate::getAttribMods(AttribMod &data, int index) con if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter attribMods in template %s", DataResource::getName())); - return ; + return; } else { @@ -1240,10 +1216,10 @@ void ServerCreatureObjectTemplate::getAttribMods(AttribMod &data, int index) con { int baseCount = base->getAttribModsCount(); if (static_cast(index) < baseCount) - { - base->getAttribMods(data, index); - return; - } + { + base->getAttribMods(data, index); + return; + } index -= baseCount; } @@ -1272,7 +1248,7 @@ void ServerCreatureObjectTemplate::getAttribModsMin(AttribMod &data, int index) if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter attribMods in template %s", DataResource::getName())); - return ; + return; } else { @@ -1286,10 +1262,10 @@ void ServerCreatureObjectTemplate::getAttribModsMin(AttribMod &data, int index) { int baseCount = base->getAttribModsCount(); if (static_cast(index) < baseCount) - { - base->getAttribModsMin(data, index); - return; - } + { + base->getAttribModsMin(data, index); + return; + } index -= baseCount; } @@ -1318,7 +1294,7 @@ void ServerCreatureObjectTemplate::getAttribModsMax(AttribMod &data, int index) if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter attribMods in template %s", DataResource::getName())); - return ; + return; } else { @@ -1332,10 +1308,10 @@ void ServerCreatureObjectTemplate::getAttribModsMax(AttribMod &data, int index) { int baseCount = base->getAttribModsCount(); if (static_cast(index) < baseCount) - { - base->getAttribModsMax(data, index); - return; - } + { + base->getAttribModsMax(data, index); + return; + } index -= baseCount; } @@ -1377,8 +1353,6 @@ size_t ServerCreatureObjectTemplate::getAttribModsCount(void) const int ServerCreatureObjectTemplate::getShockWounds() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1428,8 +1402,6 @@ int ServerCreatureObjectTemplate::getShockWounds() const int ServerCreatureObjectTemplate::getShockWoundsMin() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1479,8 +1451,6 @@ int ServerCreatureObjectTemplate::getShockWoundsMin() const int ServerCreatureObjectTemplate::getShockWoundsMax() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1530,8 +1500,6 @@ int ServerCreatureObjectTemplate::getShockWoundsMax() const bool ServerCreatureObjectTemplate::getCanCreateAvatar() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1559,8 +1527,6 @@ bool ServerCreatureObjectTemplate::getCanCreateAvatar() const const std::string & ServerCreatureObjectTemplate::getNameGeneratorType() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1588,8 +1554,6 @@ const std::string & ServerCreatureObjectTemplate::getNameGeneratorType() const float ServerCreatureObjectTemplate::getApproachTriggerRange() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1639,8 +1603,6 @@ float ServerCreatureObjectTemplate::getApproachTriggerRange() const float ServerCreatureObjectTemplate::getApproachTriggerRangeMin() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1690,8 +1652,6 @@ float ServerCreatureObjectTemplate::getApproachTriggerRangeMin() const float ServerCreatureObjectTemplate::getApproachTriggerRangeMax() const { - - const ServerCreatureObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -2033,7 +1993,6 @@ float ServerCreatureObjectTemplate::getMentalStatesDecayMax(MentalStates index) return value; } // ServerCreatureObjectTemplate::getMentalStatesDecayMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -2042,8 +2001,8 @@ float ServerCreatureObjectTemplate::getMentalStatesDecayMax(MentalStates index) */ void ServerCreatureObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerCreatureObjectTemplate_tag) { @@ -2053,7 +2012,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -2073,10 +2032,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,5)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 5)) { - - m_versionOk = false; } @@ -2226,4 +2183,4 @@ const StringId &ServerCreatureObjectTemplate::verifyName(const Unicode::String & void ServerCreatureObjectTemplate::postLoad() { ServerTangibleObjectTemplate::postLoad(); -} +} \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerDraftSchematicObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerDraftSchematicObjectTemplate.cpp index 9ffea4cf..5d8a2fc9 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerDraftSchematicObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerDraftSchematicObjectTemplate.cpp @@ -24,26 +24,26 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerDraftSchematicObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerDraftSchematicObjectTemplate::ServerDraftSchematicObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerIntangibleObjectTemplate(filename) - ,m_slotsLoaded(false) - ,m_slotsAppend(false) - ,m_skillCommandsLoaded(false) - ,m_skillCommandsAppend(false) - ,m_manufactureScriptsLoaded(false) - ,m_manufactureScriptsAppend(false) - ,m_versionOk(true) -//@END TFD INIT + , m_slotsLoaded(false) + , m_slotsAppend(false) + , m_skillCommandsLoaded(false) + , m_skillCommandsAppend(false) + , m_manufactureScriptsLoaded(false) + , m_manufactureScriptsAppend(false) + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerDraftSchematicObjectTemplate::ServerDraftSchematicObjectTemplate @@ -52,7 +52,7 @@ ServerDraftSchematicObjectTemplate::ServerDraftSchematicObjectTemplate(const std */ ServerDraftSchematicObjectTemplate::~ServerDraftSchematicObjectTemplate() { -//@BEGIN TFD CLEANUP + //@BEGIN TFD CLEANUP { std::vector::iterator iter; for (iter = m_slots.begin(); iter != m_slots.end(); ++iter) @@ -80,7 +80,7 @@ ServerDraftSchematicObjectTemplate::~ServerDraftSchematicObjectTemplate() } m_manufactureScripts.clear(); } -//@END TFD CLEANUP + //@END TFD CLEANUP } // ServerDraftSchematicObjectTemplate::~ServerDraftSchematicObjectTemplate /** @@ -143,14 +143,13 @@ Tag ServerDraftSchematicObjectTemplate::getHighestTemplateVersion(void) const */ Object * ServerDraftSchematicObjectTemplate::createObject(void) const { - WARNING(true, ("Trying to create a draft schematic %s outside the draft " "schematic factory!\n", getName())); return nullptr; } // ServerDraftSchematicObjectTemplate::createObject /** - * Called after the template data has been loaded. Verifies that the schematic has + * Called after the template data has been loaded. Verifies that the schematic has * good data. */ void ServerDraftSchematicObjectTemplate::postLoad() @@ -160,8 +159,6 @@ void ServerDraftSchematicObjectTemplate::postLoad() //@BEGIN TFD ServerDraftSchematicObjectTemplate::CraftingType ServerDraftSchematicObjectTemplate::getCategory() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -212,7 +209,7 @@ const ServerObjectTemplate * ServerDraftSchematicObjectTemplate::getCraftedObjec const std::string & templateName = m_craftedObjectTemplate.getValue(); const ServerObjectTemplate * returnValue = dynamic_cast(ObjectTemplateList::fetch(templateName)); if (returnValue == nullptr) - WARNING_STRICT_FATAL(true, ("Error loading template %s",templateName.c_str())); + WARNING_STRICT_FATAL(true, ("Error loading template %s", templateName.c_str())); return returnValue; } // ServerDraftSchematicObjectTemplate::getCraftedObjectTemplate @@ -241,7 +238,7 @@ const ServerFactoryObjectTemplate * ServerDraftSchematicObjectTemplate::getCrate const std::string & templateName = m_crateObjectTemplate.getValue(); const ServerFactoryObjectTemplate * returnValue = dynamic_cast(ObjectTemplateList::fetch(templateName)); if (returnValue == nullptr) - WARNING_STRICT_FATAL(true, ("Error loading template %s",templateName.c_str())); + WARNING_STRICT_FATAL(true, ("Error loading template %s", templateName.c_str())); return returnValue; } // ServerDraftSchematicObjectTemplate::getCrateObjectTemplate @@ -258,7 +255,7 @@ void ServerDraftSchematicObjectTemplate::getSlots(IngredientSlot &data, int inde if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter slots in template %s", DataResource::getName())); - return ; + return; } else { @@ -272,10 +269,10 @@ void ServerDraftSchematicObjectTemplate::getSlots(IngredientSlot &data, int inde { int baseCount = base->getSlotsCount(); if (index < baseCount) - { - base->getSlots(data, index); - return; - } + { + base->getSlots(data, index); + return; + } index -= baseCount; } @@ -311,7 +308,7 @@ void ServerDraftSchematicObjectTemplate::getSlotsMin(IngredientSlot &data, int i if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter slots in template %s", DataResource::getName())); - return ; + return; } else { @@ -325,10 +322,10 @@ void ServerDraftSchematicObjectTemplate::getSlotsMin(IngredientSlot &data, int i { int baseCount = base->getSlotsCount(); if (index < baseCount) - { - base->getSlotsMin(data, index); - return; - } + { + base->getSlotsMin(data, index); + return; + } index -= baseCount; } @@ -364,7 +361,7 @@ void ServerDraftSchematicObjectTemplate::getSlotsMax(IngredientSlot &data, int i if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter slots in template %s", DataResource::getName())); - return ; + return; } else { @@ -378,10 +375,10 @@ void ServerDraftSchematicObjectTemplate::getSlotsMax(IngredientSlot &data, int i { int baseCount = base->getSlotsCount(); if (index < baseCount) - { - base->getSlotsMax(data, index); - return; - } + { + base->getSlotsMax(data, index); + return; + } index -= baseCount; } @@ -489,8 +486,6 @@ size_t ServerDraftSchematicObjectTemplate::getSkillCommandsCount(void) const bool ServerDraftSchematicObjectTemplate::getDestroyIngredients() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -577,8 +572,6 @@ size_t ServerDraftSchematicObjectTemplate::getManufactureScriptsCount(void) cons int ServerDraftSchematicObjectTemplate::getItemsPerContainer() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -628,8 +621,6 @@ int ServerDraftSchematicObjectTemplate::getItemsPerContainer() const int ServerDraftSchematicObjectTemplate::getItemsPerContainerMin() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -679,8 +670,6 @@ int ServerDraftSchematicObjectTemplate::getItemsPerContainerMin() const int ServerDraftSchematicObjectTemplate::getItemsPerContainerMax() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -730,8 +719,6 @@ int ServerDraftSchematicObjectTemplate::getItemsPerContainerMax() const float ServerDraftSchematicObjectTemplate::getManufactureTime() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -781,8 +768,6 @@ float ServerDraftSchematicObjectTemplate::getManufactureTime() const float ServerDraftSchematicObjectTemplate::getManufactureTimeMin() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -832,8 +817,6 @@ float ServerDraftSchematicObjectTemplate::getManufactureTimeMin() const float ServerDraftSchematicObjectTemplate::getManufactureTimeMax() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -883,8 +866,6 @@ float ServerDraftSchematicObjectTemplate::getManufactureTimeMax() const float ServerDraftSchematicObjectTemplate::getPrototypeTime() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -934,8 +915,6 @@ float ServerDraftSchematicObjectTemplate::getPrototypeTime() const float ServerDraftSchematicObjectTemplate::getPrototypeTimeMin() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -985,8 +964,6 @@ float ServerDraftSchematicObjectTemplate::getPrototypeTimeMin() const float ServerDraftSchematicObjectTemplate::getPrototypeTimeMax() const { - - const ServerDraftSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1034,7 +1011,6 @@ float ServerDraftSchematicObjectTemplate::getPrototypeTimeMax() const return value; } // ServerDraftSchematicObjectTemplate::getPrototypeTimeMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -1043,8 +1019,8 @@ float ServerDraftSchematicObjectTemplate::getPrototypeTimeMax() const */ void ServerDraftSchematicObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerDraftSchematicObjectTemplate_tag) { @@ -1054,7 +1030,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -1074,10 +1050,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,7)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 7)) { - - m_versionOk = false; } @@ -1170,7 +1144,6 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerDraftSchematicObjectTemplate::load - //============================================================================= // class ServerDraftSchematicObjectTemplate::_IngredientSlot @@ -1179,8 +1152,8 @@ char paramName[MAX_NAME_SIZE]; */ ServerDraftSchematicObjectTemplate::_IngredientSlot::_IngredientSlot(const std::string & filename) : ObjectTemplate(filename) - ,m_optionsLoaded(false) - ,m_optionsAppend(false) + , m_optionsLoaded(false) + , m_optionsAppend(false) { } // ServerDraftSchematicObjectTemplate::_IngredientSlot::_IngredientSlot @@ -1230,8 +1203,6 @@ Tag ServerDraftSchematicObjectTemplate::_IngredientSlot::getId(void) const bool ServerDraftSchematicObjectTemplate::_IngredientSlot::getOptional(bool versionOk) const { - - const ServerDraftSchematicObjectTemplate::_IngredientSlot * base = nullptr; if (m_baseData != nullptr) { @@ -1259,8 +1230,6 @@ bool ServerDraftSchematicObjectTemplate::_IngredientSlot::getOptional(bool versi const StringId ServerDraftSchematicObjectTemplate::_IngredientSlot::getName(bool versionOk) const { - - const ServerDraftSchematicObjectTemplate::_IngredientSlot * base = nullptr; if (m_baseData != nullptr) { @@ -1299,7 +1268,7 @@ void ServerDraftSchematicObjectTemplate::_IngredientSlot::getOptions(Ingredient if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter options in template %s", DataResource::getName())); - return ; + return; } else { @@ -1313,10 +1282,10 @@ void ServerDraftSchematicObjectTemplate::_IngredientSlot::getOptions(Ingredient { int baseCount = base->getOptionsCount(); if (index < baseCount) - { - base->getOptions(data, index, versionOk); - return; - } + { + base->getOptions(data, index, versionOk); + return; + } index -= baseCount; } @@ -1350,7 +1319,7 @@ void ServerDraftSchematicObjectTemplate::_IngredientSlot::getOptionsMin(Ingredie if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter options in template %s", DataResource::getName())); - return ; + return; } else { @@ -1364,10 +1333,10 @@ void ServerDraftSchematicObjectTemplate::_IngredientSlot::getOptionsMin(Ingredie { int baseCount = base->getOptionsCount(); if (index < baseCount) - { - base->getOptionsMin(data, index, versionOk); - return; - } + { + base->getOptionsMin(data, index, versionOk); + return; + } index -= baseCount; } @@ -1401,7 +1370,7 @@ void ServerDraftSchematicObjectTemplate::_IngredientSlot::getOptionsMax(Ingredie if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter options in template %s", DataResource::getName())); - return ; + return; } else { @@ -1415,10 +1384,10 @@ void ServerDraftSchematicObjectTemplate::_IngredientSlot::getOptionsMax(Ingredie { int baseCount = base->getOptionsCount(); if (index < baseCount) - { - base->getOptionsMax(data, index, versionOk); - return; - } + { + base->getOptionsMax(data, index, versionOk); + return; + } index -= baseCount; } @@ -1465,8 +1434,6 @@ size_t ServerDraftSchematicObjectTemplate::_IngredientSlot::getOptionsCount(void const std::string & ServerDraftSchematicObjectTemplate::_IngredientSlot::getOptionalSkillCommand(bool versionOk) const { - - const ServerDraftSchematicObjectTemplate::_IngredientSlot * base = nullptr; if (m_baseData != nullptr) { @@ -1494,8 +1461,6 @@ const std::string & ServerDraftSchematicObjectTemplate::_IngredientSlot::getOpti float ServerDraftSchematicObjectTemplate::_IngredientSlot::getComplexity(bool versionOk) const { - - const ServerDraftSchematicObjectTemplate::_IngredientSlot * base = nullptr; if (m_baseData != nullptr) { @@ -1545,8 +1510,6 @@ float ServerDraftSchematicObjectTemplate::_IngredientSlot::getComplexity(bool ve float ServerDraftSchematicObjectTemplate::_IngredientSlot::getComplexityMin(bool versionOk) const { - - const ServerDraftSchematicObjectTemplate::_IngredientSlot * base = nullptr; if (m_baseData != nullptr) { @@ -1596,8 +1559,6 @@ float ServerDraftSchematicObjectTemplate::_IngredientSlot::getComplexityMin(bool float ServerDraftSchematicObjectTemplate::_IngredientSlot::getComplexityMax(bool versionOk) const { - - const ServerDraftSchematicObjectTemplate::_IngredientSlot * base = nullptr; if (m_baseData != nullptr) { @@ -1647,8 +1608,6 @@ float ServerDraftSchematicObjectTemplate::_IngredientSlot::getComplexityMax(bool const std::string & ServerDraftSchematicObjectTemplate::_IngredientSlot::getAppearance(bool versionOk) const { - - const ServerDraftSchematicObjectTemplate::_IngredientSlot * base = nullptr; if (m_baseData != nullptr) { @@ -1674,7 +1633,6 @@ const std::string & ServerDraftSchematicObjectTemplate::_IngredientSlot::getAppe return value; } // ServerDraftSchematicObjectTemplate::_IngredientSlot::getAppearance - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -1683,8 +1641,8 @@ const std::string & ServerDraftSchematicObjectTemplate::_IngredientSlot::getAppe */ void ServerDraftSchematicObjectTemplate::_IngredientSlot::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; file.enterForm(); @@ -1731,4 +1689,4 @@ char paramName[MAX_NAME_SIZE]; UNREF(file); } // ServerDraftSchematicObjectTemplate::_IngredientSlot::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerFactoryObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerFactoryObjectTemplate.cpp index d86622d6..fe0c4e5f 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerFactoryObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerFactoryObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerFactoryObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerFactoryObjectTemplate::ServerFactoryObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerTangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerFactoryObjectTemplate::ServerFactoryObjectTemplate @@ -44,8 +44,8 @@ ServerFactoryObjectTemplate::ServerFactoryObjectTemplate(const std::string & fil */ ServerFactoryObjectTemplate::~ServerFactoryObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerFactoryObjectTemplate::~ServerFactoryObjectTemplate /** @@ -121,8 +121,8 @@ Object * ServerFactoryObjectTemplate::createObject(void) const */ void ServerFactoryObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerFactoryObjectTemplate_tag) { @@ -132,7 +132,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -152,10 +152,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -173,4 +171,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerFactoryObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerGroupObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerGroupObjectTemplate.cpp index c426aa8b..4e1add97 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerGroupObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerGroupObjectTemplate.cpp @@ -24,20 +24,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerGroupObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerGroupObjectTemplate::ServerGroupObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerUniverseObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerGroupObjectTemplate::ServerGroupObjectTemplate @@ -46,8 +46,8 @@ ServerGroupObjectTemplate::ServerGroupObjectTemplate(const std::string & filenam */ ServerGroupObjectTemplate::~ServerGroupObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerGroupObjectTemplate::~ServerGroupObjectTemplate /** @@ -123,8 +123,8 @@ Object * ServerGroupObjectTemplate::createObject(void) const */ void ServerGroupObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerGroupObjectTemplate_tag) { @@ -134,7 +134,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -154,10 +154,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -175,4 +173,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerGroupObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerGuildObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerGuildObjectTemplate.cpp index 9c73ce50..7af51fce 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerGuildObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerGuildObjectTemplate.cpp @@ -24,20 +24,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerGuildObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerGuildObjectTemplate::ServerGuildObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerUniverseObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerGuildObjectTemplate::ServerGuildObjectTemplate @@ -46,8 +46,8 @@ ServerGuildObjectTemplate::ServerGuildObjectTemplate(const std::string & filenam */ ServerGuildObjectTemplate::~ServerGuildObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerGuildObjectTemplate::~ServerGuildObjectTemplate /** @@ -123,8 +123,8 @@ Object * ServerGuildObjectTemplate::createObject(void) const */ void ServerGuildObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerGuildObjectTemplate_tag) { @@ -134,7 +134,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -154,10 +154,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -175,4 +173,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerGuildObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerHarvesterInstallationObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerHarvesterInstallationObjectTemplate.cpp index d62b39c9..566f6a37 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerHarvesterInstallationObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerHarvesterInstallationObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerHarvesterInstallationObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerHarvesterInstallationObjectTemplate::ServerHarvesterInstallationObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerInstallationObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerHarvesterInstallationObjectTemplate::ServerHarvesterInstallationObjectTemplate @@ -44,8 +44,8 @@ ServerHarvesterInstallationObjectTemplate::ServerHarvesterInstallationObjectTemp */ ServerHarvesterInstallationObjectTemplate::~ServerHarvesterInstallationObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerHarvesterInstallationObjectTemplate::~ServerHarvesterInstallationObjectTemplate /** @@ -114,8 +114,6 @@ Object * ServerHarvesterInstallationObjectTemplate::createObject(void) const //@BEGIN TFD int ServerHarvesterInstallationObjectTemplate::getMaxExtractionRate() const { - - const ServerHarvesterInstallationObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -165,8 +163,6 @@ int ServerHarvesterInstallationObjectTemplate::getMaxExtractionRate() const int ServerHarvesterInstallationObjectTemplate::getMaxExtractionRateMin() const { - - const ServerHarvesterInstallationObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -216,8 +212,6 @@ int ServerHarvesterInstallationObjectTemplate::getMaxExtractionRateMin() const int ServerHarvesterInstallationObjectTemplate::getMaxExtractionRateMax() const { - - const ServerHarvesterInstallationObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -267,8 +261,6 @@ int ServerHarvesterInstallationObjectTemplate::getMaxExtractionRateMax() const int ServerHarvesterInstallationObjectTemplate::getCurrentExtractionRate() const { - - const ServerHarvesterInstallationObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -318,8 +310,6 @@ int ServerHarvesterInstallationObjectTemplate::getCurrentExtractionRate() const int ServerHarvesterInstallationObjectTemplate::getCurrentExtractionRateMin() const { - - const ServerHarvesterInstallationObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -369,8 +359,6 @@ int ServerHarvesterInstallationObjectTemplate::getCurrentExtractionRateMin() con int ServerHarvesterInstallationObjectTemplate::getCurrentExtractionRateMax() const { - - const ServerHarvesterInstallationObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -420,8 +408,6 @@ int ServerHarvesterInstallationObjectTemplate::getCurrentExtractionRateMax() con int ServerHarvesterInstallationObjectTemplate::getMaxHopperSize() const { - - const ServerHarvesterInstallationObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -471,8 +457,6 @@ int ServerHarvesterInstallationObjectTemplate::getMaxHopperSize() const int ServerHarvesterInstallationObjectTemplate::getMaxHopperSizeMin() const { - - const ServerHarvesterInstallationObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -522,8 +506,6 @@ int ServerHarvesterInstallationObjectTemplate::getMaxHopperSizeMin() const int ServerHarvesterInstallationObjectTemplate::getMaxHopperSizeMax() const { - - const ServerHarvesterInstallationObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -573,8 +555,6 @@ int ServerHarvesterInstallationObjectTemplate::getMaxHopperSizeMax() const const std::string & ServerHarvesterInstallationObjectTemplate::getMasterClassName() const { - - const ServerHarvesterInstallationObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -600,7 +580,6 @@ const std::string & ServerHarvesterInstallationObjectTemplate::getMasterClassNam return value; } // ServerHarvesterInstallationObjectTemplate::getMasterClassName - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -609,8 +588,8 @@ const std::string & ServerHarvesterInstallationObjectTemplate::getMasterClassNam */ void ServerHarvesterInstallationObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerHarvesterInstallationObjectTemplate_tag) { @@ -620,7 +599,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -640,10 +619,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -673,4 +650,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerHarvesterInstallationObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerInstallationObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerInstallationObjectTemplate.cpp index 8f8de32d..17832c22 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerInstallationObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerInstallationObjectTemplate.cpp @@ -23,20 +23,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerInstallationObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerInstallationObjectTemplate::ServerInstallationObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerTangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerInstallationObjectTemplate::ServerInstallationObjectTemplate @@ -45,8 +45,8 @@ ServerInstallationObjectTemplate::ServerInstallationObjectTemplate(const std::st */ ServerInstallationObjectTemplate::~ServerInstallationObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerInstallationObjectTemplate::~ServerInstallationObjectTemplate /** @@ -122,8 +122,8 @@ Object * ServerInstallationObjectTemplate::createObject(void) const */ void ServerInstallationObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerInstallationObjectTemplate_tag) { @@ -133,7 +133,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -153,10 +153,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,1)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 1)) { - - m_versionOk = false; } @@ -174,4 +172,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerInstallationObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerIntangibleObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerIntangibleObjectTemplate.cpp index 7215902b..60bfb3c8 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerIntangibleObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerIntangibleObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerIntangibleObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerIntangibleObjectTemplate::ServerIntangibleObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerIntangibleObjectTemplate::ServerIntangibleObjectTemplate @@ -44,8 +44,8 @@ ServerIntangibleObjectTemplate::ServerIntangibleObjectTemplate(const std::string */ ServerIntangibleObjectTemplate::~ServerIntangibleObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerIntangibleObjectTemplate::~ServerIntangibleObjectTemplate /** @@ -114,8 +114,6 @@ Object * ServerIntangibleObjectTemplate::createObject(void) const //@BEGIN TFD int ServerIntangibleObjectTemplate::getCount() const { - - const ServerIntangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -165,8 +163,6 @@ int ServerIntangibleObjectTemplate::getCount() const int ServerIntangibleObjectTemplate::getCountMin() const { - - const ServerIntangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -216,8 +212,6 @@ int ServerIntangibleObjectTemplate::getCountMin() const int ServerIntangibleObjectTemplate::getCountMax() const { - - const ServerIntangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -265,7 +259,6 @@ int ServerIntangibleObjectTemplate::getCountMax() const return value; } // ServerIntangibleObjectTemplate::getCountMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -274,8 +267,8 @@ int ServerIntangibleObjectTemplate::getCountMax() const */ void ServerIntangibleObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerIntangibleObjectTemplate_tag) { @@ -285,7 +278,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -305,10 +298,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,1)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 1)) { - - m_versionOk = false; } @@ -332,7 +323,6 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerIntangibleObjectTemplate::load - //============================================================================= // class ServerIntangibleObjectTemplate::_Ingredient @@ -341,8 +331,8 @@ char paramName[MAX_NAME_SIZE]; */ ServerIntangibleObjectTemplate::_Ingredient::_Ingredient(const std::string & filename) : ObjectTemplate(filename) - ,m_ingredientsLoaded(false) - ,m_ingredientsAppend(false) + , m_ingredientsLoaded(false) + , m_ingredientsAppend(false) { } // ServerIntangibleObjectTemplate::_Ingredient::_Ingredient @@ -392,8 +382,6 @@ Tag ServerIntangibleObjectTemplate::_Ingredient::getId(void) const ServerIntangibleObjectTemplate::IngredientType ServerIntangibleObjectTemplate::_Ingredient::getIngredientType(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_Ingredient * base = nullptr; if (m_baseData != nullptr) { @@ -432,7 +420,7 @@ void ServerIntangibleObjectTemplate::_Ingredient::getIngredients(SimpleIngredien if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter ingredients in template %s", DataResource::getName())); - return ; + return; } else { @@ -446,10 +434,10 @@ void ServerIntangibleObjectTemplate::_Ingredient::getIngredients(SimpleIngredien { int baseCount = base->getIngredientsCount(); if (index < baseCount) - { - base->getIngredients(data, index, versionOk); - return; - } + { + base->getIngredients(data, index, versionOk); + return; + } index -= baseCount; } @@ -476,7 +464,7 @@ void ServerIntangibleObjectTemplate::_Ingredient::getIngredientsMin(SimpleIngred if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter ingredients in template %s", DataResource::getName())); - return ; + return; } else { @@ -490,10 +478,10 @@ void ServerIntangibleObjectTemplate::_Ingredient::getIngredientsMin(SimpleIngred { int baseCount = base->getIngredientsCount(); if (index < baseCount) - { - base->getIngredientsMin(data, index, versionOk); - return; - } + { + base->getIngredientsMin(data, index, versionOk); + return; + } index -= baseCount; } @@ -520,7 +508,7 @@ void ServerIntangibleObjectTemplate::_Ingredient::getIngredientsMax(SimpleIngred if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter ingredients in template %s", DataResource::getName())); - return ; + return; } else { @@ -534,10 +522,10 @@ void ServerIntangibleObjectTemplate::_Ingredient::getIngredientsMax(SimpleIngred { int baseCount = base->getIngredientsCount(); if (index < baseCount) - { - base->getIngredientsMax(data, index, versionOk); - return; - } + { + base->getIngredientsMax(data, index, versionOk); + return; + } index -= baseCount; } @@ -577,8 +565,6 @@ size_t ServerIntangibleObjectTemplate::_Ingredient::getIngredientsCount(void) co float ServerIntangibleObjectTemplate::_Ingredient::getComplexity(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_Ingredient * base = nullptr; if (m_baseData != nullptr) { @@ -628,8 +614,6 @@ float ServerIntangibleObjectTemplate::_Ingredient::getComplexity(bool versionOk) float ServerIntangibleObjectTemplate::_Ingredient::getComplexityMin(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_Ingredient * base = nullptr; if (m_baseData != nullptr) { @@ -679,8 +663,6 @@ float ServerIntangibleObjectTemplate::_Ingredient::getComplexityMin(bool version float ServerIntangibleObjectTemplate::_Ingredient::getComplexityMax(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_Ingredient * base = nullptr; if (m_baseData != nullptr) { @@ -730,8 +712,6 @@ float ServerIntangibleObjectTemplate::_Ingredient::getComplexityMax(bool version const std::string & ServerIntangibleObjectTemplate::_Ingredient::getSkillCommand(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_Ingredient * base = nullptr; if (m_baseData != nullptr) { @@ -757,7 +737,6 @@ const std::string & ServerIntangibleObjectTemplate::_Ingredient::getSkillCommand return value; } // ServerIntangibleObjectTemplate::_Ingredient::getSkillCommand - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -766,8 +745,8 @@ const std::string & ServerIntangibleObjectTemplate::_Ingredient::getSkillCommand */ void ServerIntangibleObjectTemplate::_Ingredient::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; file.enterForm(); @@ -810,7 +789,6 @@ char paramName[MAX_NAME_SIZE]; UNREF(file); } // ServerIntangibleObjectTemplate::_Ingredient::load - //============================================================================= // class ServerIntangibleObjectTemplate::_SchematicAttribute @@ -859,8 +837,6 @@ Tag ServerIntangibleObjectTemplate::_SchematicAttribute::getId(void) const const StringId ServerIntangibleObjectTemplate::_SchematicAttribute::getName(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_SchematicAttribute * base = nullptr; if (m_baseData != nullptr) { @@ -888,8 +864,6 @@ const StringId ServerIntangibleObjectTemplate::_SchematicAttribute::getName(bool int ServerIntangibleObjectTemplate::_SchematicAttribute::getValue(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_SchematicAttribute * base = nullptr; if (m_baseData != nullptr) { @@ -939,8 +913,6 @@ int ServerIntangibleObjectTemplate::_SchematicAttribute::getValue(bool versionOk int ServerIntangibleObjectTemplate::_SchematicAttribute::getValueMin(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_SchematicAttribute * base = nullptr; if (m_baseData != nullptr) { @@ -990,8 +962,6 @@ int ServerIntangibleObjectTemplate::_SchematicAttribute::getValueMin(bool versio int ServerIntangibleObjectTemplate::_SchematicAttribute::getValueMax(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_SchematicAttribute * base = nullptr; if (m_baseData != nullptr) { @@ -1039,7 +1009,6 @@ int ServerIntangibleObjectTemplate::_SchematicAttribute::getValueMax(bool versio return value; } // ServerIntangibleObjectTemplate::_SchematicAttribute::getValueMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -1048,8 +1017,8 @@ int ServerIntangibleObjectTemplate::_SchematicAttribute::getValueMax(bool versio */ void ServerIntangibleObjectTemplate::_SchematicAttribute::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; file.enterForm(); @@ -1071,7 +1040,6 @@ char paramName[MAX_NAME_SIZE]; UNREF(file); } // ServerIntangibleObjectTemplate::_SchematicAttribute::load - //============================================================================= // class ServerIntangibleObjectTemplate::_SimpleIngredient @@ -1120,8 +1088,6 @@ Tag ServerIntangibleObjectTemplate::_SimpleIngredient::getId(void) const const StringId ServerIntangibleObjectTemplate::_SimpleIngredient::getName(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_SimpleIngredient * base = nullptr; if (m_baseData != nullptr) { @@ -1149,8 +1115,6 @@ const StringId ServerIntangibleObjectTemplate::_SimpleIngredient::getName(bool v const std::string & ServerIntangibleObjectTemplate::_SimpleIngredient::getIngredient(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_SimpleIngredient * base = nullptr; if (m_baseData != nullptr) { @@ -1178,8 +1142,6 @@ const std::string & ServerIntangibleObjectTemplate::_SimpleIngredient::getIngred int ServerIntangibleObjectTemplate::_SimpleIngredient::getCount(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_SimpleIngredient * base = nullptr; if (m_baseData != nullptr) { @@ -1229,8 +1191,6 @@ int ServerIntangibleObjectTemplate::_SimpleIngredient::getCount(bool versionOk) int ServerIntangibleObjectTemplate::_SimpleIngredient::getCountMin(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_SimpleIngredient * base = nullptr; if (m_baseData != nullptr) { @@ -1280,8 +1240,6 @@ int ServerIntangibleObjectTemplate::_SimpleIngredient::getCountMin(bool versionO int ServerIntangibleObjectTemplate::_SimpleIngredient::getCountMax(bool versionOk) const { - - const ServerIntangibleObjectTemplate::_SimpleIngredient * base = nullptr; if (m_baseData != nullptr) { @@ -1329,7 +1287,6 @@ int ServerIntangibleObjectTemplate::_SimpleIngredient::getCountMax(bool versionO return value; } // ServerIntangibleObjectTemplate::_SimpleIngredient::getCountMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -1338,8 +1295,8 @@ int ServerIntangibleObjectTemplate::_SimpleIngredient::getCountMax(bool versionO */ void ServerIntangibleObjectTemplate::_SimpleIngredient::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; file.enterForm(); @@ -1363,4 +1320,4 @@ char paramName[MAX_NAME_SIZE]; UNREF(file); } // ServerIntangibleObjectTemplate::_SimpleIngredient::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerManufactureInstallationObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerManufactureInstallationObjectTemplate.cpp index 21a0e496..d58f2225 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerManufactureInstallationObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerManufactureInstallationObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerManufactureInstallationObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerManufactureInstallationObjectTemplate::ServerManufactureInstallationObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerInstallationObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerManufactureInstallationObjectTemplate::ServerManufactureInstallationObjectTemplate @@ -44,8 +44,8 @@ ServerManufactureInstallationObjectTemplate::ServerManufactureInstallationObject */ ServerManufactureInstallationObjectTemplate::~ServerManufactureInstallationObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerManufactureInstallationObjectTemplate::~ServerManufactureInstallationObjectTemplate /** @@ -121,8 +121,8 @@ Object * ServerManufactureInstallationObjectTemplate::createObject(void) const */ void ServerManufactureInstallationObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerManufactureInstallationObjectTemplate_tag) { @@ -132,7 +132,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -152,10 +152,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -173,4 +171,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerManufactureInstallationObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerManufactureSchematicObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerManufactureSchematicObjectTemplate.cpp index 2ec206b5..177c7aa8 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerManufactureSchematicObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerManufactureSchematicObjectTemplate.cpp @@ -22,24 +22,24 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerManufactureSchematicObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerManufactureSchematicObjectTemplate::ServerManufactureSchematicObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerIntangibleObjectTemplate(filename) - ,m_ingredientsLoaded(false) - ,m_ingredientsAppend(false) - ,m_attributesLoaded(false) - ,m_attributesAppend(false) - ,m_versionOk(true) -//@END TFD INIT + , m_ingredientsLoaded(false) + , m_ingredientsAppend(false) + , m_attributesLoaded(false) + , m_attributesAppend(false) + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerManufactureSchematicObjectTemplate::ServerManufactureSchematicObjectTemplate @@ -48,7 +48,7 @@ ServerManufactureSchematicObjectTemplate::ServerManufactureSchematicObjectTempla */ ServerManufactureSchematicObjectTemplate::~ServerManufactureSchematicObjectTemplate() { -//@BEGIN TFD CLEANUP + //@BEGIN TFD CLEANUP { std::vector::iterator iter; for (iter = m_ingredients.begin(); iter != m_ingredients.end(); ++iter) @@ -67,7 +67,7 @@ ServerManufactureSchematicObjectTemplate::~ServerManufactureSchematicObjectTempl } m_attributes.clear(); } -//@END TFD CLEANUP + //@END TFD CLEANUP } // ServerManufactureSchematicObjectTemplate::~ServerManufactureSchematicObjectTemplate /** @@ -131,8 +131,8 @@ Tag ServerManufactureSchematicObjectTemplate::getHighestTemplateVersion(void) co */ Object * ServerManufactureSchematicObjectTemplate::createObject(void) const { -// WARNING(true, ("Someone is trying to create a manf schematic without a " -// "draft schematic source!")); + // WARNING(true, ("Someone is trying to create a manf schematic without a " + // "draft schematic source!")); return new ManufactureSchematicObject(this); } // ServerManufactureSchematicObjectTemplate::createObject @@ -147,12 +147,12 @@ Object * ServerManufactureSchematicObjectTemplate::createObject(const char *cons if (objectTemplate) { Object * object = nullptr; - const ServerManufactureSchematicObjectTemplate * const manfTemplate = + const ServerManufactureSchematicObjectTemplate * const manfTemplate = dynamic_cast( - objectTemplate); + objectTemplate); if (manfTemplate != nullptr) object = manfTemplate->createObject(schematic); - objectTemplate->releaseReference (); + objectTemplate->releaseReference(); return object; } @@ -172,8 +172,6 @@ Object * ServerManufactureSchematicObjectTemplate::createObject(const DraftSchem //@BEGIN TFD const std::string & ServerManufactureSchematicObjectTemplate::getDraftSchematic() const { - - const ServerManufactureSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -201,8 +199,6 @@ const std::string & ServerManufactureSchematicObjectTemplate::getDraftSchematic( const std::string & ServerManufactureSchematicObjectTemplate::getCreator() const { - - const ServerManufactureSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -241,7 +237,7 @@ void ServerManufactureSchematicObjectTemplate::getIngredients(IngredientSlot &da if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter ingredients in template %s", DataResource::getName())); - return ; + return; } else { @@ -255,10 +251,10 @@ void ServerManufactureSchematicObjectTemplate::getIngredients(IngredientSlot &da { int baseCount = base->getIngredientsCount(); if (index < baseCount) - { - base->getIngredients(data, index); - return; - } + { + base->getIngredients(data, index); + return; + } index -= baseCount; } @@ -284,7 +280,7 @@ void ServerManufactureSchematicObjectTemplate::getIngredientsMin(IngredientSlot if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter ingredients in template %s", DataResource::getName())); - return ; + return; } else { @@ -298,10 +294,10 @@ void ServerManufactureSchematicObjectTemplate::getIngredientsMin(IngredientSlot { int baseCount = base->getIngredientsCount(); if (index < baseCount) - { - base->getIngredientsMin(data, index); - return; - } + { + base->getIngredientsMin(data, index); + return; + } index -= baseCount; } @@ -327,7 +323,7 @@ void ServerManufactureSchematicObjectTemplate::getIngredientsMax(IngredientSlot if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter ingredients in template %s", DataResource::getName())); - return ; + return; } else { @@ -341,10 +337,10 @@ void ServerManufactureSchematicObjectTemplate::getIngredientsMax(IngredientSlot { int baseCount = base->getIngredientsCount(); if (index < baseCount) - { - base->getIngredientsMax(data, index); - return; - } + { + base->getIngredientsMax(data, index); + return; + } index -= baseCount; } @@ -383,8 +379,6 @@ size_t ServerManufactureSchematicObjectTemplate::getIngredientsCount(void) const int ServerManufactureSchematicObjectTemplate::getItemCount() const { - - const ServerManufactureSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -434,8 +428,6 @@ int ServerManufactureSchematicObjectTemplate::getItemCount() const int ServerManufactureSchematicObjectTemplate::getItemCountMin() const { - - const ServerManufactureSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -485,8 +477,6 @@ int ServerManufactureSchematicObjectTemplate::getItemCountMin() const int ServerManufactureSchematicObjectTemplate::getItemCountMax() const { - - const ServerManufactureSchematicObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -547,7 +537,7 @@ void ServerManufactureSchematicObjectTemplate::getAttributes(SchematicAttribute if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter attributes in template %s", DataResource::getName())); - return ; + return; } else { @@ -561,10 +551,10 @@ void ServerManufactureSchematicObjectTemplate::getAttributes(SchematicAttribute { int baseCount = base->getAttributesCount(); if (index < baseCount) - { - base->getAttributes(data, index); - return; - } + { + base->getAttributes(data, index); + return; + } index -= baseCount; } @@ -590,7 +580,7 @@ void ServerManufactureSchematicObjectTemplate::getAttributesMin(SchematicAttribu if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter attributes in template %s", DataResource::getName())); - return ; + return; } else { @@ -604,10 +594,10 @@ void ServerManufactureSchematicObjectTemplate::getAttributesMin(SchematicAttribu { int baseCount = base->getAttributesCount(); if (index < baseCount) - { - base->getAttributesMin(data, index); - return; - } + { + base->getAttributesMin(data, index); + return; + } index -= baseCount; } @@ -633,7 +623,7 @@ void ServerManufactureSchematicObjectTemplate::getAttributesMax(SchematicAttribu if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter attributes in template %s", DataResource::getName())); - return ; + return; } else { @@ -647,10 +637,10 @@ void ServerManufactureSchematicObjectTemplate::getAttributesMax(SchematicAttribu { int baseCount = base->getAttributesCount(); if (index < baseCount) - { - base->getAttributesMax(data, index); - return; - } + { + base->getAttributesMax(data, index); + return; + } index -= baseCount; } @@ -687,7 +677,6 @@ size_t ServerManufactureSchematicObjectTemplate::getAttributesCount(void) const return count; } // ServerManufactureSchematicObjectTemplate::getAttributesCount - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -696,8 +685,8 @@ size_t ServerManufactureSchematicObjectTemplate::getAttributesCount(void) const */ void ServerManufactureSchematicObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerManufactureSchematicObjectTemplate_tag) { @@ -707,7 +696,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -727,10 +716,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -796,7 +783,6 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerManufactureSchematicObjectTemplate::load - //============================================================================= // class ServerManufactureSchematicObjectTemplate::_IngredientSlot @@ -845,8 +831,6 @@ Tag ServerManufactureSchematicObjectTemplate::_IngredientSlot::getId(void) const const StringId ServerManufactureSchematicObjectTemplate::_IngredientSlot::getName(bool versionOk) const { - - const ServerManufactureSchematicObjectTemplate::_IngredientSlot * base = nullptr; if (m_baseData != nullptr) { @@ -885,7 +869,7 @@ void ServerManufactureSchematicObjectTemplate::_IngredientSlot::getIngredient(In if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter ingredient in template %s", DataResource::getName())); - return ; + return; } else { @@ -924,7 +908,7 @@ void ServerManufactureSchematicObjectTemplate::_IngredientSlot::getIngredientMin if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter ingredient in template %s", DataResource::getName())); - return ; + return; } else { @@ -963,7 +947,7 @@ void ServerManufactureSchematicObjectTemplate::_IngredientSlot::getIngredientMax if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter ingredient in template %s", DataResource::getName())); - return ; + return; } else { @@ -989,7 +973,6 @@ void ServerManufactureSchematicObjectTemplate::_IngredientSlot::getIngredientMax data.skillCommand = param->getSkillCommand(versionOk); } // ServerManufactureSchematicObjectTemplate::_IngredientSlot::getIngredientMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -998,8 +981,8 @@ void ServerManufactureSchematicObjectTemplate::_IngredientSlot::getIngredientMax */ void ServerManufactureSchematicObjectTemplate::_IngredientSlot::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; file.enterForm(); @@ -1021,4 +1004,4 @@ char paramName[MAX_NAME_SIZE]; UNREF(file); } // ServerManufactureSchematicObjectTemplate::_IngredientSlot::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerMissionObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerMissionObjectTemplate.cpp index 393edf46..5ee34097 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerMissionObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerMissionObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerMissionObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerMissionObjectTemplate::ServerMissionObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerIntangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerMissionObjectTemplate::ServerMissionObjectTemplate @@ -44,8 +44,8 @@ ServerMissionObjectTemplate::ServerMissionObjectTemplate(const std::string & fil */ ServerMissionObjectTemplate::~ServerMissionObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerMissionObjectTemplate::~ServerMissionObjectTemplate /** @@ -121,8 +121,8 @@ Object * ServerMissionObjectTemplate::createObject(void) const */ void ServerMissionObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerMissionObjectTemplate_tag) { @@ -132,7 +132,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -152,10 +152,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -173,4 +171,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerMissionObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerObjectTemplate.cpp index 2ace8a95..957562c3 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerObjectTemplate.cpp @@ -26,35 +26,35 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerObjectTemplate::ms_allowDefaultTemplateParams = true; -typedef std::unordered_map > XP_MAP; +typedef std::unordered_map > XP_MAP; static XP_MAP * XpMap = nullptr; - /** * Class constructor. */ ServerObjectTemplate::ServerObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ObjectTemplate(filename) - ,m_scriptsLoaded(false) - ,m_scriptsAppend(false) - ,m_visibleFlagsLoaded(false) - ,m_visibleFlagsAppend(false) - ,m_deleteFlagsLoaded(false) - ,m_deleteFlagsAppend(false) - ,m_moveFlagsLoaded(false) - ,m_moveFlagsAppend(false) - ,m_contentsLoaded(false) - ,m_contentsAppend(false) - ,m_xpPointsLoaded(false) - ,m_xpPointsAppend(false) - ,m_versionOk(true) -//@END TFD INIT + , m_scriptsLoaded(false) + , m_scriptsAppend(false) + , m_visibleFlagsLoaded(false) + , m_visibleFlagsAppend(false) + , m_deleteFlagsLoaded(false) + , m_deleteFlagsAppend(false) + , m_moveFlagsLoaded(false) + , m_moveFlagsAppend(false) + , m_contentsLoaded(false) + , m_contentsAppend(false) + , m_xpPointsLoaded(false) + , m_xpPointsAppend(false) + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerObjectTemplate::ServerObjectTemplate @@ -66,9 +66,9 @@ ServerObjectTemplate::~ServerObjectTemplate() if (m_baseData) { m_baseData->releaseReference(); - m_baseData=0; + m_baseData = 0; } -//@BEGIN TFD CLEANUP + //@BEGIN TFD CLEANUP { std::vector::iterator iter; for (iter = m_scripts.begin(); iter != m_scripts.end(); ++iter) @@ -123,7 +123,7 @@ ServerObjectTemplate::~ServerObjectTemplate() } m_xpPoints.clear(); } -//@END TFD CLEANUP + //@END TFD CLEANUP } // ServerObjectTemplate::~ServerObjectTemplate /** @@ -299,11 +299,11 @@ const std::string & ServerObjectTemplate::getXpString(XpTypes type) //---------------------------------------------------------------------- -const std::string & ServerObjectTemplate::getDamageTypeString (DamageType type) +const std::string & ServerObjectTemplate::getDamageTypeString(DamageType type) { static const std::string emptyString; - static const std::string DAMAGE_TYPE_NAMES[] = + static const std::string DAMAGE_TYPE_NAMES[] = { "kinetic", "energy", @@ -329,7 +329,7 @@ const std::string & ServerObjectTemplate::getDamageTypeString (DamageType type) for (int index = 0; index < DAMAGE_TYPE_NAMES_SIZE; ++index) { if ((i_damage & (1 << index)) != 0) - return DAMAGE_TYPE_NAMES [index]; + return DAMAGE_TYPE_NAMES[index]; } } @@ -338,11 +338,11 @@ const std::string & ServerObjectTemplate::getDamageTypeString (DamageType type) //---------------------------------------------------------------------- -const std::string & ServerObjectTemplate::getArmorRatingString (ArmorRating type) +const std::string & ServerObjectTemplate::getArmorRatingString(ArmorRating type) { static const std::string emptyString; - static const std::string ARMOR_RATING_NAMES[] = + static const std::string ARMOR_RATING_NAMES[] = { "none", "light", @@ -357,7 +357,7 @@ const std::string & ServerObjectTemplate::getArmorRatingString (ArmorRating type if (i_type < 0 || i_type >= ARMOR_RATING_NAMES_SIZE) return emptyString; - return ARMOR_RATING_NAMES [i_type]; + return ARMOR_RATING_NAMES[i_type]; } //---------------------------------------------------------------------- @@ -365,8 +365,6 @@ const std::string & ServerObjectTemplate::getArmorRatingString (ArmorRating type //@BEGIN TFD const std::string & ServerObjectTemplate::getSharedTemplate() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -464,7 +462,7 @@ void ServerObjectTemplate::getObjvars(DynamicVariableList &list) const if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter objvars in template %s", DataResource::getName())); - return ; + return; } else { @@ -481,8 +479,6 @@ void ServerObjectTemplate::getObjvars(DynamicVariableList &list) const int ServerObjectTemplate::getVolume() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -532,8 +528,6 @@ int ServerObjectTemplate::getVolume() const int ServerObjectTemplate::getVolumeMin() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -583,8 +577,6 @@ int ServerObjectTemplate::getVolumeMin() const int ServerObjectTemplate::getVolumeMax() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -808,8 +800,6 @@ size_t ServerObjectTemplate::getMoveFlagsCount(void) const bool ServerObjectTemplate::getInvulnerable() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -837,8 +827,6 @@ bool ServerObjectTemplate::getInvulnerable() const float ServerObjectTemplate::getComplexity() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -888,8 +876,6 @@ float ServerObjectTemplate::getComplexity() const float ServerObjectTemplate::getComplexityMin() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -939,8 +925,6 @@ float ServerObjectTemplate::getComplexityMin() const float ServerObjectTemplate::getComplexityMax() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -990,8 +974,6 @@ float ServerObjectTemplate::getComplexityMax() const int ServerObjectTemplate::getTintIndex() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1041,8 +1023,6 @@ int ServerObjectTemplate::getTintIndex() const int ServerObjectTemplate::getTintIndexMin() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1092,8 +1072,6 @@ int ServerObjectTemplate::getTintIndexMin() const int ServerObjectTemplate::getTintIndexMax() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1301,7 +1279,7 @@ void ServerObjectTemplate::getContents(Contents &data, int index) const if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter contents in template %s", DataResource::getName())); - return ; + return; } else { @@ -1315,10 +1293,10 @@ void ServerObjectTemplate::getContents(Contents &data, int index) const { int baseCount = base->getContentsCount(); if (index < baseCount) - { - base->getContents(data, index); - return; - } + { + base->getContents(data, index); + return; + } index -= baseCount; } @@ -1345,7 +1323,7 @@ void ServerObjectTemplate::getContentsMin(Contents &data, int index) const if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter contents in template %s", DataResource::getName())); - return ; + return; } else { @@ -1359,10 +1337,10 @@ void ServerObjectTemplate::getContentsMin(Contents &data, int index) const { int baseCount = base->getContentsCount(); if (index < baseCount) - { - base->getContentsMin(data, index); - return; - } + { + base->getContentsMin(data, index); + return; + } index -= baseCount; } @@ -1389,7 +1367,7 @@ void ServerObjectTemplate::getContentsMax(Contents &data, int index) const if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter contents in template %s", DataResource::getName())); - return ; + return; } else { @@ -1403,10 +1381,10 @@ void ServerObjectTemplate::getContentsMax(Contents &data, int index) const { int baseCount = base->getContentsCount(); if (index < baseCount) - { - base->getContentsMax(data, index); - return; - } + { + base->getContentsMax(data, index); + return; + } index -= baseCount; } @@ -1457,7 +1435,7 @@ void ServerObjectTemplate::getXpPoints(Xp &data, int index) const if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter xpPoints in template %s", DataResource::getName())); - return ; + return; } else { @@ -1471,10 +1449,10 @@ void ServerObjectTemplate::getXpPoints(Xp &data, int index) const { int baseCount = base->getXpPointsCount(); if (index < baseCount) - { - base->getXpPoints(data, index); - return; - } + { + base->getXpPoints(data, index); + return; + } index -= baseCount; } @@ -1501,7 +1479,7 @@ void ServerObjectTemplate::getXpPointsMin(Xp &data, int index) const if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter xpPoints in template %s", DataResource::getName())); - return ; + return; } else { @@ -1515,10 +1493,10 @@ void ServerObjectTemplate::getXpPointsMin(Xp &data, int index) const { int baseCount = base->getXpPointsCount(); if (index < baseCount) - { - base->getXpPointsMin(data, index); - return; - } + { + base->getXpPointsMin(data, index); + return; + } index -= baseCount; } @@ -1545,7 +1523,7 @@ void ServerObjectTemplate::getXpPointsMax(Xp &data, int index) const if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == nullptr) { DEBUG_WARNING(true, ("Returning default value for missing parameter xpPoints in template %s", DataResource::getName())); - return ; + return; } else { @@ -1559,10 +1537,10 @@ void ServerObjectTemplate::getXpPointsMax(Xp &data, int index) const { int baseCount = base->getXpPointsCount(); if (index < baseCount) - { - base->getXpPointsMax(data, index); - return; - } + { + base->getXpPointsMax(data, index); + return; + } index -= baseCount; } @@ -1602,8 +1580,6 @@ size_t ServerObjectTemplate::getXpPointsCount(void) const bool ServerObjectTemplate::getPersistByDefault() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1631,8 +1607,6 @@ bool ServerObjectTemplate::getPersistByDefault() const bool ServerObjectTemplate::getPersistContents() const { - - const ServerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1658,7 +1632,6 @@ bool ServerObjectTemplate::getPersistContents() const return value; } // ServerObjectTemplate::getPersistContents - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -1667,8 +1640,8 @@ bool ServerObjectTemplate::getPersistContents() const */ void ServerObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerObjectTemplate_tag) { @@ -1677,7 +1650,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -1697,10 +1670,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,1,1)) + if (getHighestTemplateVersion() != TAG(0, 0, 1, 1)) { - - m_versionOk = false; } @@ -1864,7 +1835,6 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerObjectTemplate::load - //============================================================================= // class ServerObjectTemplate::_AttribMod @@ -1913,8 +1883,6 @@ Tag ServerObjectTemplate::_AttribMod::getId(void) const ServerObjectTemplate::Attributes ServerObjectTemplate::_AttribMod::getTarget(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -1942,8 +1910,6 @@ ServerObjectTemplate::Attributes ServerObjectTemplate::_AttribMod::getTarget(boo int ServerObjectTemplate::_AttribMod::getValue(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -1993,8 +1959,6 @@ int ServerObjectTemplate::_AttribMod::getValue(bool versionOk) const int ServerObjectTemplate::_AttribMod::getValueMin(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2044,8 +2008,6 @@ int ServerObjectTemplate::_AttribMod::getValueMin(bool versionOk) const int ServerObjectTemplate::_AttribMod::getValueMax(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2095,8 +2057,6 @@ int ServerObjectTemplate::_AttribMod::getValueMax(bool versionOk) const float ServerObjectTemplate::_AttribMod::getTime(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2146,8 +2106,6 @@ float ServerObjectTemplate::_AttribMod::getTime(bool versionOk) const float ServerObjectTemplate::_AttribMod::getTimeMin(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2197,8 +2155,6 @@ float ServerObjectTemplate::_AttribMod::getTimeMin(bool versionOk) const float ServerObjectTemplate::_AttribMod::getTimeMax(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2248,8 +2204,6 @@ float ServerObjectTemplate::_AttribMod::getTimeMax(bool versionOk) const float ServerObjectTemplate::_AttribMod::getTimeAtValue(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2299,8 +2253,6 @@ float ServerObjectTemplate::_AttribMod::getTimeAtValue(bool versionOk) const float ServerObjectTemplate::_AttribMod::getTimeAtValueMin(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2350,8 +2302,6 @@ float ServerObjectTemplate::_AttribMod::getTimeAtValueMin(bool versionOk) const float ServerObjectTemplate::_AttribMod::getTimeAtValueMax(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2401,8 +2351,6 @@ float ServerObjectTemplate::_AttribMod::getTimeAtValueMax(bool versionOk) const float ServerObjectTemplate::_AttribMod::getDecay(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2452,8 +2400,6 @@ float ServerObjectTemplate::_AttribMod::getDecay(bool versionOk) const float ServerObjectTemplate::_AttribMod::getDecayMin(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2503,8 +2449,6 @@ float ServerObjectTemplate::_AttribMod::getDecayMin(bool versionOk) const float ServerObjectTemplate::_AttribMod::getDecayMax(bool versionOk) const { - - const ServerObjectTemplate::_AttribMod * base = nullptr; if (m_baseData != nullptr) { @@ -2552,7 +2496,6 @@ float ServerObjectTemplate::_AttribMod::getDecayMax(bool versionOk) const return value; } // ServerObjectTemplate::_AttribMod::getDecayMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -2561,8 +2504,8 @@ float ServerObjectTemplate::_AttribMod::getDecayMax(bool versionOk) const */ void ServerObjectTemplate::_AttribMod::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; file.enterForm(); @@ -2590,7 +2533,6 @@ char paramName[MAX_NAME_SIZE]; UNREF(file); } // ServerObjectTemplate::_AttribMod::load - //============================================================================= // struct ServerObjectTemplate::Contents @@ -2637,7 +2579,6 @@ ServerObjectTemplate::Contents & ServerObjectTemplate::Contents::operator =(cons } // ServerObjectTemplate::Contents::operator = #endif - //============================================================================= // class ServerObjectTemplate::_Contents @@ -2686,8 +2627,6 @@ Tag ServerObjectTemplate::_Contents::getId(void) const const std::string & ServerObjectTemplate::_Contents::getSlotName(bool versionOk) const { - - const ServerObjectTemplate::_Contents * base = nullptr; if (m_baseData != nullptr) { @@ -2715,8 +2654,6 @@ const std::string & ServerObjectTemplate::_Contents::getSlotName(bool versionOk) bool ServerObjectTemplate::_Contents::getEquipObject(bool versionOk) const { - - const ServerObjectTemplate::_Contents * base = nullptr; if (m_baseData != nullptr) { @@ -2770,12 +2707,11 @@ const ServerObjectTemplate * ServerObjectTemplate::_Contents::getContent(bool ve { returnValue = dynamic_cast(ObjectTemplateList::fetch(templateName)); if (returnValue == nullptr) - WARNING_STRICT_FATAL(true, ("Error loading template %s",templateName.c_str())); + WARNING_STRICT_FATAL(true, ("Error loading template %s", templateName.c_str())); } return returnValue; } // ServerObjectTemplate::_Contents::getContent - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -2784,8 +2720,8 @@ const ServerObjectTemplate * ServerObjectTemplate::_Contents::getContent(bool ve */ void ServerObjectTemplate::_Contents::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; file.enterForm(); @@ -2809,7 +2745,6 @@ char paramName[MAX_NAME_SIZE]; UNREF(file); } // ServerObjectTemplate::_Contents::load - //============================================================================= // class ServerObjectTemplate::_MentalStateMod @@ -2858,8 +2793,6 @@ Tag ServerObjectTemplate::_MentalStateMod::getId(void) const ServerObjectTemplate::MentalStates ServerObjectTemplate::_MentalStateMod::getTarget(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -2887,8 +2820,6 @@ ServerObjectTemplate::MentalStates ServerObjectTemplate::_MentalStateMod::getTar float ServerObjectTemplate::_MentalStateMod::getValue(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -2938,8 +2869,6 @@ float ServerObjectTemplate::_MentalStateMod::getValue(bool versionOk) const float ServerObjectTemplate::_MentalStateMod::getValueMin(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -2989,8 +2918,6 @@ float ServerObjectTemplate::_MentalStateMod::getValueMin(bool versionOk) const float ServerObjectTemplate::_MentalStateMod::getValueMax(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -3040,8 +2967,6 @@ float ServerObjectTemplate::_MentalStateMod::getValueMax(bool versionOk) const float ServerObjectTemplate::_MentalStateMod::getTime(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -3091,8 +3016,6 @@ float ServerObjectTemplate::_MentalStateMod::getTime(bool versionOk) const float ServerObjectTemplate::_MentalStateMod::getTimeMin(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -3142,8 +3065,6 @@ float ServerObjectTemplate::_MentalStateMod::getTimeMin(bool versionOk) const float ServerObjectTemplate::_MentalStateMod::getTimeMax(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -3193,8 +3114,6 @@ float ServerObjectTemplate::_MentalStateMod::getTimeMax(bool versionOk) const float ServerObjectTemplate::_MentalStateMod::getTimeAtValue(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -3244,8 +3163,6 @@ float ServerObjectTemplate::_MentalStateMod::getTimeAtValue(bool versionOk) cons float ServerObjectTemplate::_MentalStateMod::getTimeAtValueMin(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -3295,8 +3212,6 @@ float ServerObjectTemplate::_MentalStateMod::getTimeAtValueMin(bool versionOk) c float ServerObjectTemplate::_MentalStateMod::getTimeAtValueMax(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -3346,8 +3261,6 @@ float ServerObjectTemplate::_MentalStateMod::getTimeAtValueMax(bool versionOk) c float ServerObjectTemplate::_MentalStateMod::getDecay(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -3397,8 +3310,6 @@ float ServerObjectTemplate::_MentalStateMod::getDecay(bool versionOk) const float ServerObjectTemplate::_MentalStateMod::getDecayMin(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -3448,8 +3359,6 @@ float ServerObjectTemplate::_MentalStateMod::getDecayMin(bool versionOk) const float ServerObjectTemplate::_MentalStateMod::getDecayMax(bool versionOk) const { - - const ServerObjectTemplate::_MentalStateMod * base = nullptr; if (m_baseData != nullptr) { @@ -3497,7 +3406,6 @@ float ServerObjectTemplate::_MentalStateMod::getDecayMax(bool versionOk) const return value; } // ServerObjectTemplate::_MentalStateMod::getDecayMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -3506,8 +3414,8 @@ float ServerObjectTemplate::_MentalStateMod::getDecayMax(bool versionOk) const */ void ServerObjectTemplate::_MentalStateMod::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; file.enterForm(); @@ -3535,7 +3443,6 @@ char paramName[MAX_NAME_SIZE]; UNREF(file); } // ServerObjectTemplate::_MentalStateMod::load - //============================================================================= // class ServerObjectTemplate::_Xp @@ -3584,8 +3491,6 @@ Tag ServerObjectTemplate::_Xp::getId(void) const ServerObjectTemplate::XpTypes ServerObjectTemplate::_Xp::getType(bool versionOk) const { - - const ServerObjectTemplate::_Xp * base = nullptr; if (m_baseData != nullptr) { @@ -3613,8 +3518,6 @@ ServerObjectTemplate::XpTypes ServerObjectTemplate::_Xp::getType(bool versionOk) int ServerObjectTemplate::_Xp::getLevel(bool versionOk) const { - - const ServerObjectTemplate::_Xp * base = nullptr; if (m_baseData != nullptr) { @@ -3664,8 +3567,6 @@ int ServerObjectTemplate::_Xp::getLevel(bool versionOk) const int ServerObjectTemplate::_Xp::getLevelMin(bool versionOk) const { - - const ServerObjectTemplate::_Xp * base = nullptr; if (m_baseData != nullptr) { @@ -3715,8 +3616,6 @@ int ServerObjectTemplate::_Xp::getLevelMin(bool versionOk) const int ServerObjectTemplate::_Xp::getLevelMax(bool versionOk) const { - - const ServerObjectTemplate::_Xp * base = nullptr; if (m_baseData != nullptr) { @@ -3766,8 +3665,6 @@ int ServerObjectTemplate::_Xp::getLevelMax(bool versionOk) const int ServerObjectTemplate::_Xp::getValue(bool versionOk) const { - - const ServerObjectTemplate::_Xp * base = nullptr; if (m_baseData != nullptr) { @@ -3817,8 +3714,6 @@ int ServerObjectTemplate::_Xp::getValue(bool versionOk) const int ServerObjectTemplate::_Xp::getValueMin(bool versionOk) const { - - const ServerObjectTemplate::_Xp * base = nullptr; if (m_baseData != nullptr) { @@ -3868,8 +3763,6 @@ int ServerObjectTemplate::_Xp::getValueMin(bool versionOk) const int ServerObjectTemplate::_Xp::getValueMax(bool versionOk) const { - - const ServerObjectTemplate::_Xp * base = nullptr; if (m_baseData != nullptr) { @@ -3917,7 +3810,6 @@ int ServerObjectTemplate::_Xp::getValueMax(bool versionOk) const return value; } // ServerObjectTemplate::_Xp::getValueMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -3926,8 +3818,8 @@ int ServerObjectTemplate::_Xp::getValueMax(bool versionOk) const */ void ServerObjectTemplate::_Xp::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; file.enterForm(); @@ -3951,4 +3843,4 @@ char paramName[MAX_NAME_SIZE]; UNREF(file); } // ServerObjectTemplate::_Xp::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlanetObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlanetObjectTemplate.cpp index e062a1a2..6f5a7cbf 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlanetObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlanetObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerPlanetObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerPlanetObjectTemplate::ServerPlanetObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerUniverseObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerPlanetObjectTemplate::ServerPlanetObjectTemplate @@ -44,8 +44,8 @@ ServerPlanetObjectTemplate::ServerPlanetObjectTemplate(const std::string & filen */ ServerPlanetObjectTemplate::~ServerPlanetObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerPlanetObjectTemplate::~ServerPlanetObjectTemplate /** @@ -114,8 +114,6 @@ Object * ServerPlanetObjectTemplate::createObject(void) const //@BEGIN TFD const std::string & ServerPlanetObjectTemplate::getPlanetName() const { - - const ServerPlanetObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -141,7 +139,6 @@ const std::string & ServerPlanetObjectTemplate::getPlanetName() const return value; } // ServerPlanetObjectTemplate::getPlanetName - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -150,8 +147,8 @@ const std::string & ServerPlanetObjectTemplate::getPlanetName() const */ void ServerPlanetObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerPlanetObjectTemplate_tag) { @@ -161,7 +158,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -181,10 +178,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -208,4 +203,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerPlanetObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlayerObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlayerObjectTemplate.cpp index 5c5b8bc7..752f5ed4 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlayerObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlayerObjectTemplate.cpp @@ -24,20 +24,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerPlayerObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerPlayerObjectTemplate::ServerPlayerObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerIntangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerPlayerObjectTemplate::ServerPlayerObjectTemplate @@ -46,8 +46,8 @@ ServerPlayerObjectTemplate::ServerPlayerObjectTemplate(const std::string & filen */ ServerPlayerObjectTemplate::~ServerPlayerObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerPlayerObjectTemplate::~ServerPlayerObjectTemplate /** @@ -123,8 +123,8 @@ Object * ServerPlayerObjectTemplate::createObject(void) const */ void ServerPlayerObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerPlayerObjectTemplate_tag) { @@ -134,7 +134,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -154,10 +154,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -175,4 +173,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerPlayerObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlayerQuestObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlayerQuestObjectTemplate.cpp index f8e95c89..48d74162 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlayerQuestObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerPlayerQuestObjectTemplate.cpp @@ -24,20 +24,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerPlayerQuestObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerPlayerQuestObjectTemplate::ServerPlayerQuestObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerTangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerPlayerQuestObjectTemplate::ServerPlayerQuestObjectTemplate @@ -46,8 +46,8 @@ ServerPlayerQuestObjectTemplate::ServerPlayerQuestObjectTemplate(const std::stri */ ServerPlayerQuestObjectTemplate::~ServerPlayerQuestObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerPlayerQuestObjectTemplate::~ServerPlayerQuestObjectTemplate /** @@ -113,7 +113,6 @@ Object * ServerPlayerQuestObjectTemplate::createObject(void) const return new PlayerQuestObject(this); } // ServerMissionObjectTemplate::createObject - //@BEGIN TFD /** @@ -124,8 +123,8 @@ Object * ServerPlayerQuestObjectTemplate::createObject(void) const */ void ServerPlayerQuestObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerPlayerQuestObjectTemplate_tag) { @@ -135,7 +134,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -155,10 +154,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -176,4 +173,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerPlayerQuestObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerResourceContainerObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerResourceContainerObjectTemplate.cpp index 664a0e50..a4eba676 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerResourceContainerObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerResourceContainerObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerResourceContainerObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerResourceContainerObjectTemplate::ServerResourceContainerObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerTangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerResourceContainerObjectTemplate::ServerResourceContainerObjectTemplate @@ -44,8 +44,8 @@ ServerResourceContainerObjectTemplate::ServerResourceContainerObjectTemplate(con */ ServerResourceContainerObjectTemplate::~ServerResourceContainerObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerResourceContainerObjectTemplate::~ServerResourceContainerObjectTemplate /** @@ -114,8 +114,6 @@ Object * ServerResourceContainerObjectTemplate::createObject(void) const //@BEGIN TFD int ServerResourceContainerObjectTemplate::getMaxResources() const { - - const ServerResourceContainerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -165,8 +163,6 @@ int ServerResourceContainerObjectTemplate::getMaxResources() const int ServerResourceContainerObjectTemplate::getMaxResourcesMin() const { - - const ServerResourceContainerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -216,8 +212,6 @@ int ServerResourceContainerObjectTemplate::getMaxResourcesMin() const int ServerResourceContainerObjectTemplate::getMaxResourcesMax() const { - - const ServerResourceContainerObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -265,7 +259,6 @@ int ServerResourceContainerObjectTemplate::getMaxResourcesMax() const return value; } // ServerResourceContainerObjectTemplate::getMaxResourcesMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -274,8 +267,8 @@ int ServerResourceContainerObjectTemplate::getMaxResourcesMax() const */ void ServerResourceContainerObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerResourceContainerObjectTemplate_tag) { @@ -285,7 +278,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -305,10 +298,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -332,4 +323,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerResourceContainerObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerShipObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerShipObjectTemplate.cpp index fee87be0..d4b0320c 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerShipObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerShipObjectTemplate.cpp @@ -23,20 +23,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerShipObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerShipObjectTemplate::ServerShipObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerTangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerShipObjectTemplate::ServerShipObjectTemplate @@ -45,8 +45,8 @@ ServerShipObjectTemplate::ServerShipObjectTemplate(const std::string & filename) */ ServerShipObjectTemplate::~ServerShipObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerShipObjectTemplate::~ServerShipObjectTemplate /** @@ -115,8 +115,6 @@ Object * ServerShipObjectTemplate::createObject(void) const //@BEGIN TFD const std::string & ServerShipObjectTemplate::getShipType() const { - - const ServerShipObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -142,7 +140,6 @@ const std::string & ServerShipObjectTemplate::getShipType() const return value; } // ServerShipObjectTemplate::getShipType - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -151,8 +148,8 @@ const std::string & ServerShipObjectTemplate::getShipType() const */ void ServerShipObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerShipObjectTemplate_tag) { @@ -162,7 +159,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -182,10 +179,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,1)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 1)) { - - m_versionOk = false; } @@ -209,4 +204,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerShipObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerStaticObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerStaticObjectTemplate.cpp index c4d48e62..46819a82 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerStaticObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerStaticObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerStaticObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerStaticObjectTemplate::ServerStaticObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerStaticObjectTemplate::ServerStaticObjectTemplate @@ -44,8 +44,8 @@ ServerStaticObjectTemplate::ServerStaticObjectTemplate(const std::string & filen */ ServerStaticObjectTemplate::~ServerStaticObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerStaticObjectTemplate::~ServerStaticObjectTemplate /** @@ -114,8 +114,6 @@ Object * ServerStaticObjectTemplate::createObject(void) const //@BEGIN TFD bool ServerStaticObjectTemplate::getClientOnlyBuildout() const { - - const ServerStaticObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -141,7 +139,6 @@ bool ServerStaticObjectTemplate::getClientOnlyBuildout() const return value; } // ServerStaticObjectTemplate::getClientOnlyBuildout - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -150,8 +147,8 @@ bool ServerStaticObjectTemplate::getClientOnlyBuildout() const */ void ServerStaticObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerStaticObjectTemplate_tag) { @@ -161,7 +158,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -181,10 +178,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,1)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 1)) { - - m_versionOk = false; } @@ -208,4 +203,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerStaticObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerTangibleObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerTangibleObjectTemplate.cpp index 6212cc40..7909df9e 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerTangibleObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerTangibleObjectTemplate.cpp @@ -23,22 +23,22 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerTangibleObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerTangibleObjectTemplate::ServerTangibleObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerObjectTemplate(filename) - ,m_triggerVolumesLoaded(false) - ,m_triggerVolumesAppend(false) - ,m_versionOk(true) -//@END TFD INIT + , m_triggerVolumesLoaded(false) + , m_triggerVolumesAppend(false) + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerTangibleObjectTemplate::ServerTangibleObjectTemplate @@ -47,7 +47,7 @@ ServerTangibleObjectTemplate::ServerTangibleObjectTemplate(const std::string & f */ ServerTangibleObjectTemplate::~ServerTangibleObjectTemplate() { -//@BEGIN TFD CLEANUP + //@BEGIN TFD CLEANUP { std::vector::iterator iter; for (iter = m_triggerVolumes.begin(); iter != m_triggerVolumes.end(); ++iter) @@ -57,7 +57,7 @@ ServerTangibleObjectTemplate::~ServerTangibleObjectTemplate() } m_triggerVolumes.clear(); } -//@END TFD CLEANUP + //@END TFD CLEANUP } // ServerTangibleObjectTemplate::~ServerTangibleObjectTemplate /** @@ -186,8 +186,6 @@ size_t ServerTangibleObjectTemplate::getTriggerVolumesCount(void) const ServerTangibleObjectTemplate::CombatSkeleton ServerTangibleObjectTemplate::getCombatSkeleton() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -215,8 +213,6 @@ ServerTangibleObjectTemplate::CombatSkeleton ServerTangibleObjectTemplate::getCo int ServerTangibleObjectTemplate::getMaxHitPoints() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -266,8 +262,6 @@ int ServerTangibleObjectTemplate::getMaxHitPoints() const int ServerTangibleObjectTemplate::getMaxHitPointsMin() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -317,8 +311,6 @@ int ServerTangibleObjectTemplate::getMaxHitPointsMin() const int ServerTangibleObjectTemplate::getMaxHitPointsMax() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -394,15 +386,13 @@ const ServerArmorTemplate * ServerTangibleObjectTemplate::getArmor() const { returnValue = dynamic_cast(ObjectTemplateList::fetch(templateName)); if (returnValue == nullptr) - WARNING_STRICT_FATAL(true, ("Error loading template %s",templateName.c_str())); + WARNING_STRICT_FATAL(true, ("Error loading template %s", templateName.c_str())); } return returnValue; } // ServerTangibleObjectTemplate::getArmor int ServerTangibleObjectTemplate::getInterestRadius() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -452,8 +442,6 @@ int ServerTangibleObjectTemplate::getInterestRadius() const int ServerTangibleObjectTemplate::getInterestRadiusMin() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -503,8 +491,6 @@ int ServerTangibleObjectTemplate::getInterestRadiusMin() const int ServerTangibleObjectTemplate::getInterestRadiusMax() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -554,8 +540,6 @@ int ServerTangibleObjectTemplate::getInterestRadiusMax() const int ServerTangibleObjectTemplate::getCount() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -605,8 +589,6 @@ int ServerTangibleObjectTemplate::getCount() const int ServerTangibleObjectTemplate::getCountMin() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -656,8 +638,6 @@ int ServerTangibleObjectTemplate::getCountMin() const int ServerTangibleObjectTemplate::getCountMax() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -707,8 +687,6 @@ int ServerTangibleObjectTemplate::getCountMax() const int ServerTangibleObjectTemplate::getCondition() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -758,8 +736,6 @@ int ServerTangibleObjectTemplate::getCondition() const int ServerTangibleObjectTemplate::getConditionMin() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -809,8 +785,6 @@ int ServerTangibleObjectTemplate::getConditionMin() const int ServerTangibleObjectTemplate::getConditionMax() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -860,8 +834,6 @@ int ServerTangibleObjectTemplate::getConditionMax() const bool ServerTangibleObjectTemplate::getWantSawAttackTriggers() const { - - const ServerTangibleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -887,7 +859,6 @@ bool ServerTangibleObjectTemplate::getWantSawAttackTriggers() const return value; } // ServerTangibleObjectTemplate::getWantSawAttackTriggers - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -896,8 +867,8 @@ bool ServerTangibleObjectTemplate::getWantSawAttackTriggers() const */ void ServerTangibleObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerTangibleObjectTemplate_tag) { @@ -907,7 +878,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -927,10 +898,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,4)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 4)) { - - m_versionOk = false; } @@ -985,4 +954,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerTangibleObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerUniverseObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerUniverseObjectTemplate.cpp index bf4eafdd..eb9194d0 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerUniverseObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerUniverseObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerUniverseObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerUniverseObjectTemplate::ServerUniverseObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerUniverseObjectTemplate::ServerUniverseObjectTemplate @@ -44,8 +44,8 @@ ServerUniverseObjectTemplate::ServerUniverseObjectTemplate(const std::string & f */ ServerUniverseObjectTemplate::~ServerUniverseObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerUniverseObjectTemplate::~ServerUniverseObjectTemplate /** @@ -121,8 +121,8 @@ Object * ServerUniverseObjectTemplate::createObject(void) const */ void ServerUniverseObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerUniverseObjectTemplate_tag) { @@ -132,7 +132,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -152,10 +152,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -173,4 +171,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerUniverseObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerVehicleObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerVehicleObjectTemplate.cpp index fc9605f8..0ee8b18c 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerVehicleObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerVehicleObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerVehicleObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerVehicleObjectTemplate::ServerVehicleObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerTangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerVehicleObjectTemplate::ServerVehicleObjectTemplate @@ -44,8 +44,8 @@ ServerVehicleObjectTemplate::ServerVehicleObjectTemplate(const std::string & fil */ ServerVehicleObjectTemplate::~ServerVehicleObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerVehicleObjectTemplate::~ServerVehicleObjectTemplate /** @@ -114,8 +114,6 @@ Object * ServerVehicleObjectTemplate::createObject(void) const //@BEGIN TFD const std::string & ServerVehicleObjectTemplate::getFuelType() const { - - const ServerVehicleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -143,8 +141,6 @@ const std::string & ServerVehicleObjectTemplate::getFuelType() const float ServerVehicleObjectTemplate::getCurrentFuel() const { - - const ServerVehicleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -194,8 +190,6 @@ float ServerVehicleObjectTemplate::getCurrentFuel() const float ServerVehicleObjectTemplate::getCurrentFuelMin() const { - - const ServerVehicleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -245,8 +239,6 @@ float ServerVehicleObjectTemplate::getCurrentFuelMin() const float ServerVehicleObjectTemplate::getCurrentFuelMax() const { - - const ServerVehicleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -296,8 +288,6 @@ float ServerVehicleObjectTemplate::getCurrentFuelMax() const float ServerVehicleObjectTemplate::getMaxFuel() const { - - const ServerVehicleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -347,8 +337,6 @@ float ServerVehicleObjectTemplate::getMaxFuel() const float ServerVehicleObjectTemplate::getMaxFuelMin() const { - - const ServerVehicleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -398,8 +386,6 @@ float ServerVehicleObjectTemplate::getMaxFuelMin() const float ServerVehicleObjectTemplate::getMaxFuelMax() const { - - const ServerVehicleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -449,8 +435,6 @@ float ServerVehicleObjectTemplate::getMaxFuelMax() const float ServerVehicleObjectTemplate::getConsumpsion() const { - - const ServerVehicleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -500,8 +484,6 @@ float ServerVehicleObjectTemplate::getConsumpsion() const float ServerVehicleObjectTemplate::getConsumpsionMin() const { - - const ServerVehicleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -551,8 +533,6 @@ float ServerVehicleObjectTemplate::getConsumpsionMin() const float ServerVehicleObjectTemplate::getConsumpsionMax() const { - - const ServerVehicleObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -600,7 +580,6 @@ float ServerVehicleObjectTemplate::getConsumpsionMax() const return value; } // ServerVehicleObjectTemplate::getConsumpsionMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -609,8 +588,8 @@ float ServerVehicleObjectTemplate::getConsumpsionMax() const */ void ServerVehicleObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerVehicleObjectTemplate_tag) { @@ -620,7 +599,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -640,10 +619,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,0,0)) + if (getHighestTemplateVersion() != TAG(0, 0, 0, 0)) { - - m_versionOk = false; } @@ -673,4 +650,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerVehicleObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/objectTemplate/ServerWeaponObjectTemplate.cpp b/engine/server/library/serverGame/src/shared/objectTemplate/ServerWeaponObjectTemplate.cpp index 973ac20e..ee19eb9c 100755 --- a/engine/server/library/serverGame/src/shared/objectTemplate/ServerWeaponObjectTemplate.cpp +++ b/engine/server/library/serverGame/src/shared/objectTemplate/ServerWeaponObjectTemplate.cpp @@ -22,20 +22,20 @@ const std::string DefaultString(""); const StringId DefaultStringId("", 0); -const Vector DefaultVector(0,0,0); +const Vector DefaultVector(0, 0, 0); const TriggerVolumeData DefaultTriggerVolumeData; bool ServerWeaponObjectTemplate::ms_allowDefaultTemplateParams = true; - /** * Class constructor. */ ServerWeaponObjectTemplate::ServerWeaponObjectTemplate(const std::string & filename) //@BEGIN TFD INIT : ServerTangibleObjectTemplate(filename) - ,m_versionOk(true) -//@END TFD INIT + , m_versionOk(true) + , m_templateVersion(0) + //@END TFD INIT { } // ServerWeaponObjectTemplate::ServerWeaponObjectTemplate @@ -44,8 +44,8 @@ ServerWeaponObjectTemplate::ServerWeaponObjectTemplate(const std::string & filen */ ServerWeaponObjectTemplate::~ServerWeaponObjectTemplate() { -//@BEGIN TFD CLEANUP -//@END TFD CLEANUP + //@BEGIN TFD CLEANUP + //@END TFD CLEANUP } // ServerWeaponObjectTemplate::~ServerWeaponObjectTemplate /** @@ -114,8 +114,6 @@ Object * ServerWeaponObjectTemplate::createObject(void) const //@BEGIN TFD ServerWeaponObjectTemplate::WeaponType ServerWeaponObjectTemplate::getWeaponType() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -143,8 +141,6 @@ ServerWeaponObjectTemplate::WeaponType ServerWeaponObjectTemplate::getWeaponType ServerWeaponObjectTemplate::AttackType ServerWeaponObjectTemplate::getAttackType() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -172,8 +168,6 @@ ServerWeaponObjectTemplate::AttackType ServerWeaponObjectTemplate::getAttackType ServerWeaponObjectTemplate::DamageType ServerWeaponObjectTemplate::getDamageType() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -201,8 +195,6 @@ ServerWeaponObjectTemplate::DamageType ServerWeaponObjectTemplate::getDamageType ServerWeaponObjectTemplate::DamageType ServerWeaponObjectTemplate::getElementalType() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -230,8 +222,6 @@ ServerWeaponObjectTemplate::DamageType ServerWeaponObjectTemplate::getElementalT int ServerWeaponObjectTemplate::getElementalValue() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -281,8 +271,6 @@ int ServerWeaponObjectTemplate::getElementalValue() const int ServerWeaponObjectTemplate::getElementalValueMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -332,8 +320,6 @@ int ServerWeaponObjectTemplate::getElementalValueMin() const int ServerWeaponObjectTemplate::getElementalValueMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -383,8 +369,6 @@ int ServerWeaponObjectTemplate::getElementalValueMax() const int ServerWeaponObjectTemplate::getMinDamageAmount() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -434,8 +418,6 @@ int ServerWeaponObjectTemplate::getMinDamageAmount() const int ServerWeaponObjectTemplate::getMinDamageAmountMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -485,8 +467,6 @@ int ServerWeaponObjectTemplate::getMinDamageAmountMin() const int ServerWeaponObjectTemplate::getMinDamageAmountMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -536,8 +516,6 @@ int ServerWeaponObjectTemplate::getMinDamageAmountMax() const int ServerWeaponObjectTemplate::getMaxDamageAmount() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -587,8 +565,6 @@ int ServerWeaponObjectTemplate::getMaxDamageAmount() const int ServerWeaponObjectTemplate::getMaxDamageAmountMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -638,8 +614,6 @@ int ServerWeaponObjectTemplate::getMaxDamageAmountMin() const int ServerWeaponObjectTemplate::getMaxDamageAmountMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -689,8 +663,6 @@ int ServerWeaponObjectTemplate::getMaxDamageAmountMax() const float ServerWeaponObjectTemplate::getAttackSpeed() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -740,8 +712,6 @@ float ServerWeaponObjectTemplate::getAttackSpeed() const float ServerWeaponObjectTemplate::getAttackSpeedMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -791,8 +761,6 @@ float ServerWeaponObjectTemplate::getAttackSpeedMin() const float ServerWeaponObjectTemplate::getAttackSpeedMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -842,8 +810,6 @@ float ServerWeaponObjectTemplate::getAttackSpeedMax() const float ServerWeaponObjectTemplate::getAudibleRange() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -893,8 +859,6 @@ float ServerWeaponObjectTemplate::getAudibleRange() const float ServerWeaponObjectTemplate::getAudibleRangeMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -944,8 +908,6 @@ float ServerWeaponObjectTemplate::getAudibleRangeMin() const float ServerWeaponObjectTemplate::getAudibleRangeMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -995,8 +957,6 @@ float ServerWeaponObjectTemplate::getAudibleRangeMax() const float ServerWeaponObjectTemplate::getMinRange() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1046,8 +1006,6 @@ float ServerWeaponObjectTemplate::getMinRange() const float ServerWeaponObjectTemplate::getMinRangeMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1097,8 +1055,6 @@ float ServerWeaponObjectTemplate::getMinRangeMin() const float ServerWeaponObjectTemplate::getMinRangeMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1148,8 +1104,6 @@ float ServerWeaponObjectTemplate::getMinRangeMax() const float ServerWeaponObjectTemplate::getMaxRange() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1199,8 +1153,6 @@ float ServerWeaponObjectTemplate::getMaxRange() const float ServerWeaponObjectTemplate::getMaxRangeMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1250,8 +1202,6 @@ float ServerWeaponObjectTemplate::getMaxRangeMin() const float ServerWeaponObjectTemplate::getMaxRangeMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1301,8 +1251,6 @@ float ServerWeaponObjectTemplate::getMaxRangeMax() const float ServerWeaponObjectTemplate::getDamageRadius() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1352,8 +1300,6 @@ float ServerWeaponObjectTemplate::getDamageRadius() const float ServerWeaponObjectTemplate::getDamageRadiusMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1403,8 +1349,6 @@ float ServerWeaponObjectTemplate::getDamageRadiusMin() const float ServerWeaponObjectTemplate::getDamageRadiusMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1454,8 +1398,6 @@ float ServerWeaponObjectTemplate::getDamageRadiusMax() const float ServerWeaponObjectTemplate::getWoundChance() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1505,8 +1447,6 @@ float ServerWeaponObjectTemplate::getWoundChance() const float ServerWeaponObjectTemplate::getWoundChanceMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1556,8 +1496,6 @@ float ServerWeaponObjectTemplate::getWoundChanceMin() const float ServerWeaponObjectTemplate::getWoundChanceMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1607,8 +1545,6 @@ float ServerWeaponObjectTemplate::getWoundChanceMax() const int ServerWeaponObjectTemplate::getAttackCost() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1658,8 +1594,6 @@ int ServerWeaponObjectTemplate::getAttackCost() const int ServerWeaponObjectTemplate::getAttackCostMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1709,8 +1643,6 @@ int ServerWeaponObjectTemplate::getAttackCostMin() const int ServerWeaponObjectTemplate::getAttackCostMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1760,8 +1692,6 @@ int ServerWeaponObjectTemplate::getAttackCostMax() const int ServerWeaponObjectTemplate::getAccuracy() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1811,8 +1741,6 @@ int ServerWeaponObjectTemplate::getAccuracy() const int ServerWeaponObjectTemplate::getAccuracyMin() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1862,8 +1790,6 @@ int ServerWeaponObjectTemplate::getAccuracyMin() const int ServerWeaponObjectTemplate::getAccuracyMax() const { - - const ServerWeaponObjectTemplate * base = nullptr; if (m_baseData != nullptr) { @@ -1911,7 +1837,6 @@ int ServerWeaponObjectTemplate::getAccuracyMax() const return value; } // ServerWeaponObjectTemplate::getAccuracyMax - /** * Loads the template data from an iff file. We should already be in the form * for this template. @@ -1920,8 +1845,8 @@ int ServerWeaponObjectTemplate::getAccuracyMax() const */ void ServerWeaponObjectTemplate::load(Iff &file) { -static const int MAX_NAME_SIZE = 256; -char paramName[MAX_NAME_SIZE]; + static const int MAX_NAME_SIZE = 256; + char paramName[MAX_NAME_SIZE]; if (file.getCurrentName() != ServerWeaponObjectTemplate_tag) { @@ -1931,7 +1856,7 @@ char paramName[MAX_NAME_SIZE]; file.enterForm(); m_templateVersion = file.getCurrentName(); - if (m_templateVersion == TAG(D,E,R,V)) + if (m_templateVersion == TAG(D, E, R, V)) { file.enterForm(); file.enterChunk(); @@ -1951,10 +1876,8 @@ char paramName[MAX_NAME_SIZE]; file.exitForm(); m_templateVersion = file.getCurrentName(); } - if (getHighestTemplateVersion() != TAG(0,0,1,1)) + if (getHighestTemplateVersion() != TAG(0, 0, 1, 1)) { - - m_versionOk = false; } @@ -2006,4 +1929,4 @@ char paramName[MAX_NAME_SIZE]; return; } // ServerWeaponObjectTemplate::load -//@END TFD +//@END TFD \ No newline at end of file diff --git a/engine/shared/library/sharedNetworkMessages/src/shared/clientGameServer/MessageQueueDraftSlots.h b/engine/shared/library/sharedNetworkMessages/src/shared/clientGameServer/MessageQueueDraftSlots.h index 8514b2f3..4cb0740b 100755 --- a/engine/shared/library/sharedNetworkMessages/src/shared/clientGameServer/MessageQueueDraftSlots.h +++ b/engine/shared/library/sharedNetworkMessages/src/shared/clientGameServer/MessageQueueDraftSlots.h @@ -7,7 +7,6 @@ // //======================================================================== - #ifndef INCLUDED_MessageQueueDraftSlots_H #define INCLUDED_MessageQueueDraftSlots_H @@ -40,17 +39,17 @@ public: const Slot & getSlot(int index) const; typedef stdvector::fwd SlotVector; - const SlotVector & getSlots () const; - void setSlots (const SlotVector & sv); + const SlotVector & getSlots() const; + void setSlots(const SlotVector & sv); - void setManfSchemId (const NetworkId & id); - const NetworkId & getManfSchemId () const; + void setManfSchemId(const NetworkId & id); + const NetworkId & getManfSchemId() const; - void setPrototypeId (const NetworkId & id); - const NetworkId & getPrototypeId () const; + void setPrototypeId(const NetworkId & id); + const NetworkId & getPrototypeId() const; - void setVolume (int volume); - int getVolume () const; + void setVolume(int volume); + int getVolume() const; void setCanManufacture(bool canManufacture); bool canManufacture() const; @@ -64,15 +63,15 @@ private: bool m_canManufacture; }; - //---------------------------------------------------------------------- inline MessageQueueDraftSlots::MessageQueueDraftSlots(const NetworkId & toolId, const NetworkId & manfSchemId) : -m_slots (), -m_toolId (toolId), -m_manfSchemId (manfSchemId), -m_prototypeId (), -m_volume (1) + m_slots(), + m_toolId(toolId), + m_manfSchemId(manfSchemId), + m_prototypeId(), + m_volume(1), + m_canManufacture() { } @@ -107,56 +106,56 @@ inline const MessageQueueDraftSlots::Slot & MessageQueueDraftSlots::getSlot(int //---------------------------------------------------------------------- -inline void MessageQueueDraftSlots::setSlots (const SlotVector & sv) +inline void MessageQueueDraftSlots::setSlots(const SlotVector & sv) { m_slots = sv; } //---------------------------------------------------------------------- -inline const MessageQueueDraftSlots::SlotVector & MessageQueueDraftSlots::getSlots () const +inline const MessageQueueDraftSlots::SlotVector & MessageQueueDraftSlots::getSlots() const { return m_slots; } //---------------------------------------------------------------------- -inline void MessageQueueDraftSlots::setManfSchemId (const NetworkId & id) +inline void MessageQueueDraftSlots::setManfSchemId(const NetworkId & id) { m_manfSchemId = id; } //---------------------------------------------------------------------- -inline const NetworkId & MessageQueueDraftSlots::getManfSchemId () const +inline const NetworkId & MessageQueueDraftSlots::getManfSchemId() const { return m_manfSchemId; } //---------------------------------------------------------------------- -inline void MessageQueueDraftSlots::setPrototypeId (const NetworkId & id) +inline void MessageQueueDraftSlots::setPrototypeId(const NetworkId & id) { m_prototypeId = id; } //---------------------------------------------------------------------- -inline const NetworkId & MessageQueueDraftSlots::getPrototypeId () const +inline const NetworkId & MessageQueueDraftSlots::getPrototypeId() const { return m_prototypeId; } //---------------------------------------------------------------------- -inline void MessageQueueDraftSlots::setVolume (int volume) +inline void MessageQueueDraftSlots::setVolume(int volume) { m_volume = volume; } //---------------------------------------------------------------------- -inline int MessageQueueDraftSlots::getVolume () const +inline int MessageQueueDraftSlots::getVolume() const { return m_volume; } @@ -177,5 +176,4 @@ inline bool MessageQueueDraftSlots::canManufacture() const //---------------------------------------------------------------------- - #endif // INCLUDED_MessageQueueDraftSlots_H diff --git a/external/3rd/library/platform/projects/MonAPI2/MonitorAPI.cpp b/external/3rd/library/platform/projects/MonAPI2/MonitorAPI.cpp index cbe80abf..9c2994aa 100755 --- a/external/3rd/library/platform/projects/MonAPI2/MonitorAPI.cpp +++ b/external/3rd/library/platform/projects/MonAPI2/MonitorAPI.cpp @@ -10,46 +10,45 @@ // ********************************** DO NOT EDIT THIS FILE *********************************** // ********************************************************************************************** // ********************************************************************************************** -void set_bit( unsigned char p[], int bit){ p[bit >> 3] |= 1 << (bit & 0x7); } -void unset_bit(unsigned char p[], int bit){ p[bit >> 3] &= ~(1 << (bit & 0x7)); } -int get_bit( unsigned char p[], int bit){ return (p[bit >> 3] >> (bit & 0x7)) & 1; } -int ZEXPORT uncompress2( Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); - +void set_bit(unsigned char p[], int bit) { p[bit >> 3] |= 1 << (bit & 0x7); } +void unset_bit(unsigned char p[], int bit) { p[bit >> 3] &= ~(1 << (bit & 0x7)); } +int get_bit(unsigned char p[], int bit) { return (p[bit >> 3] >> (bit & 0x7)) & 1; } +int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); //////////////////////////////////////// // Player implementation //////////////////////////////////////// -MonitorObject::MonitorObject(UdpConnection *con,CMonitorData *_gamedata, char *passwd, char **addressList,bool _bprint) +MonitorObject::MonitorObject(UdpConnection *con, CMonitorData *_gamedata, char *passwd, char **addressList, bool _bprint) { - mbprint = _bprint; - mMonitorData = _gamedata; - mbAuthenticated = false; - mPasswd = passwd; - mAddressList = addressList; - mHierarchySent = false; - mSequence = 1; + mbprint = _bprint; + mMonitorData = _gamedata; + mbAuthenticated = false; + mPasswd = passwd; + mAddressList = addressList; + mHierarchySent = false; + mSequence = 1; mlastUpdateTime = 0; - mConnection = con; + mConnection = con; mConnection->AddRef(); mConnection->SetHandler(this); // Flag all the descriptions - mMark = new unsigned char [ (mMonitorData->DataMax()/8)+2]; - memset(mMark,0,(mMonitorData->DataMax()/8)+2); + mMark = new unsigned char[(mMonitorData->DataMax() / 8) + 2]; + memset(mMark, 0, (mMonitorData->DataMax() / 8) + 2); char hold[256]; - if( mbprint ) + if (mbprint) { - fprintf(stderr,"MONITOR API CONNECTED: %s:%d\n", - mConnection->GetDestinationIp().GetAddress(hold), + fprintf(stderr, "MONITOR API CONNECTED: %s:%d\n", + mConnection->GetDestinationIp().GetAddress(hold), mConnection->GetDestinationPort()); } } MonitorObject::~MonitorObject() { - delete [] mMark; + delete[] mMark; - if( mConnection ) + if (mConnection) { mConnection->SetHandler(nullptr); mConnection->Disconnect(); @@ -57,22 +56,22 @@ MonitorObject::~MonitorObject() } } -void MonitorObject::OnTerminated( UdpConnection * /* con */) +void MonitorObject::OnTerminated(UdpConnection * /* con */) { -char hold[214]; + char hold[214]; - if( mConnection ) + if (mConnection) { - if( mbprint ) + if (mbprint) { mConnection->GetDestinationIp().GetAddress(hold); - if( mbprint ) + if (mbprint) { - fprintf(stderr,"MONITOR API TERMINATE %s:%d %s - %s\n", - hold, + fprintf(stderr, "MONITOR API TERMINATE %s:%d %s - %s\n", + hold, mConnection->GetDestinationPort(), - UdpConnection::DisconnectReasonText( mConnection->GetDisconnectReason()), - UdpConnection::DisconnectReasonText( mConnection->GetOtherSideDisconnectReason())); + UdpConnection::DisconnectReasonText(mConnection->GetDisconnectReason()), + UdpConnection::DisconnectReasonText(mConnection->GetOtherSideDisconnectReason())); } } mConnection->SetHandler(nullptr); @@ -82,32 +81,30 @@ char hold[214]; } } - -void MonitorObject::OnRoutePacket( UdpConnection * con, const unsigned char *data, int dataLen) +void MonitorObject::OnRoutePacket(UdpConnection * con, const unsigned char *data, int dataLen) { - - if( dataLen < 6 ) + if (dataLen < 6) { - if( mbprint ) - fprintf(stderr,"MONITOR API: This should not happen, line %d\n",__LINE__); + if (mbprint) + fprintf(stderr, "MONITOR API: This should not happen, line %d\n", __LINE__); } simpleMessage msg(data); - if( con == nullptr ) + if (con == nullptr) { - if( mbprint) - fprintf(stderr,"MONITOR API: MonitorObject.OnRoutePacket, recived a nullptr connection.?\n"); + if (mbprint) + fprintf(stderr, "MONITOR API: MonitorObject.OnRoutePacket, recived a nullptr connection.?\n"); return; } // ************************* Login Process *************************** - if ( mbAuthenticated == false ) - { - if ( msg.getCommand() != MON_MSG_AUTH ) - return; + if (mbAuthenticated == false) + { + if (msg.getCommand() != MON_MSG_AUTH) + return; - if( processAuthRequest(data, dataLen) == false ) + if (processAuthRequest(data, dataLen) == false) return; mbAuthenticated = true; @@ -115,21 +112,20 @@ void MonitorObject::OnRoutePacket( UdpConnection * con, const unsigned char *da } // ************************* Process Commands *********************** - switch(msg.getCommand()) + switch (msg.getCommand()) { - - // *********************** Game Server Processing ****************** + // *********************** Game Server Processing ****************** case MON_MSG_QUERY_ELEMENTS: - if( mHierarchySent == true ) - { - mMonitorData->processElementsRequest(con,mSequence,(char *)&data[6],dataLen,mlastUpdateTime ); + if (mHierarchySent == true) + { + mMonitorData->processElementsRequest(con, mSequence, (char *)&data[6], dataLen, mlastUpdateTime); mlastUpdateTime = (long)time(nullptr); break; } // When the hierarchy has changed, fall through case MON_MSG_QUERY_HIERARCHY_BLOCK: - if( mMonitorData->processHierarchyRequestBlock(con,mSequence) == false) + if (mMonitorData->processHierarchyRequestBlock(con, mSequence) == false) { break; } @@ -137,7 +133,7 @@ void MonitorObject::OnRoutePacket( UdpConnection * con, const unsigned char *da break; case MON_MSG_QUERY_DESCRIPTION: - mMonitorData->processDescriptionRequest(con,mSequence,(char *)&data[6], dataLen,mMark); + mMonitorData->processDescriptionRequest(con, mSequence, (char *)&data[6], dataLen, mMark); break; case MON_MSG_ERROR: @@ -145,43 +141,41 @@ void MonitorObject::OnRoutePacket( UdpConnection * con, const unsigned char *da break; default: - fprintf(stderr,"MONITOR API: unknown message type received from client [%x]\n",msg.getCommand()); + fprintf(stderr, "MONITOR API: unknown message type received from client [%x]\n", msg.getCommand()); break; } } - bool MonitorObject::checkAddress(const char * address) { -int x = 0; - while( mAddressList[x] ) + int x = 0; + while (mAddressList[x]) { - if (strncmp(mAddressList[x], address, strlen(mAddressList[x]))== 0) + if (strncmp(mAddressList[x], address, strlen(mAddressList[x])) == 0) return true; x++; } return false; } -bool MonitorObject::checkPasswd( const char *passwd) +bool MonitorObject::checkPasswd(const char *passwd) { - if (strcmp(mPasswd,passwd)== 0 ) + if (strcmp(mPasswd, passwd) == 0) return true; - return false; + return false; } bool MonitorObject::processAuthRequest(const unsigned char * data, int /* dataLen */) { -char reply; -stringMessage strMsg(data); -char addBuff[16] = {0}; -char sendBuf[32]; -int len; - + char reply; + stringMessage strMsg(data); + char addBuff[16] = { 0 }; + char sendBuf[32]; + int len; reply = '1'; - - if ( checkAddress(mConnection->GetDestinationIp().GetAddress(addBuff)) == false) + + if (checkAddress(mConnection->GetDestinationIp().GetAddress(addBuff)) == false) { reply = '3'; } @@ -191,21 +185,21 @@ int len; } memset(sendBuf, 0, sizeof(sendBuf)); - + len = 0; - packShort( sendBuf + len, len,(short)MON_MSG_AUTHREPLY); - packShort( sendBuf + len, len, mSequence); - packShort( sendBuf + len, len,(short)3); - packShort( sendBuf + len, len,(short)CURRENT_API_VERSION); - packByte( sendBuf + len, len, reply); - - mConnection->Send(cUdpChannelReliable1, sendBuf, 9 ); + packShort(sendBuf + len, len, (short)MON_MSG_AUTHREPLY); + packShort(sendBuf + len, len, mSequence); + packShort(sendBuf + len, len, (short)3); + packShort(sendBuf + len, len, (short)CURRENT_API_VERSION); + packByte(sendBuf + len, len, reply); + + mConnection->Send(cUdpChannelReliable1, sendBuf, 9); return true; } -void MonitorObject::DescriptionMark(int x,int mode) +void MonitorObject::DescriptionMark(int x, int mode) { - if( mode == 0 ) set_bit(mMark,x); else unset_bit(mMark,x); + if (mode == 0) set_bit(mMark, x); else unset_bit(mMark, x); } char * getErrorString(unsigned short errorCode) @@ -240,7 +234,6 @@ char * getErrorString(unsigned short errorCode) case INVALID_ERROR_CODE: return "Received invalid error message"; - } } return "Undefined error code"; @@ -250,7 +243,7 @@ bool MonitorObject::processError(const unsigned char * data) { stringMessage strMsg(data); unsigned short errCode = (unsigned short)atoi(strMsg.getData()); - fprintf(stderr,"MONITOR API Error: %s\n", getErrorString(errCode)); + fprintf(stderr, "MONITOR API Error: %s\n", getErrorString(errCode)); return true; } @@ -261,46 +254,46 @@ MonitorManager::MonitorManager(const char *configFile, CMonitorData *_gamedata, { mManager = manager; mbprint = _bprint; - passString = nullptr; + passString = nullptr; mMonitorData = _gamedata; mObjectCount = 0; - for(int x=0;xSetHandler(nullptr); con->Disconnect(); con->Release(); } - if( mbprint ) - fprintf(stderr,"MonitorAPI: Collector connection reached max (%d).\n",CONNECTION_MAX); + if (mbprint) + fprintf(stderr, "MonitorAPI: Collector connection reached max (%d).\n", CONNECTION_MAX); return; } - - AddObject(new MonitorObject(con,mMonitorData,passString,allowedAddressList,mbprint)); + + AddObject(new MonitorObject(con, mMonitorData, passString, allowedAddressList, mbprint)); } void MonitorManager::AddObject(MonitorObject *Object) @@ -313,8 +306,8 @@ void MonitorManager::GiveTime() // check if the monitor object is no longer connected for (int i = 0; i < mObjectCount; i++) { - if( mObject[i]->mConnection == nullptr || - mObject[i]->mConnection->GetStatus() == UdpConnection::cStatusDisconnected ) + if (mObject[i]->mConnection == nullptr || + mObject[i]->mConnection->GetStatus() == UdpConnection::cStatusDisconnected) { MonitorObject *o = mObject[i]; mObjectCount--; @@ -331,32 +324,31 @@ void MonitorManager::HierarchyChanged() mObject[i]->HeirarchyChanged(); } -void MonitorManager::DescriptionMark(int x ,int mode) +void MonitorManager::DescriptionMark(int x, int mode) { for (int i = 0; i < mObjectCount; i++) - mObject[i]->DescriptionMark(x,mode); + mObject[i]->DescriptionMark(x, mode); } bool MonitorManager::loadAuthData(const char * filename) { -int nline; -int len; -int x; -char buffer[1024]; + int nline; + int len; + int x; + char buffer[1024]; - FILE *fp = fopen(filename,"r"); + FILE *fp = fopen(filename, "r"); if (fp == nullptr) { - fprintf(stderr,"Monitor API: could not open %s file\nTHIS FILE IS REQUIRED.\n", filename); + fprintf(stderr, "Monitor API: could not open %s file\nTHIS FILE IS REQUIRED.\n", filename); return false; } - + free(passString); - - for(x=0;x 0 ) + if (len > 0) { - if( nline == 0 ) + if (nline == 0) { - passString = (char *)malloc( len + 1 ); - strcpy(passString,buffer); + passString = (char *)malloc(len + 1); + strcpy(passString, buffer); } else { - allowedAddressList[x] = (char *)malloc( len + 1 ); - strcpy(allowedAddressList[x],buffer); + allowedAddressList[x] = (char *)malloc(len + 1); + strcpy(allowedAddressList[x], buffer); x++; } } nline++; - } + } } // clean up fclose(fp); @@ -398,40 +390,40 @@ char buffer[1024]; // ****************************************************************************************************** // ****************************************************************************************************** -CMonitorAPI::CMonitorAPI( const char *configFile, unsigned short Port, bool _bprint , char *address, UdpManager * mang ) +CMonitorAPI::CMonitorAPI(const char *configFile, unsigned short Port, bool _bprint, char *address, UdpManager * mang) { mbprint = _bprint; mPort = Port; mAddress = nullptr; - if( address ) + if (address) { - mAddress = (char *)malloc(strlen(address)+1); - strcpy(mAddress,address); + mAddress = (char *)malloc(strlen(address) + 1); + strcpy(mAddress, address); } - if( mang == nullptr ) + if (mang == nullptr) { UdpManager::Params params; - params.handler = nullptr; - params.maxConnections = CONNECTION_MAX; + params.handler = nullptr; + params.maxConnections = CONNECTION_MAX; params.outgoingBufferSize = 1000000; - params.noDataTimeout = 130000; + params.noDataTimeout = 130000; params.oldestUnacknowledgedTimeout = 120000; params.processIcmpErrors = false; - params.port = mPort; - mManager = new UdpManager(¶ms); - mMonitorData = new CMonitorData(); + params.port = mPort; + mManager = new UdpManager(¶ms); + mMonitorData = new CMonitorData(); } - - mObjectManager = new MonitorManager(configFile,mMonitorData,mManager,mbprint); + + mObjectManager = new MonitorManager(configFile, mMonitorData, mManager, mbprint); mManager->SetHandler(mObjectManager); - if( mbprint ) - fprintf(stderr,"MonitorAPI: started on port->%d\n",mPort); + if (mbprint) + fprintf(stderr, "MonitorAPI: started on port->%d\n", mPort); } - + CMonitorAPI::~CMonitorAPI() { free(mAddress); @@ -441,127 +433,123 @@ CMonitorAPI::~CMonitorAPI() mManager->Release(); delete mMonitorData; - } void CMonitorAPI::Update() { - if( mManager ) + if (mManager) mManager->GiveTime(); - if( mObjectManager ) + if (mObjectManager) mObjectManager->GiveTime(); } -int CMonitorAPI::add(const char *label, int id, int ping, const char *des ) -{ -int rnt; +int CMonitorAPI::add(const char *label, int id, int ping, const char *des) +{ + int rnt; - rnt = mMonitorData->add(label,id,ping,des); - if( rnt ) + rnt = mMonitorData->add(label, id, ping, des); + if (rnt) mObjectManager->HierarchyChanged(); - return rnt; + return rnt; } void CMonitorAPI::remove(int Id) -{ - mMonitorData->remove(Id); +{ + mMonitorData->remove(Id); mObjectManager->HierarchyChanged(); } -void CMonitorAPI::setDescription( int Id, const char *Description ) +void CMonitorAPI::setDescription(int Id, const char *Description) { -int x; -int mode; - - x = mMonitorData->setDescription(Id,Description,mode); - if( x == -1 ) + int x; + int mode; + + x = mMonitorData->setDescription(Id, Description, mode); + if (x == -1) return; - mObjectManager->DescriptionMark(x,mode); + mObjectManager->DescriptionMark(x, mode); } -void CMonitorAPI::dump(){ mMonitorData->dump(); } +void CMonitorAPI::dump() { mMonitorData->dump(); } //---------------------------------------------------------------- -monMessage::monMessage():command(0),sequence(0),size(0){} +monMessage::monMessage() :command(0), sequence(0), size(0) {} //---------------------------------------------------------------- -monMessage::monMessage(short cmd,short seq,short s):command(cmd),sequence(seq),size(s){} +monMessage::monMessage(short cmd, short seq, short s) : command(cmd), sequence(seq), size(s) {} //---------------------------------------------------------------- -monMessage::monMessage(const unsigned char * source):command(0),sequence(0),size(0) -{ -int len; +monMessage::monMessage(const unsigned char * source) : command(0), sequence(0), size(0) +{ + int len; len = 0; - unpackShort( (char *)source + len, len,command); - unpackShort( (char *)source + len, len,sequence); - unpackShort( (char *)source + len, len,size); + unpackShort((char *)source + len, len, command); + unpackShort((char *)source + len, len, sequence); + unpackShort((char *)source + len, len, size); } //---------------------------------------------------------------- // monMessage::monMessage(const monMessage ©):command(copy.command),sequence(copy.sequence),size(copy.size){} - - //---------------------------------------------------------------- -stringMessage::stringMessage(const unsigned char * source):monMessage(source) +stringMessage::stringMessage(const unsigned char * source) :monMessage(source) { -int size; + int size; - size = (int)strlen((char *)source+6) +1; - data = new char [ size ]; - strcpy(data,(char *)source+6); // Add six for the size of the header + size = (int)strlen((char *)source + 6) + 1; + data = new char[size]; + strcpy(data, (char *)source + 6); // Add six for the size of the header } //---------------------------------------------------------------- -stringMessage::stringMessage(const unsigned short command,const unsigned short sequence,const unsigned short size,char * newData): -monMessage(command, sequence, size) +stringMessage::stringMessage(const unsigned short command, const unsigned short sequence, const unsigned short size, char * newData) : + monMessage(command, sequence, size) { - data = new char [strlen(newData) + 1]; + data = new char[strlen(newData) + 1]; strncpy(data, newData, strlen(newData + 1)); } //---------------------------------------------------------------- stringMessage::~stringMessage() { - delete [] data; + delete[] data; data = 0; } //---------------------------------------------------------------- authReplyMessage::authReplyMessage(const unsigned char * source) : -monMessage(source) + monMessage(source) { int len = 6; - unpackShort((char *)source+len,len,version); - unpackByte((char *)source+len,len,data); + unpackShort((char *)source + len, len, version); + unpackByte((char *)source + len, len, data); } //---------------------------------------------------------------- -authReplyMessage::authReplyMessage(const unsigned short command, - const unsigned short sequence, - const unsigned short size, - unsigned char newData): -monMessage(command, sequence, size),data(newData){} - +authReplyMessage::authReplyMessage(const unsigned short command, + const unsigned short sequence, + const unsigned short size, + unsigned char newData) : + monMessage(command, sequence, size), data(newData), version() {} //---------------------------------------------------------------- dataReplyMessage::dataReplyMessage(const unsigned char * source) : -monMessage(source) + monMessage(source) { - data = new unsigned char[getSize()+1]; + data = new unsigned char[getSize() + 1]; memcpy(data, source + 6, getSize()); data[getSize()] = 0; } //---------------------------------------------------------------- -dataReplyMessage::dataReplyMessage(const unsigned short command, - const unsigned short sequence, - const unsigned short size, - unsigned char * newData, - int newDataLen): -monMessage(command, sequence, size) +dataReplyMessage::dataReplyMessage(const unsigned short command, + const unsigned short sequence, + const unsigned short size, + unsigned char * newData, + int newDataLen) : + monMessage(command, sequence, size) { data = new unsigned char[newDataLen]; memcpy(data, newData, newDataLen); @@ -570,51 +558,46 @@ monMessage(command, sequence, size) //---------------------------------------------------------------- dataReplyMessage::~dataReplyMessage() { - delete [] data; + delete[] data; data = 0; } //---------------------------------------------------------------- -simpleMessage::simpleMessage(const unsigned char * source):monMessage(source){} +simpleMessage::simpleMessage(const unsigned char * source) :monMessage(source) {} //---------------------------------------------------------------- -simpleMessage::simpleMessage(const unsigned short command, - const unsigned short sequence, - const unsigned short size): -monMessage(command, sequence, size){} +simpleMessage::simpleMessage(const unsigned short command, + const unsigned short sequence, + const unsigned short size) : + monMessage(command, sequence, size) {} //---------------------------------------------------------------- -simpleMessage::~simpleMessage(){} +simpleMessage::~simpleMessage() {} //---------------------------------------------------------------- - //---------------------------------------------------------------- dataBlockReplyMessage::dataBlockReplyMessage(const unsigned char * source) : -monMessage(source) + monMessage(source) { -int err; -unsigned long S = 4000000; -unsigned char *p; + int err; + unsigned long S = 4000000; + unsigned char *p; data = nullptr; p = (unsigned char *)malloc(4000000); - memset(p,0,4000000); - err = uncompress(p,&S,(source+6),(long)getSize()); - if( Z_OK != err ) { free(p);return; } - data = new unsigned char[S+1]; - memcpy(data,p,S); + memset(p, 0, 4000000); + err = uncompress(p, &S, (source + 6), (long)getSize()); + if (Z_OK != err) { free(p); return; } + data = new unsigned char[S + 1]; + memcpy(data, p, S); setSize((unsigned short)S); free(p); } //---------------------------------------------------------------- dataBlockReplyMessage::~dataBlockReplyMessage() { - if (data) - { - delete [] data; - data = 0; - } -} - - - - + if (data) + { + delete[] data; + data = 0; + } +} \ No newline at end of file diff --git a/external/3rd/library/soePlatform/CSAssist/utils/Base/AutoLog.h b/external/3rd/library/soePlatform/CSAssist/utils/Base/AutoLog.h index 18871c7f..0386b26e 100755 --- a/external/3rd/library/soePlatform/CSAssist/utils/Base/AutoLog.h +++ b/external/3rd/library/soePlatform/CSAssist/utils/Base/AutoLog.h @@ -6,110 +6,109 @@ #include #ifdef EXTERNAL_DISTRO -namespace NAMESPACE +namespace NAMESPACE { - #endif -namespace Base -{ + namespace Base + { + class CAutoLog + { + public: + enum eLogLevel { + eLOG_NONE = 0, // log entries are discarded + eLOG_ERROR = 1, // log errors only + eLOG_ALERT = 2, // log alerts and errors only + eLOG_NORMAL = 3, // log all normal events, no debug + eLOG_DEBUG = 4 // log everything + }; - class CAutoLog - { - public: - enum eLogLevel { - eLOG_NONE = 0, // log entries are discarded - eLOG_ERROR = 1, // log errors only - eLOG_ALERT = 2, // log alerts and errors only - eLOG_NORMAL = 3, // log all normal events, no debug - eLOG_DEBUG = 4 // log everything - }; + // Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_NORMAL. + void SetLogLevel(eLogLevel loglevel); - // Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_NORMAL. - void SetLogLevel(eLogLevel loglevel); + // Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR. + void SetPrintLevel(eLogLevel printlevel); - // Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR. - void SetPrintLevel(eLogLevel printlevel); + // Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR. + void SetFlushLevel(eLogLevel flushlevel); - // Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR. - void SetFlushLevel(eLogLevel flushlevel); + // constructor, no file loaded + CAutoLog(); - // constructor, no file loaded - CAutoLog(); + // version of constructor that calls Open(file) + CAutoLog(const char * file); - // version of constructor that calls Open(file) - CAutoLog(const char * file); + // destructor, will close file if opened + ~CAutoLog(); - // destructor, will close file if opened - ~CAutoLog(); + // Open log file. If a file is already open, function will fail. + // returns true if no error + bool Open(const char * file); - // Open log file. If a file is already open, function will fail. - // returns true if no error - bool Open(const char * file); + // Close log file if opened. + void Close(void); - // Close log file if opened. - void Close(void); + // Make an entry in the log. Format and variable arguments are identical to printf. + // severity will be compared to master log level to determine if the log entry will be made + // severity will be compared to master print level to determine if the log entry will be printed to stdout + void Log(eLogLevel severity, char * format, ...); - // Make an entry in the log. Format and variable arguments are identical to printf. - // severity will be compared to master log level to determine if the log entry will be made - // severity will be compared to master print level to determine if the log entry will be printed to stdout - void Log(eLogLevel severity, char * format, ...); + // Equivalent to the above with the approriate severity argument + void LogError(char * format, ...); + void LogAlert(char * format, ...); + void Log(char * format, ...); + void LogDebug(char * format, ...); - // Equivalent to the above with the approriate severity argument - void LogError(char * format, ...); - void LogAlert(char * format, ...); - void Log(char * format, ...); - void LogDebug(char * format, ...); + private: + FILE * pFile; // current log file opened + char * pFilename; // current log file opened + int nTodaysDayOfYear; // remember the current day to detect change of day + void Archive(void); // archives current log - private: - FILE * pFile; // current log file opened - char * pFilename; // current log file opened - int nTodaysDayOfYear; // remember the current day to detect change of day - void Archive(void); // archives current log + static eLogLevel nLogMask; // master severity level + static eLogLevel nPrintMask; // master severity level + static eLogLevel nFlushMask; // master severity level + }; - static eLogLevel nLogMask; // master severity level - static eLogLevel nPrintMask; // master severity level - static eLogLevel nFlushMask; // master severity level - }; + //------------------------------------- + inline void CAutoLog::SetLogLevel(eLogLevel loglevel) + { + nLogMask = loglevel; + } - //------------------------------------- - inline void CAutoLog::SetLogLevel(eLogLevel loglevel) - { - nLogMask = loglevel; - } + //------------------------------------- + inline void CAutoLog::SetPrintLevel(eLogLevel printlevel) + { + nPrintMask = printlevel; + } - //------------------------------------- - inline void CAutoLog::SetPrintLevel(eLogLevel printlevel) - { - nPrintMask = printlevel; - } + //------------------------------------- + inline void CAutoLog::SetFlushLevel(eLogLevel flushlevel) + { + nFlushMask = flushlevel; + } - //------------------------------------- - inline void CAutoLog::SetFlushLevel(eLogLevel flushlevel) - { - nFlushMask = flushlevel; - } + //------------------------------------- + inline CAutoLog::CAutoLog() + { + pFilename = nullptr; + pFile = (FILE *)-1; + nTodaysDayOfYear = 0; + } - //------------------------------------- - inline CAutoLog::CAutoLog() - { - pFilename = nullptr; - pFile = (FILE *)-1; - } + //------------------------------------- + inline CAutoLog::CAutoLog(const char * file) + { + pFilename = nullptr; + pFile = (FILE *)-1; + Open(file); + } - //------------------------------------- - inline CAutoLog::CAutoLog(const char * file) - { - pFilename = nullptr; - pFile = (FILE *)-1; - Open(file); - } - - //------------------------------------- - inline CAutoLog::~CAutoLog() - { - Close(); - } -}; + //------------------------------------- + inline CAutoLog::~CAutoLog() + { + Close(); + } + }; #ifdef EXTERNAL_DISTRO }; #endif diff --git a/external/3rd/library/soePlatform/CSAssist/utils/TcpLibrary/TcpManager.cpp b/external/3rd/library/soePlatform/CSAssist/utils/TcpLibrary/TcpManager.cpp index 86778910..2073fc8f 100755 --- a/external/3rd/library/soePlatform/CSAssist/utils/TcpLibrary/TcpManager.cpp +++ b/external/3rd/library/soePlatform/CSAssist/utils/TcpLibrary/TcpManager.cpp @@ -4,731 +4,707 @@ #include "TcpConnection.h" #ifndef WIN32 - #include +#include #endif - #ifdef EXTERNAL_DISTRO -namespace NAMESPACE +namespace NAMESPACE { #endif -TcpManager::TcpParams::TcpParams() -: port(0), - maxConnections(10), - incomingBufferSize(64*1024), - outgoingBufferSize(64*1024), - allocatorBlockSize(8*1024), - allocatorBlockCount(16), - maxRecvMessageSize(0), - keepAliveDelay(0), - noDataTimeout(0) -{ - memset(bindAddress, 0, sizeof(bindAddress)); -} + TcpManager::TcpParams::TcpParams() + : port(0), + maxConnections(10), + incomingBufferSize(64 * 1024), + outgoingBufferSize(64 * 1024), + allocatorBlockSize(8 * 1024), + allocatorBlockCount(16), + maxRecvMessageSize(0), + keepAliveDelay(0), + noDataTimeout(0) + { + memset(bindAddress, 0, sizeof(bindAddress)); + } -TcpManager::TcpParams::TcpParams(const TcpParams &cpy) -: port(cpy.port), - maxConnections(cpy.maxConnections), - incomingBufferSize(cpy.incomingBufferSize), - outgoingBufferSize(cpy.outgoingBufferSize), - allocatorBlockSize(cpy.allocatorBlockSize), - allocatorBlockCount(cpy.allocatorBlockCount), - maxRecvMessageSize(cpy.maxRecvMessageSize), - keepAliveDelay(cpy.keepAliveDelay), - noDataTimeout(cpy.noDataTimeout) -{ -} + TcpManager::TcpParams::TcpParams(const TcpParams &cpy) + : port(cpy.port), + maxConnections(cpy.maxConnections), + incomingBufferSize(cpy.incomingBufferSize), + outgoingBufferSize(cpy.outgoingBufferSize), + allocatorBlockSize(cpy.allocatorBlockSize), + allocatorBlockCount(cpy.allocatorBlockCount), + maxRecvMessageSize(cpy.maxRecvMessageSize), + keepAliveDelay(cpy.keepAliveDelay), + noDataTimeout(cpy.noDataTimeout) + { + } -TcpManager::TcpManager(const TcpParams ¶ms) -: m_handler(nullptr), - m_keepAliveList(nullptr, 1), - m_aliveList(nullptr, 2), - m_noDataList(nullptr, 1), - m_dataList(nullptr, 2), - m_params(params), - m_refCount(1), - m_connectionList(nullptr), - m_connectionListCount(0), - m_socket(INVALID_SOCKET), - m_boundAsServer(false), - m_allocator(params.allocatorBlockSize, params.allocatorBlockCount), - m_keepAliveTimer(), - m_noDataTimer() -{ - if (params.keepAliveDelay > 0) - m_keepAliveTimer.start(); - - if (params.noDataTimeout > 0) - m_noDataTimer.start(); - -#if defined(WIN32) - WSADATA wsaData; - WSAStartup(MAKEWORD(1,1), &wsaData); - - FD_ZERO(&m_permfds);//select only used on win32 -#endif - -} - - -TcpManager::~TcpManager() -{ -#if defined(WIN32) - WSACleanup(); -#endif - - if (m_boundAsServer) - { -#if defined(WIN32) - closesocket(m_socket); -#else - close(m_socket); -#endif - } - while (m_connectionList != nullptr) - { - TcpConnection *con = m_connectionList; - m_connectionList = m_connectionList->m_nextConnection; - con->Release(); - m_connectionListCount--; - } -} - - -bool TcpManager::BindAsServer() -{ - - m_socket = socket(AF_INET, SOCK_STREAM, 0); - - if ((unsigned) m_socket != INVALID_SOCKET) - { -#if defined(WIN32) - FD_SET(m_socket, &m_permfds);//the socket this server is listening on - - unsigned long isNonBlocking = 1; - int outBufSize = m_params.outgoingBufferSize; - int inBufSize = m_params.incomingBufferSize; - int keepAlive = 1; - int reuseAddr = 1; - struct linger ld; - ld.l_onoff = 0; - ld.l_linger = 0; - - if (ioctlsocket(m_socket, FIONBIO, &isNonBlocking) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, (char *)&outBufSize, sizeof(outBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char *)&inBufSize, sizeof(inBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepAlive, sizeof(keepAlive)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuseAddr, sizeof(reuseAddr)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, (char *)&ld, sizeof(ld)) != 0 ) - { - return false; - } -#else // linux is to remain the default compile mode - unsigned long isNonBlocking = 1; - unsigned long keepAlive = 1; - unsigned long outBufSize = m_params.outgoingBufferSize; - unsigned long inBufSize = m_params.incomingBufferSize; - unsigned long reuseAddr = 1; - struct linger ld; - ld.l_onoff = 0; - ld.l_linger = 0; - - if (ioctl(m_socket, FIONBIO, &isNonBlocking) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, &outBufSize, sizeof(outBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, &inBufSize, sizeof(inBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(keepAlive)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, &ld, sizeof(ld)) != 0) - { - return false; - } -#endif - } - else - { - return false; - } - - - struct sockaddr_in addr_loc; - addr_loc.sin_family = AF_INET; - addr_loc.sin_port = htons(m_params.port); - addr_loc.sin_addr.s_addr = htonl(INADDR_ANY); - if (m_params.bindAddress[0] != 0) - { - unsigned long address = inet_addr(m_params.bindAddress); - if (address == INADDR_NONE) - { - struct hostent * lphp; - lphp = gethostbyname(m_params.bindAddress); - if (lphp != nullptr) - addr_loc.sin_addr.s_addr = ((struct in_addr *)(lphp->h_addr))->s_addr; - } - else - { - addr_loc.sin_addr.s_addr = address; - } - } - - if (bind(m_socket, (struct sockaddr *)&addr_loc, sizeof(addr_loc)) != 0) - { - return false; - } - - if (listen(m_socket, 1000) != 0) - { - return false; - } - - m_boundAsServer = true; - return true; -} - -TcpConnection *TcpManager::acceptClient() -{ - TcpConnection *newConn = nullptr; - - if (m_boundAsServer && m_connectionListCount < m_params.maxConnections) - { - - sockaddr_in addr; - int addrLength = sizeof(addr); - SOCKET sock = ::accept(m_socket, (sockaddr *) &addr, (socklen_t *) &addrLength); - - - if ((unsigned) sock != INVALID_SOCKET) - { - newConn = new TcpConnection(this, &m_allocator, m_params, sock, IPAddress(addr.sin_addr.s_addr), ntohs(addr.sin_port)); - addNewConnection(newConn); - if (m_handler != nullptr) - { - m_handler->OnConnectRequest(newConn); - } - } - } - - return newConn; -} - -void TcpManager::SetHandler(TcpManagerHandler *handler) -{ - m_handler = handler; -} - -SOCKET TcpManager::getMaxFD() -{ + TcpManager::TcpManager(const TcpParams ¶ms) + : m_handler(nullptr), + m_keepAliveList(nullptr, 1), + m_aliveList(nullptr, 2), + m_noDataList(nullptr, 1), + m_dataList(nullptr, 2), + m_params(params), + m_refCount(1), + m_connectionList(nullptr), + m_connectionListCount(0), + m_socket(INVALID_SOCKET), + m_boundAsServer(false), + m_allocator(params.allocatorBlockSize, params.allocatorBlockCount), + m_keepAliveTimer(), + m_noDataTimer() #ifdef WIN32 - return 0;//this param is not used on win32 for select, only on unix -#else - SOCKET maxfd = 0; - - if (m_boundAsServer) - maxfd = m_socket+1; - - TcpConnection *next = nullptr; - for (TcpConnection *con = m_connectionList ; con != nullptr ; con = next) - { - next = con->m_nextConnection; - if (con->GetStatus() != TcpConnection::StatusDisconnected && con->m_socket > maxfd) - { - maxfd = con->m_socket + 1; - } - } - return maxfd; + , m_permfds() #endif -} + { + if (params.keepAliveDelay > 0) + m_keepAliveTimer.start(); -TcpConnection *TcpManager::getConnection(SOCKET fd) -{ - TcpConnection *next = nullptr; - for (TcpConnection *con = m_connectionList ; con != nullptr ; con = next) - { - next = con->m_nextConnection; - if (con->m_socket == fd) - { - return con; - } - } - //if get here ,couldn't find it - return nullptr; -} + if (params.noDataTimeout > 0) + m_noDataTimer.start(); -bool TcpManager::GiveTime(unsigned maxTimeAcceptingConnections,unsigned maxSendTimePerConnection, unsigned maxRecvTimePerConnection) -{ - bool processedIncoming = false; +#if defined(WIN32) + WSADATA wsaData; + WSAStartup(MAKEWORD(1, 1), &wsaData); - if (maxTimeAcceptingConnections == 0 && maxSendTimePerConnection==0 && maxRecvTimePerConnection==0) - { - //they don't want to do anything now - return processedIncoming; - } + FD_ZERO(&m_permfds);//select only used on win32 +#endif + } - AddRef(); //keep a reference to ourself in case we callback to the application and the application releases us. + TcpManager::~TcpManager() + { +#if defined(WIN32) + WSACleanup(); +#endif + if (m_boundAsServer) + { +#if defined(WIN32) + closesocket(m_socket); +#else + close(m_socket); +#endif + } + while (m_connectionList != nullptr) + { + TcpConnection *con = m_connectionList; + m_connectionList = m_connectionList->m_nextConnection; + con->Release(); + m_connectionListCount--; + } + } + bool TcpManager::BindAsServer() + { + m_socket = socket(AF_INET, SOCK_STREAM, 0); - //first process outgoing on each connection, and finish establishing connections, if params say to - if (m_connectionListCount != 0 && maxSendTimePerConnection != 0) - { + if ((unsigned)m_socket != INVALID_SOCKET) + { +#if defined(WIN32) + FD_SET(m_socket, &m_permfds);//the socket this server is listening on - // Send output from last heartbeat - TcpConnection *next = nullptr; - for (TcpConnection *con = m_connectionList ; con != nullptr ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextConnection; - if (next) next->AddRef(); - if(con->GetStatus() == TcpConnection::StatusConnected) - { - Clock timer; - timer.start(); - while(!timer.isDone(maxSendTimePerConnection)) - { - int err = con->processOutgoing(); + unsigned long isNonBlocking = 1; + int outBufSize = m_params.outgoingBufferSize; + int inBufSize = m_params.incomingBufferSize; + int keepAlive = 1; + int reuseAddr = 1; + struct linger ld; + ld.l_onoff = 0; + ld.l_linger = 0; - if (err > 0) - { - //couldn't finish processing last request, don't try more - break; - } - else if (err < 0) - { - break; - } - } - con->Release(); - } - else if (con->GetStatus() == TcpConnection::StatusNegotiating) - { - if (con->finishConnect() < 0) - { + if (ioctlsocket(m_socket, FIONBIO, &isNonBlocking) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, (char *)&outBufSize, sizeof(outBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char *)&inBufSize, sizeof(inBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepAlive, sizeof(keepAlive)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuseAddr, sizeof(reuseAddr)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, (char *)&ld, sizeof(ld)) != 0) + { + return false; + } +#else // linux is to remain the default compile mode + unsigned long isNonBlocking = 1; + unsigned long keepAlive = 1; + unsigned long outBufSize = m_params.outgoingBufferSize; + unsigned long inBufSize = m_params.incomingBufferSize; + unsigned long reuseAddr = 1; + struct linger ld; + ld.l_onoff = 0; + ld.l_linger = 0; + + if (ioctl(m_socket, FIONBIO, &isNonBlocking) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, &outBufSize, sizeof(outBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, &inBufSize, sizeof(inBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(keepAlive)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, &ld, sizeof(ld)) != 0) + { + return false; + } +#endif + } + else + { + return false; + } + + struct sockaddr_in addr_loc; + addr_loc.sin_family = AF_INET; + addr_loc.sin_port = htons(m_params.port); + addr_loc.sin_addr.s_addr = htonl(INADDR_ANY); + if (m_params.bindAddress[0] != 0) + { + unsigned long address = inet_addr(m_params.bindAddress); + if (address == INADDR_NONE) + { + struct hostent * lphp; + lphp = gethostbyname(m_params.bindAddress); + if (lphp != nullptr) + addr_loc.sin_addr.s_addr = ((struct in_addr *)(lphp->h_addr))->s_addr; + } + else + { + addr_loc.sin_addr.s_addr = address; + } + } + + if (bind(m_socket, (struct sockaddr *)&addr_loc, sizeof(addr_loc)) != 0) + { + return false; + } + + if (listen(m_socket, 1000) != 0) + { + return false; + } + + m_boundAsServer = true; + return true; + } + + TcpConnection *TcpManager::acceptClient() + { + TcpConnection *newConn = nullptr; + + if (m_boundAsServer && m_connectionListCount < m_params.maxConnections) + { + sockaddr_in addr; + int addrLength = sizeof(addr); + SOCKET sock = ::accept(m_socket, (sockaddr *)&addr, (socklen_t *)&addrLength); + + if ((unsigned)sock != INVALID_SOCKET) + { + newConn = new TcpConnection(this, &m_allocator, m_params, sock, IPAddress(addr.sin_addr.s_addr), ntohs(addr.sin_port)); + addNewConnection(newConn); + if (m_handler != nullptr) + { + m_handler->OnConnectRequest(newConn); + } + } + } + + return newConn; + } + + void TcpManager::SetHandler(TcpManagerHandler *handler) + { + m_handler = handler; + } + + SOCKET TcpManager::getMaxFD() + { +#ifdef WIN32 + return 0;//this param is not used on win32 for select, only on unix +#else + SOCKET maxfd = 0; + + if (m_boundAsServer) + maxfd = m_socket + 1; + + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + next = con->m_nextConnection; + if (con->GetStatus() != TcpConnection::StatusDisconnected && con->m_socket > maxfd) + { + maxfd = con->m_socket + 1; + } + } + return maxfd; +#endif + } + + TcpConnection *TcpManager::getConnection(SOCKET fd) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + next = con->m_nextConnection; + if (con->m_socket == fd) + { + return con; + } + } + //if get here ,couldn't find it + return nullptr; + } + + bool TcpManager::GiveTime(unsigned maxTimeAcceptingConnections, unsigned maxSendTimePerConnection, unsigned maxRecvTimePerConnection) + { + bool processedIncoming = false; + + if (maxTimeAcceptingConnections == 0 && maxSendTimePerConnection == 0 && maxRecvTimePerConnection == 0) + { + //they don't want to do anything now + return processedIncoming; + } + + AddRef(); //keep a reference to ourself in case we callback to the application and the application releases us. + + //first process outgoing on each connection, and finish establishing connections, if params say to + if (m_connectionListCount != 0 && maxSendTimePerConnection != 0) + { + // Send output from last heartbeat + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextConnection; + if (next) next->AddRef(); + if (con->GetStatus() == TcpConnection::StatusConnected) + { + Clock timer; + timer.start(); + while (!timer.isDone(maxSendTimePerConnection)) + { + int err = con->processOutgoing(); + + if (err > 0) + { + //couldn't finish processing last request, don't try more + break; + } + else if (err < 0) + { + break; + } + } con->Release(); - continue; - } - con->Release(); - } - else //inactive client in client list???? - { - removeConnection(con); - con->Release(); - continue; - } - } - - } - - //process incoming messages (including connect requests) - if (( - m_boundAsServer //if in server mode and want to spend time accepting clients - && maxTimeAcceptingConnections != 0 - ) - || - ( - m_connectionListCount != 0 //if there are connections and want to spend time receiving on them - && maxRecvTimePerConnection != 0 - ) - ) - { -#ifdef WIN32 - SOCKET maxfd = getMaxFD(); //re-calc maxfd every time select on WIN32 - - //select on all fd's - struct timeval timeout; - - fd_set tmpfds; - tmpfds = m_permfds; - timeout.tv_sec = 0; - timeout.tv_usec = 0; - int cnt = select(maxfd, &tmpfds, nullptr, nullptr, &timeout); // blocks for timeout - - - if (cnt > 0) - { - if (m_boundAsServer && maxTimeAcceptingConnections != 0) - {//activity on our socket means connect requests - - //see if are new incoming clients - if (FD_ISSET(m_socket, &tmpfds)) - { - //yep - Clock timer; - timer.start(); - while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) - { - //loop - } - } - } - - - - //process incoming client messages - if (maxRecvTimePerConnection != 0) - { - TcpConnection *next = nullptr; - for (TcpConnection *con = m_connectionList ; con != nullptr ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextConnection; - if (next) next->AddRef(); - - SOCKET fd = con->m_socket; - if (fd == INVALID_SOCKET) - { - //invalid socket in list?, check if is connecting, otherwise, Disconnect and discard - if (con->GetStatus() != TcpConnection::StatusNegotiating) - { - removeConnection(con); - con->Release(); - continue; - } - } - - if (FD_ISSET(fd, &tmpfds)) - { - Clock timer; - timer.start(); - while(!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) - { - int err = con->processIncoming(); - if (err >= 0) - { - processedIncoming = true; - } - - if (err > 0) - { - //couldn't finish processing last request, don't try more - break; - } - else if (err < 0) - { - break; - } - - }//while(!timer...) - }//if (FD_ISSET...) + } + else if (con->GetStatus() == TcpConnection::StatusNegotiating) + { + if (con->finishConnect() < 0) + { + con->Release(); + continue; + } con->Release(); - }//for (...) - } //maxRecvTimePerConnection != 0 - }//cnt > 0 + } + else //inactive client in client list???? + { + removeConnection(con); + con->Release(); + continue; + } + } + } + + //process incoming messages (including connect requests) + if (( + m_boundAsServer //if in server mode and want to spend time accepting clients + && maxTimeAcceptingConnections != 0 + ) + || + ( + m_connectionListCount != 0 //if there are connections and want to spend time receiving on them + && maxRecvTimePerConnection != 0 + ) + ) + { +#ifdef WIN32 + SOCKET maxfd = getMaxFD(); //re-calc maxfd every time select on WIN32 + + //select on all fd's + struct timeval timeout; + + fd_set tmpfds; + tmpfds = m_permfds; + timeout.tv_sec = 0; + timeout.tv_usec = 0; + int cnt = select(maxfd, &tmpfds, nullptr, nullptr, &timeout); // blocks for timeout + + if (cnt > 0) + { + if (m_boundAsServer && maxTimeAcceptingConnections != 0) + {//activity on our socket means connect requests + //see if are new incoming clients + if (FD_ISSET(m_socket, &tmpfds)) + { + //yep + Clock timer; + timer.start(); + while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) + { + //loop + } + } + } + + //process incoming client messages + if (maxRecvTimePerConnection != 0) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextConnection; + if (next) next->AddRef(); + + SOCKET fd = con->m_socket; + if (fd == INVALID_SOCKET) + { + //invalid socket in list?, check if is connecting, otherwise, Disconnect and discard + if (con->GetStatus() != TcpConnection::StatusNegotiating) + { + removeConnection(con); + con->Release(); + continue; + } + } + + if (FD_ISSET(fd, &tmpfds)) + { + Clock timer; + timer.start(); + while (!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) + { + int err = con->processIncoming(); + if (err >= 0) + { + processedIncoming = true; + } + + if (err > 0) + { + //couldn't finish processing last request, don't try more + break; + } + else if (err < 0) + { + break; + } + }//while(!timer...) + }//if (FD_ISSET...) + con->Release(); + }//for (...) + } //maxRecvTimePerConnection != 0 + }//cnt > 0 #else //on UNIX use poll - int numfds = m_connectionListCount; - int idx = 0; - if (m_boundAsServer) - { - numfds++; - idx++; - } + int numfds = m_connectionListCount; + int idx = 0; + if (m_boundAsServer) + { + numfds++; + idx++; + } - struct pollfd pollfds[numfds]; + struct pollfd pollfds[numfds]; - if (m_boundAsServer) - { - pollfds[0].fd = m_socket; - pollfds[0].events |= POLLIN; - } + if (m_boundAsServer) + { + pollfds[0].fd = m_socket; + pollfds[0].events |= POLLIN; + } - TcpConnection *next = nullptr; - for (TcpConnection *con = m_connectionList ; con != nullptr ; con = next, idx++) - { - next = con->m_nextConnection; - pollfds[idx].fd = con->m_socket; - pollfds[idx].events |= POLLIN; - pollfds[idx].events |= POLLHUP; - } - + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next, idx++) + { + next = con->m_nextConnection; + pollfds[idx].fd = con->m_socket; + pollfds[idx].events |= POLLIN; + pollfds[idx].events |= POLLHUP; + } - int cnt = poll(pollfds, numfds, 1); + int cnt = poll(pollfds, numfds, 1); - if((unsigned) cnt == SOCKET_ERROR) - { - //poll not working? - //TODO: need to notify client somehow, don't think we can assume a fatal error here - } - else if (cnt > 0) - { - for (idx = 0; idx < numfds; idx++) - { - //find corresponding TcpConnection - //TODO: optimize, seriously, this is takes linear time, every time - TcpConnection *con = getConnection(pollfds[idx].fd); + if ((unsigned)cnt == SOCKET_ERROR) + { + //poll not working? + //TODO: need to notify client somehow, don't think we can assume a fatal error here + } + else if (cnt > 0) + { + for (idx = 0; idx < numfds; idx++) + { + //find corresponding TcpConnection + //TODO: optimize, seriously, this is takes linear time, every time + TcpConnection *con = getConnection(pollfds[idx].fd); - if (pollfds[idx].revents & POLLIN) - { - if (m_boundAsServer && maxTimeAcceptingConnections != 0 && pollfds[idx].fd == m_socket) - { - //new incoming clients - Clock timer; - timer.start(); - while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) - { - //loop - } + if (pollfds[idx].revents & POLLIN) + { + if (m_boundAsServer && maxTimeAcceptingConnections != 0 && pollfds[idx].fd == m_socket) + { + //new incoming clients + Clock timer; + timer.start(); + while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) + { + //loop + } - continue;//don't try to readmsgs from listening fd - } - - //process regular msg(s) - if (con == nullptr) - { - close(pollfds[idx].fd); - continue; - } + continue;//don't try to readmsgs from listening fd + } - Clock timer; - timer.start(); - con->AddRef();//so it can't get deleted while we are checking it's status - while(!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) - { - int err = con->processIncoming(); - if (err >= 0) - { - processedIncoming = true; - } + //process regular msg(s) + if (con == nullptr) + { + close(pollfds[idx].fd); + continue; + } - if (err > 0) - { - //couldn't finish processing last request, don't try more - break; - } - else if (err < 0) - { - break; - } + Clock timer; + timer.start(); + con->AddRef();//so it can't get deleted while we are checking it's status + while (!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) + { + int err = con->processIncoming(); + if (err >= 0) + { + processedIncoming = true; + } - }//while(!timer....) - con->Release(); - }//if(pollfds[... - else if (pollfds[idx].revents & POLLHUP) - { - if (con == nullptr) - { - close(pollfds[idx].fd); - continue; - } + if (err > 0) + { + //couldn't finish processing last request, don't try more + break; + } + else if (err < 0) + { + break; + } + }//while(!timer....) + con->Release(); + }//if(pollfds[... + else if (pollfds[idx].revents & POLLHUP) + { + if (con == nullptr) + { + close(pollfds[idx].fd); + continue; + } - //Disconnect client - con->Disconnect(); - } - }//for (idx=0.... - }//else if (cnt > 0) + //Disconnect client + con->Disconnect(); + } + }//for (idx=0.... + }//else if (cnt > 0) #endif - }//wanted to process incoming messages or connect requests + }//wanted to process incoming messages or connect requests - //now process any keepalives, if time to do that - if (m_params.keepAliveDelay > 0 && m_keepAliveTimer.isDone(m_params.keepAliveDelay)) - { - TcpConnection *next = nullptr; - for (TcpConnection *con = m_keepAliveList.m_beginList ; con != nullptr ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextKeepAliveConnection; - if (next) next->AddRef(); - - con->Send(nullptr, 0); //note: this request will move the connection from the keepAliveList to the aliveList - con->Release(); - } + //now process any keepalives, if time to do that + if (m_params.keepAliveDelay > 0 && m_keepAliveTimer.isDone(m_params.keepAliveDelay)) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_keepAliveList.m_beginList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextKeepAliveConnection; + if (next) next->AddRef(); - //now move the complete alive list over to the keepalive list to reset those timers - m_keepAliveList.m_beginList = m_aliveList.m_beginList; - m_aliveList.m_beginList = nullptr; + con->Send(nullptr, 0); //note: this request will move the connection from the keepAliveList to the aliveList + con->Release(); + } - //switch id's for those connections that were in the alive list last go - around - int tmpID = m_aliveList.m_listID; - m_aliveList.m_listID = m_keepAliveList.m_listID; - m_keepAliveList.m_listID = tmpID; + //now move the complete alive list over to the keepalive list to reset those timers + m_keepAliveList.m_beginList = m_aliveList.m_beginList; + m_aliveList.m_beginList = nullptr; - m_keepAliveTimer.reset(); - m_keepAliveTimer.start(); - } + //switch id's for those connections that were in the alive list last go - around + int tmpID = m_aliveList.m_listID; + m_aliveList.m_listID = m_keepAliveList.m_listID; + m_keepAliveList.m_listID = tmpID; - //now process any noDataCons, if time to do that - if (m_params.noDataTimeout > 0 && m_noDataTimer.isDone(m_params.noDataTimeout)) - { - TcpConnection *next = nullptr; - for (TcpConnection *con = m_noDataList.m_beginList ; con != nullptr ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextRecvDataConnection; - if (next) next->AddRef(); + m_keepAliveTimer.reset(); + m_keepAliveTimer.start(); + } - //time to disconnect this guy - con->Disconnect(); - con->Release(); - } + //now process any noDataCons, if time to do that + if (m_params.noDataTimeout > 0 && m_noDataTimer.isDone(m_params.noDataTimeout)) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_noDataList.m_beginList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextRecvDataConnection; + if (next) next->AddRef(); - //now move the complete data list over to the nodata list to reset those timers - m_noDataList.m_beginList = m_dataList.m_beginList; - m_dataList.m_beginList = nullptr; + //time to disconnect this guy + con->Disconnect(); + con->Release(); + } - //switch id's for those connections that were in the data list last go - around - int tmpID = m_dataList.m_listID; - m_dataList.m_listID = m_noDataList.m_listID; - m_noDataList.m_listID = tmpID; + //now move the complete data list over to the nodata list to reset those timers + m_noDataList.m_beginList = m_dataList.m_beginList; + m_dataList.m_beginList = nullptr; - m_noDataTimer.reset(); - m_noDataTimer.start(); - } + //switch id's for those connections that were in the data list last go - around + int tmpID = m_dataList.m_listID; + m_dataList.m_listID = m_noDataList.m_listID; + m_noDataList.m_listID = tmpID; - Release(); + m_noDataTimer.reset(); + m_noDataTimer.start(); + } - return processedIncoming; -} + Release(); -TcpConnection *TcpManager::EstablishConnection(const char *serverAddress, unsigned short serverPort, unsigned timeout) -{ - if (m_boundAsServer) - { - //can't open outgoing connections when in server mode - // use a different TcpManager to do that - return nullptr; - } + return processedIncoming; + } - if (m_connectionListCount >= m_params.maxConnections) - return(nullptr); + TcpConnection *TcpManager::EstablishConnection(const char *serverAddress, unsigned short serverPort, unsigned timeout) + { + if (m_boundAsServer) + { + //can't open outgoing connections when in server mode + // use a different TcpManager to do that + return nullptr; + } - // get server address - unsigned long address = inet_addr(serverAddress); - if (address == INADDR_NONE) - { - struct hostent * lphp; - lphp = gethostbyname(serverAddress); - if (lphp == nullptr) - return(nullptr); - address = ((struct in_addr *)(lphp->h_addr))->s_addr; - } - IPAddress destIP(address); + if (m_connectionListCount >= m_params.maxConnections) + return(nullptr); - TcpConnection *con = new TcpConnection(this, &m_allocator, m_params, destIP, serverPort, timeout); - con->AddRef();//for the client - to conform to UdpLibrary method - addNewConnection(con); + // get server address + unsigned long address = inet_addr(serverAddress); + if (address == INADDR_NONE) + { + struct hostent * lphp; + lphp = gethostbyname(serverAddress); + if (lphp == nullptr) + return(nullptr); + address = ((struct in_addr *)(lphp->h_addr))->s_addr; + } + IPAddress destIP(address); - return con; -} + TcpConnection *con = new TcpConnection(this, &m_allocator, m_params, destIP, serverPort, timeout); + con->AddRef();//for the client - to conform to UdpLibrary method + addNewConnection(con); -void TcpManager::addNewConnection(TcpConnection *con) -{ - con->AddRef(); + return con; + } + + void TcpManager::addNewConnection(TcpConnection *con) + { + con->AddRef(); #ifdef WIN32 //uses select - if (con->m_socket != INVALID_SOCKET) - FD_SET(con->m_socket, &m_permfds); + if (con->m_socket != INVALID_SOCKET) + FD_SET(con->m_socket, &m_permfds); #endif - con->m_nextConnection = m_connectionList; - con->m_prevConnection = nullptr; - if (m_connectionList != nullptr) - m_connectionList->m_prevConnection = con; - m_connectionList = con; - m_connectionListCount++; + con->m_nextConnection = m_connectionList; + con->m_prevConnection = nullptr; + if (m_connectionList != nullptr) + m_connectionList->m_prevConnection = con; + m_connectionList = con; + m_connectionListCount++; - con->m_nextKeepAliveConnection = m_aliveList.m_beginList; - con->m_prevKeepAliveConnection = nullptr; - if (m_aliveList.m_beginList != nullptr) - m_aliveList.m_beginList->m_prevKeepAliveConnection = con; - m_aliveList.m_beginList = con; - con->m_aliveListId = m_keepAliveList.m_listID;//start it out thinking it's already in the alive list, since it is + con->m_nextKeepAliveConnection = m_aliveList.m_beginList; + con->m_prevKeepAliveConnection = nullptr; + if (m_aliveList.m_beginList != nullptr) + m_aliveList.m_beginList->m_prevKeepAliveConnection = con; + m_aliveList.m_beginList = con; + con->m_aliveListId = m_keepAliveList.m_listID;//start it out thinking it's already in the alive list, since it is - con->m_nextRecvDataConnection = m_dataList.m_beginList; - con->m_prevRecvDataConnection = nullptr; - if (m_dataList.m_beginList != nullptr) - m_dataList.m_beginList->m_prevRecvDataConnection = con; - m_dataList.m_beginList = con; - con->m_recvDataListId = m_noDataList.m_listID;//start it out thinking it's already in the data list, since it is -} + con->m_nextRecvDataConnection = m_dataList.m_beginList; + con->m_prevRecvDataConnection = nullptr; + if (m_dataList.m_beginList != nullptr) + m_dataList.m_beginList->m_prevRecvDataConnection = con; + m_dataList.m_beginList = con; + con->m_recvDataListId = m_noDataList.m_listID;//start it out thinking it's already in the data list, since it is + } -void TcpManager::removeConnection(TcpConnection *con) -{ - if (!con->wasRemovedFromMgr()) - { - con->setRemovedFromMgr(); - m_connectionListCount--; - #ifdef WIN32 //select only used on win32 - if (con->m_socket != INVALID_SOCKET) - { - FD_CLR(con->m_socket, &m_permfds); - } - #endif - if (con->m_prevConnection != nullptr) - con->m_prevConnection->m_nextConnection = con->m_nextConnection; - if (con->m_nextConnection != nullptr) - con->m_nextConnection->m_prevConnection = con->m_prevConnection; - if (m_connectionList == con) - m_connectionList = con->m_nextConnection; - con->m_nextConnection = nullptr; - con->m_prevConnection = nullptr; + void TcpManager::removeConnection(TcpConnection *con) + { + if (!con->wasRemovedFromMgr()) + { + con->setRemovedFromMgr(); + m_connectionListCount--; +#ifdef WIN32 //select only used on win32 + if (con->m_socket != INVALID_SOCKET) + { + FD_CLR(con->m_socket, &m_permfds); + } +#endif + if (con->m_prevConnection != nullptr) + con->m_prevConnection->m_nextConnection = con->m_nextConnection; + if (con->m_nextConnection != nullptr) + con->m_nextConnection->m_prevConnection = con->m_prevConnection; + if (m_connectionList == con) + m_connectionList = con->m_nextConnection; + con->m_nextConnection = nullptr; + con->m_prevConnection = nullptr; - if (con->m_prevKeepAliveConnection != nullptr) - con->m_prevKeepAliveConnection->m_nextKeepAliveConnection = con->m_nextKeepAliveConnection; - if (con->m_nextKeepAliveConnection != nullptr) - con->m_nextKeepAliveConnection->m_prevKeepAliveConnection = con->m_prevKeepAliveConnection; + if (con->m_prevKeepAliveConnection != nullptr) + con->m_prevKeepAliveConnection->m_nextKeepAliveConnection = con->m_nextKeepAliveConnection; + if (con->m_nextKeepAliveConnection != nullptr) + con->m_nextKeepAliveConnection->m_prevKeepAliveConnection = con->m_prevKeepAliveConnection; - if (m_aliveList.m_beginList == con) - m_aliveList.m_beginList = con->m_nextKeepAliveConnection; - else if (m_keepAliveList.m_beginList == con) - m_keepAliveList.m_beginList = con->m_nextKeepAliveConnection; - con->m_nextKeepAliveConnection = nullptr; - con->m_prevKeepAliveConnection = nullptr; + if (m_aliveList.m_beginList == con) + m_aliveList.m_beginList = con->m_nextKeepAliveConnection; + else if (m_keepAliveList.m_beginList == con) + m_keepAliveList.m_beginList = con->m_nextKeepAliveConnection; + con->m_nextKeepAliveConnection = nullptr; + con->m_prevKeepAliveConnection = nullptr; + if (con->m_prevRecvDataConnection != nullptr) + con->m_prevRecvDataConnection->m_nextRecvDataConnection = con->m_nextRecvDataConnection; + if (con->m_nextRecvDataConnection != nullptr) + con->m_nextRecvDataConnection->m_prevRecvDataConnection = con->m_prevRecvDataConnection; + if (m_dataList.m_beginList == con) + m_dataList.m_beginList = con->m_nextRecvDataConnection; + else if (m_noDataList.m_beginList == con) + m_noDataList.m_beginList = con->m_nextRecvDataConnection; + con->m_nextRecvDataConnection = nullptr; + con->m_prevRecvDataConnection = nullptr; - if (con->m_prevRecvDataConnection != nullptr) - con->m_prevRecvDataConnection->m_nextRecvDataConnection = con->m_nextRecvDataConnection; - if (con->m_nextRecvDataConnection != nullptr) - con->m_nextRecvDataConnection->m_prevRecvDataConnection = con->m_prevRecvDataConnection; + con->Release(); + } + } - if (m_dataList.m_beginList == con) - m_dataList.m_beginList = con->m_nextRecvDataConnection; - else if (m_noDataList.m_beginList == con) - m_noDataList.m_beginList = con->m_nextRecvDataConnection; - con->m_nextRecvDataConnection = nullptr; - con->m_prevRecvDataConnection = nullptr; + void TcpManager::AddRef() + { + m_refCount++; + } + void TcpManager::Release() + { + if (--m_refCount == 0) + delete this; + } + IPAddress TcpManager::GetLocalIp() const + { + struct sockaddr_in addr_self; + memset(&addr_self, 0, sizeof(addr_self)); + socklen_t len = sizeof(addr_self); + getsockname(m_socket, (struct sockaddr *)&addr_self, &len); + return(IPAddress(addr_self.sin_addr.s_addr)); + } - con->Release(); - } -} - -void TcpManager::AddRef() -{ - m_refCount++; -} - -void TcpManager::Release() -{ - if (--m_refCount == 0) - delete this; -} - -IPAddress TcpManager::GetLocalIp() const -{ - struct sockaddr_in addr_self; - memset(&addr_self, 0, sizeof(addr_self)); - socklen_t len = sizeof(addr_self); - getsockname(m_socket, (struct sockaddr *)&addr_self, &len); - return(IPAddress(addr_self.sin_addr.s_addr)); - -} - -unsigned int TcpManager::GetLocalPort() const -{ - struct sockaddr_in addr_self; - memset(&addr_self, 0, sizeof(addr_self)); - socklen_t len = sizeof(addr_self); - getsockname(m_socket, (struct sockaddr *)&addr_self, &len); - return(ntohs(addr_self.sin_port)); -} - + unsigned int TcpManager::GetLocalPort() const + { + struct sockaddr_in addr_self; + memset(&addr_self, 0, sizeof(addr_self)); + socklen_t len = sizeof(addr_self); + getsockname(m_socket, (struct sockaddr *)&addr_self, &len); + return(ntohs(addr_self.sin_port)); + } #ifdef EXTERNAL_DISTRO }; -#endif - - +#endif \ No newline at end of file diff --git a/external/3rd/library/soePlatform/CTServiceGameAPI/CTGenericAPI/GenericConnection.cpp b/external/3rd/library/soePlatform/CTServiceGameAPI/CTGenericAPI/GenericConnection.cpp index 2fd9ca45..ae67918e 100755 --- a/external/3rd/library/soePlatform/CTServiceGameAPI/CTGenericAPI/GenericConnection.cpp +++ b/external/3rd/library/soePlatform/CTServiceGameAPI/CTGenericAPI/GenericConnection.cpp @@ -12,198 +12,199 @@ //---------------------------------------- #ifdef EXTERNAL_DISTRO -namespace NAMESPACE +namespace NAMESPACE { #endif -using namespace std; -using namespace Base; + using namespace std; + using namespace Base; -GenericConnection::GenericConnection(const char *host, short port, GenericAPICore *apiCore, unsigned reconnectTimeout, unsigned noDataTimeoutSecs, unsigned noAckTimeoutSecs, unsigned incomingBufSizeInKB, unsigned outgoingBufSizeInKB, unsigned keepAlive, unsigned maxRecvMessageSizeInKB) -: m_bConnected(CON_NONE), - m_apiCore(apiCore), - m_con(nullptr), - m_host(host), - m_port(port), - m_lastTrack(123455), //random choice != 1 - m_conState(CON_DISCONNECT), - m_reconnectTimeout(reconnectTimeout) -{ - TcpManager::TcpParams params; - - params.incomingBufferSize = incomingBufSizeInKB * 1024; - params.outgoingBufferSize = outgoingBufSizeInKB * 1024; - params.maxConnections = 1; - params.port = 0; - params.maxRecvMessageSize = maxRecvMessageSizeInKB*1024; - params.keepAliveDelay = keepAlive * 1000; - params.noDataTimeout = noDataTimeoutSecs * 1000; - //params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000; - - m_manager = new TcpManager(params); -} - -GenericConnection::~GenericConnection() -{ - if(m_con) + GenericConnection::GenericConnection(const char *host, short port, GenericAPICore *apiCore, unsigned reconnectTimeout, unsigned noDataTimeoutSecs, unsigned noAckTimeoutSecs, unsigned incomingBufSizeInKB, unsigned outgoingBufSizeInKB, unsigned keepAlive, unsigned maxRecvMessageSizeInKB) + : m_bConnected(CON_NONE), + m_apiCore(apiCore), + m_con(nullptr), + m_host(host), + m_port(port), + m_lastTrack(123455), //random choice != 1 + m_conState(CON_DISCONNECT), + m_reconnectTimeout(reconnectTimeout), + m_conTimeout(100) { - m_con->SetHandler(nullptr); - m_con->Disconnect();//don't worry about onterminated being called, we've set it's handler to nullptr, so it wont - m_con->Release(); + TcpManager::TcpParams params; + + params.incomingBufferSize = incomingBufSizeInKB * 1024; + params.outgoingBufferSize = outgoingBufSizeInKB * 1024; + params.maxConnections = 1; + params.port = 0; + params.maxRecvMessageSize = maxRecvMessageSizeInKB * 1024; + params.keepAliveDelay = keepAlive * 1000; + params.noDataTimeout = noDataTimeoutSecs * 1000; + //params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000; + + m_manager = new TcpManager(params); } - m_manager->Release(); -} - -void GenericConnection::disconnect() -{ - if (m_con) + GenericConnection::~GenericConnection() { - m_con->Disconnect(); - //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); - m_con = nullptr; + if (m_con) + { + m_con->SetHandler(nullptr); + m_con->Disconnect();//don't worry about onterminated being called, we've set it's handler to nullptr, so it wont + m_con->Release(); + } + + m_manager->Release(); } - m_conState = CON_DISCONNECT; - m_bConnected = CON_NONE; -} -void GenericConnection::OnTerminated(TcpConnection *con) -{ -// m_apiCore->OnDisconnect(m_host.c_str(), m_port); - m_apiCore->OnDisconnect(this); - if(m_con) + void GenericConnection::disconnect() { - m_con->Release(); - m_con = nullptr; + if (m_con) + { + m_con->Disconnect(); + //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); + m_con = nullptr; + } + m_conState = CON_DISCONNECT; + m_bConnected = CON_NONE; } - m_conState = CON_DISCONNECT; - m_bConnected = CON_NONE; -} -void GenericConnection::OnRoutePacket(TcpConnection *con, const unsigned char *data, int dataLen) -{ - short type; - unsigned track; - - ByteStream msg(data, dataLen); - ByteStream::ReadIterator iter = msg.begin(); - - get(iter, type); - get(iter, track); - GenericResponse *res = nullptr; - - // the following if block is a temporary fix that prevents - // a crash with a game team in which they occasionally find - // themselves receiving a dupe track in consecutive calls to - // OnRoutePacket (which then leads to a callback being called - // twice and data being invalid on the second call -> crash!). - if (track != 0 && - track == m_lastTrack) + void GenericConnection::OnTerminated(TcpConnection *con) { - printf("!!! ERROR !!! Got a duplicate track ID %u\n", track); - return; + // m_apiCore->OnDisconnect(m_host.c_str(), m_port); + m_apiCore->OnDisconnect(this); + if (m_con) + { + m_con->Release(); + m_con = nullptr; + } + m_conState = CON_DISCONNECT; + m_bConnected = CON_NONE; } - m_lastTrack = track; - // end temporary fix. - - if(track == 0) // notification message from the server, not as a response to a request from this API + void GenericConnection::OnRoutePacket(TcpConnection *con, const unsigned char *data, int dataLen) { - if (type == CTService::CTGAME_REQUEST_CONNECT) - { // this is a special case, for when we have identified our game code to server - m_bConnected = CON_IDENTIFIED; - m_apiCore->OnConnect(this); + short type; + unsigned track; + + ByteStream msg(data, dataLen); + ByteStream::ReadIterator iter = msg.begin(); + + get(iter, type); + get(iter, track); + GenericResponse *res = nullptr; + + // the following if block is a temporary fix that prevents + // a crash with a game team in which they occasionally find + // themselves receiving a dupe track in consecutive calls to + // OnRoutePacket (which then leads to a callback being called + // twice and data being invalid on the second call -> crash!). + if (track != 0 && + track == m_lastTrack) + { + printf("!!! ERROR !!! Got a duplicate track ID %u\n", track); + return; + } + m_lastTrack = track; + + // end temporary fix. + + if (track == 0) // notification message from the server, not as a response to a request from this API + { + if (type == CTService::CTGAME_REQUEST_CONNECT) + { // this is a special case, for when we have identified our game code to server + m_bConnected = CON_IDENTIFIED; + m_apiCore->OnConnect(this); + } + else + { + m_apiCore->responseCallback(type, iter, this); + } } else { - m_apiCore->responseCallback(type, iter, this); + map::iterator mapIter = m_apiCore->m_pending.find(track); + + if (mapIter != m_apiCore->m_pending.end()) + { + res = (*mapIter).second; + iter = msg.begin(); + res->unpack(iter); + m_apiCore->responseCallback(res); + m_apiCore->m_pendingCount--; + m_apiCore->m_pending.erase(mapIter); + delete res; + } } } - else + + void GenericConnection::process() { - map::iterator mapIter = m_apiCore->m_pending.find(track); + switch (m_conState) + { + case CON_DISCONNECT: + // create connection object, attempting to connect and + // checking for connection in next state, CON_NEGOTIATE + m_con = m_manager->EstablishConnection(m_host.c_str(), m_port); + if (m_con) + { + m_con->SetHandler(this); + m_conState = CON_NEGOTIATE; + m_conTimeout = time(nullptr) + m_reconnectTimeout; + } + break; + case CON_NEGOTIATE: + // check for connection - if(mapIter != m_apiCore->m_pending.end()) - { - res = (*mapIter).second; - iter = msg.begin(); - res->unpack(iter); - m_apiCore->responseCallback(res); - m_apiCore->m_pendingCount--; - m_apiCore->m_pending.erase(mapIter); - delete res; - } - } -} - -void GenericConnection::process() -{ - switch(m_conState) - { - case CON_DISCONNECT: - // create connection object, attempting to connect and - // checking for connection in next state, CON_NEGOTIATE - m_con = m_manager->EstablishConnection(m_host.c_str(), m_port); - if(m_con) - { - m_con->SetHandler(this); - m_conState = CON_NEGOTIATE; - m_conTimeout = time(nullptr) + m_reconnectTimeout; - } - break; - case CON_NEGOTIATE: - // check for connection - - if(m_con->GetStatus() == TcpConnection::StatusConnected) - { - // we're connected - m_conState = CON_CONNECT; - m_bConnected = CON_CONNECTED; - // instead of calling OnConnect() right now, we are going to submit a connection packet - // identifying us -// m_apiCore->OnConnect(this); - Base::ByteStream msg; - put(msg, (short)CTService::CTGAME_REQUEST_CONNECT); - put(msg, (unsigned)0); // track - put(msg, (unsigned)API_VERSION_CODE); - put(msg, m_apiCore->getGameCode()); - Send(msg); - } - else if(time(nullptr) > m_conTimeout) - { - // we did not connect - m_con->Disconnect(); - //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); - m_con = nullptr; + if (m_con->GetStatus() == TcpConnection::StatusConnected) + { + // we're connected + m_conState = CON_CONNECT; + m_bConnected = CON_CONNECTED; + // instead of calling OnConnect() right now, we are going to submit a connection packet + // identifying us + // m_apiCore->OnConnect(this); + Base::ByteStream msg; + put(msg, (short)CTService::CTGAME_REQUEST_CONNECT); + put(msg, (unsigned)0); // track + put(msg, (unsigned)API_VERSION_CODE); + put(msg, m_apiCore->getGameCode()); + Send(msg); + } + else if (time(nullptr) > m_conTimeout) + { + // we did not connect + m_con->Disconnect(); + //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); + m_con = nullptr; + m_conState = CON_DISCONNECT; + m_bConnected = CON_NONE; + } + break; + case CON_CONNECT: + // do nothing + break; + default: + // this should not occur, but we revert to CON_DISCONNECT if it does m_conState = CON_DISCONNECT; - m_bConnected = CON_NONE; - } - break; - case CON_CONNECT: - // do nothing - break; - default: - // this should not occur, but we revert to CON_DISCONNECT if it does - m_conState = CON_DISCONNECT; - m_bConnected = CON_NONE; - if (m_con) - { - m_con->Disconnect(); - //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); - m_con = nullptr; + m_bConnected = CON_NONE; + if (m_con) + { + m_con->Disconnect(); + //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); + m_con = nullptr; + } } + m_manager->GiveTime(); } - m_manager->GiveTime(); -} -void GenericConnection::Send(Base::ByteStream &msg) -{ - if(m_con && m_con->GetStatus() == TcpConnection::StatusConnected) + void GenericConnection::Send(Base::ByteStream &msg) { - m_con->Send((const char *)msg.getBuffer(), msg.getSize()); + if (m_con && m_con->GetStatus() == TcpConnection::StatusConnected) + { + m_con->Send((const char *)msg.getBuffer(), msg.getSize()); + } } -} #ifdef EXTERNAL_DISTRO }; -#endif +#endif \ No newline at end of file diff --git a/external/3rd/library/soePlatform/CTServiceGameAPI/CTGenericAPI/GenericMessage.cpp b/external/3rd/library/soePlatform/CTServiceGameAPI/CTGenericAPI/GenericMessage.cpp index c01729d8..695d9442 100755 --- a/external/3rd/library/soePlatform/CTServiceGameAPI/CTGenericAPI/GenericMessage.cpp +++ b/external/3rd/library/soePlatform/CTServiceGameAPI/CTGenericAPI/GenericMessage.cpp @@ -9,36 +9,35 @@ //---------------------------------------- #ifdef EXTERNAL_DISTRO -namespace NAMESPACE +namespace NAMESPACE { - #endif -using namespace Base; + using namespace Base; -//------------------------------------------- -GenericRequest::GenericRequest(short type, unsigned server_track) -: m_type(type), m_server_track(server_track) -//------------------------------------------- -{ -} + //------------------------------------------- + GenericRequest::GenericRequest(short type, unsigned server_track) + : m_type(type), m_server_track(server_track), m_track(0), m_timeout(100) + //------------------------------------------- + { + } -//------------------------------------------- -GenericResponse::GenericResponse(short type, unsigned result, void *user) -: m_type(type), m_result(result), m_user(user) -//------------------------------------------- -{ -} + //------------------------------------------- + GenericResponse::GenericResponse(short type, unsigned result, void *user) + : m_type(type), m_result(result), m_user(user), m_track(0), m_timeout(100) + //------------------------------------------- + { + } -//----------------------------------------- -void GenericResponse::unpack(ByteStream::ReadIterator &iter) -//----------------------------------------- -{ - get(iter, m_type); - get(iter, m_track); - get(iter, m_result); -} + //----------------------------------------- + void GenericResponse::unpack(ByteStream::ReadIterator &iter) + //----------------------------------------- + { + get(iter, m_type); + get(iter, m_track); + get(iter, m_result); + } #ifdef EXTERNAL_DISTRO }; -#endif +#endif \ No newline at end of file diff --git a/external/3rd/library/soePlatform/CTServiceGameAPI/TcpLibrary/TcpManager.cpp b/external/3rd/library/soePlatform/CTServiceGameAPI/TcpLibrary/TcpManager.cpp index 2586fa64..bfc84c13 100755 --- a/external/3rd/library/soePlatform/CTServiceGameAPI/TcpLibrary/TcpManager.cpp +++ b/external/3rd/library/soePlatform/CTServiceGameAPI/TcpLibrary/TcpManager.cpp @@ -4,731 +4,707 @@ #include "TcpConnection.h" #ifndef WIN32 - #include +#include #endif - #ifdef EXTERNAL_DISTRO -namespace NAMESPACE +namespace NAMESPACE { #endif -TcpManager::TcpParams::TcpParams() -: port(0), - maxConnections(10), - incomingBufferSize(64*1024), - outgoingBufferSize(64*1024), - allocatorBlockSize(8*1024), - allocatorBlockCount(16), - maxRecvMessageSize(0), - keepAliveDelay(0), - noDataTimeout(0) -{ - memset(bindAddress, 0, sizeof(bindAddress)); -} + TcpManager::TcpParams::TcpParams() + : port(0), + maxConnections(10), + incomingBufferSize(64 * 1024), + outgoingBufferSize(64 * 1024), + allocatorBlockSize(8 * 1024), + allocatorBlockCount(16), + maxRecvMessageSize(0), + keepAliveDelay(0), + noDataTimeout(0) + { + memset(bindAddress, 0, sizeof(bindAddress)); + } -TcpManager::TcpParams::TcpParams(const TcpParams &cpy) -: port(cpy.port), - maxConnections(cpy.maxConnections), - incomingBufferSize(cpy.incomingBufferSize), - outgoingBufferSize(cpy.outgoingBufferSize), - allocatorBlockSize(cpy.allocatorBlockSize), - allocatorBlockCount(cpy.allocatorBlockCount), - maxRecvMessageSize(cpy.maxRecvMessageSize), - keepAliveDelay(cpy.keepAliveDelay), - noDataTimeout(cpy.noDataTimeout) -{ -} + TcpManager::TcpParams::TcpParams(const TcpParams &cpy) + : port(cpy.port), + maxConnections(cpy.maxConnections), + incomingBufferSize(cpy.incomingBufferSize), + outgoingBufferSize(cpy.outgoingBufferSize), + allocatorBlockSize(cpy.allocatorBlockSize), + allocatorBlockCount(cpy.allocatorBlockCount), + maxRecvMessageSize(cpy.maxRecvMessageSize), + keepAliveDelay(cpy.keepAliveDelay), + noDataTimeout(cpy.noDataTimeout) + { + } -TcpManager::TcpManager(const TcpParams ¶ms) -: m_handler(nullptr), - m_keepAliveList(nullptr, 1), - m_aliveList(nullptr, 2), - m_noDataList(nullptr, 1), - m_dataList(nullptr, 2), - m_params(params), - m_refCount(1), - m_connectionList(nullptr), - m_connectionListCount(0), - m_socket(INVALID_SOCKET), - m_boundAsServer(false), - m_allocator(params.allocatorBlockSize, params.allocatorBlockCount), - m_keepAliveTimer(), - m_noDataTimer() -{ - if (params.keepAliveDelay > 0) - m_keepAliveTimer.start(); - - if (params.noDataTimeout > 0) - m_noDataTimer.start(); - -#if defined(WIN32) - WSADATA wsaData; - WSAStartup(MAKEWORD(1,1), &wsaData); - - FD_ZERO(&m_permfds);//select only used on win32 -#endif - -} - - -TcpManager::~TcpManager() -{ -#if defined(WIN32) - WSACleanup(); -#endif - - if (m_boundAsServer) - { -#if defined(WIN32) - closesocket(m_socket); -#else - close(m_socket); -#endif - } - while (m_connectionList != nullptr) - { - TcpConnection *con = m_connectionList; - m_connectionList = m_connectionList->m_nextConnection; - con->Release(); - m_connectionListCount--; - } -} - - -bool TcpManager::BindAsServer() -{ - - m_socket = socket(AF_INET, SOCK_STREAM, 0); - - if (m_socket != INVALID_SOCKET) - { -#if defined(WIN32) - FD_SET(m_socket, &m_permfds);//the socket this server is listening on - - unsigned long isNonBlocking = 1; - int outBufSize = m_params.outgoingBufferSize; - int inBufSize = m_params.incomingBufferSize; - int keepAlive = 1; - int reuseAddr = 1; - struct linger ld; - ld.l_onoff = 0; - ld.l_linger = 0; - - if (ioctlsocket(m_socket, FIONBIO, &isNonBlocking) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, (char *)&outBufSize, sizeof(outBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char *)&inBufSize, sizeof(inBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepAlive, sizeof(keepAlive)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuseAddr, sizeof(reuseAddr)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, (char *)&ld, sizeof(ld)) != 0 ) - { - return false; - } -#else // linux is to remain the default compile mode - unsigned long isNonBlocking = 1; - unsigned long keepAlive = 1; - unsigned long outBufSize = m_params.outgoingBufferSize; - unsigned long inBufSize = m_params.incomingBufferSize; - unsigned long reuseAddr = 1; - struct linger ld; - ld.l_onoff = 0; - ld.l_linger = 0; - - if (ioctl(m_socket, FIONBIO, &isNonBlocking) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, &outBufSize, sizeof(outBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, &inBufSize, sizeof(inBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(keepAlive)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, &ld, sizeof(ld)) != 0) - { - return false; - } -#endif - } - else - { - return false; - } - - - struct sockaddr_in addr_loc; - addr_loc.sin_family = AF_INET; - addr_loc.sin_port = htons(m_params.port); - addr_loc.sin_addr.s_addr = htonl(INADDR_ANY); - if (m_params.bindAddress[0] != 0) - { - unsigned long address = inet_addr(m_params.bindAddress); - if (address == INADDR_NONE) - { - struct hostent * lphp; - lphp = gethostbyname(m_params.bindAddress); - if (lphp != nullptr) - addr_loc.sin_addr.s_addr = ((struct in_addr *)(lphp->h_addr))->s_addr; - } - else - { - addr_loc.sin_addr.s_addr = address; - } - } - - if (bind(m_socket, (struct sockaddr *)&addr_loc, sizeof(addr_loc)) != 0) - { - return false; - } - - if (listen(m_socket, 1000) != 0) - { - return false; - } - - m_boundAsServer = true; - return true; -} - -TcpConnection *TcpManager::acceptClient() -{ - TcpConnection *newConn = nullptr; - - if (m_boundAsServer && m_connectionListCount < m_params.maxConnections) - { - - sockaddr_in addr; - int addrLength = sizeof(addr); - SOCKET sock = ::accept(m_socket, (sockaddr *) &addr, (socklen_t *) &addrLength); - - - if (sock != INVALID_SOCKET) - { - newConn = new TcpConnection(this, &m_allocator, m_params, sock, IPAddress(addr.sin_addr.s_addr), ntohs(addr.sin_port)); - addNewConnection(newConn); - if (m_handler != nullptr) - { - m_handler->OnConnectRequest(newConn); - } - } - } - - return newConn; -} - -void TcpManager::SetHandler(TcpManagerHandler *handler) -{ - m_handler = handler; -} - -SOCKET TcpManager::getMaxFD() -{ + TcpManager::TcpManager(const TcpParams ¶ms) + : m_handler(nullptr), + m_keepAliveList(nullptr, 1), + m_aliveList(nullptr, 2), + m_noDataList(nullptr, 1), + m_dataList(nullptr, 2), + m_params(params), + m_refCount(1), + m_connectionList(nullptr), + m_connectionListCount(0), + m_socket(INVALID_SOCKET), + m_boundAsServer(false), + m_allocator(params.allocatorBlockSize, params.allocatorBlockCount), + m_keepAliveTimer(), + m_noDataTimer() #ifdef WIN32 - return 0;//this param is not used on win32 for select, only on unix -#else - SOCKET maxfd = 0; - - if (m_boundAsServer) - maxfd = m_socket+1; - - TcpConnection *next = nullptr; - for (TcpConnection *con = m_connectionList ; con != nullptr ; con = next) - { - next = con->m_nextConnection; - if (con->GetStatus() != TcpConnection::StatusDisconnected && con->m_socket > maxfd) - { - maxfd = con->m_socket + 1; - } - } - return maxfd; + , m_permfds() #endif -} + { + if (params.keepAliveDelay > 0) + m_keepAliveTimer.start(); -TcpConnection *TcpManager::getConnection(SOCKET fd) -{ - TcpConnection *next = nullptr; - for (TcpConnection *con = m_connectionList ; con != nullptr ; con = next) - { - next = con->m_nextConnection; - if (con->m_socket == fd) - { - return con; - } - } - //if get here ,couldn't find it - return nullptr; -} + if (params.noDataTimeout > 0) + m_noDataTimer.start(); -bool TcpManager::GiveTime(unsigned maxTimeAcceptingConnections,unsigned maxSendTimePerConnection, unsigned maxRecvTimePerConnection) -{ - bool processedIncoming = false; +#if defined(WIN32) + WSADATA wsaData; + WSAStartup(MAKEWORD(1, 1), &wsaData); - if (maxTimeAcceptingConnections == 0 && maxSendTimePerConnection==0 && maxRecvTimePerConnection==0) - { - //they don't want to do anything now - return processedIncoming; - } + FD_ZERO(&m_permfds);//select only used on win32 +#endif + } - AddRef(); //keep a reference to ourself in case we callback to the application and the application releases us. + TcpManager::~TcpManager() + { +#if defined(WIN32) + WSACleanup(); +#endif + if (m_boundAsServer) + { +#if defined(WIN32) + closesocket(m_socket); +#else + close(m_socket); +#endif + } + while (m_connectionList != nullptr) + { + TcpConnection *con = m_connectionList; + m_connectionList = m_connectionList->m_nextConnection; + con->Release(); + m_connectionListCount--; + } + } + bool TcpManager::BindAsServer() + { + m_socket = socket(AF_INET, SOCK_STREAM, 0); - //first process outgoing on each connection, and finish establishing connections, if params say to - if (m_connectionListCount != 0 && maxSendTimePerConnection != 0) - { + if (m_socket != INVALID_SOCKET) + { +#if defined(WIN32) + FD_SET(m_socket, &m_permfds);//the socket this server is listening on - // Send output from last heartbeat - TcpConnection *next = nullptr; - for (TcpConnection *con = m_connectionList ; con != nullptr ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextConnection; - if (next) next->AddRef(); - if(con->GetStatus() == TcpConnection::StatusConnected) - { - Clock timer; - timer.start(); - while(!timer.isDone(maxSendTimePerConnection)) - { - int err = con->processOutgoing(); + unsigned long isNonBlocking = 1; + int outBufSize = m_params.outgoingBufferSize; + int inBufSize = m_params.incomingBufferSize; + int keepAlive = 1; + int reuseAddr = 1; + struct linger ld; + ld.l_onoff = 0; + ld.l_linger = 0; - if (err > 0) - { - //couldn't finish processing last request, don't try more - break; - } - else if (err < 0) - { - break; - } - } - con->Release(); - } - else if (con->GetStatus() == TcpConnection::StatusNegotiating) - { - if (con->finishConnect() < 0) - { + if (ioctlsocket(m_socket, FIONBIO, &isNonBlocking) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, (char *)&outBufSize, sizeof(outBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char *)&inBufSize, sizeof(inBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepAlive, sizeof(keepAlive)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuseAddr, sizeof(reuseAddr)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, (char *)&ld, sizeof(ld)) != 0) + { + return false; + } +#else // linux is to remain the default compile mode + unsigned long isNonBlocking = 1; + unsigned long keepAlive = 1; + unsigned long outBufSize = m_params.outgoingBufferSize; + unsigned long inBufSize = m_params.incomingBufferSize; + unsigned long reuseAddr = 1; + struct linger ld; + ld.l_onoff = 0; + ld.l_linger = 0; + + if (ioctl(m_socket, FIONBIO, &isNonBlocking) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, &outBufSize, sizeof(outBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, &inBufSize, sizeof(inBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(keepAlive)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, &ld, sizeof(ld)) != 0) + { + return false; + } +#endif + } + else + { + return false; + } + + struct sockaddr_in addr_loc; + addr_loc.sin_family = AF_INET; + addr_loc.sin_port = htons(m_params.port); + addr_loc.sin_addr.s_addr = htonl(INADDR_ANY); + if (m_params.bindAddress[0] != 0) + { + unsigned long address = inet_addr(m_params.bindAddress); + if (address == INADDR_NONE) + { + struct hostent * lphp; + lphp = gethostbyname(m_params.bindAddress); + if (lphp != nullptr) + addr_loc.sin_addr.s_addr = ((struct in_addr *)(lphp->h_addr))->s_addr; + } + else + { + addr_loc.sin_addr.s_addr = address; + } + } + + if (bind(m_socket, (struct sockaddr *)&addr_loc, sizeof(addr_loc)) != 0) + { + return false; + } + + if (listen(m_socket, 1000) != 0) + { + return false; + } + + m_boundAsServer = true; + return true; + } + + TcpConnection *TcpManager::acceptClient() + { + TcpConnection *newConn = nullptr; + + if (m_boundAsServer && m_connectionListCount < m_params.maxConnections) + { + sockaddr_in addr; + int addrLength = sizeof(addr); + SOCKET sock = ::accept(m_socket, (sockaddr *)&addr, (socklen_t *)&addrLength); + + if (sock != INVALID_SOCKET) + { + newConn = new TcpConnection(this, &m_allocator, m_params, sock, IPAddress(addr.sin_addr.s_addr), ntohs(addr.sin_port)); + addNewConnection(newConn); + if (m_handler != nullptr) + { + m_handler->OnConnectRequest(newConn); + } + } + } + + return newConn; + } + + void TcpManager::SetHandler(TcpManagerHandler *handler) + { + m_handler = handler; + } + + SOCKET TcpManager::getMaxFD() + { +#ifdef WIN32 + return 0;//this param is not used on win32 for select, only on unix +#else + SOCKET maxfd = 0; + + if (m_boundAsServer) + maxfd = m_socket + 1; + + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + next = con->m_nextConnection; + if (con->GetStatus() != TcpConnection::StatusDisconnected && con->m_socket > maxfd) + { + maxfd = con->m_socket + 1; + } + } + return maxfd; +#endif + } + + TcpConnection *TcpManager::getConnection(SOCKET fd) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + next = con->m_nextConnection; + if (con->m_socket == fd) + { + return con; + } + } + //if get here ,couldn't find it + return nullptr; + } + + bool TcpManager::GiveTime(unsigned maxTimeAcceptingConnections, unsigned maxSendTimePerConnection, unsigned maxRecvTimePerConnection) + { + bool processedIncoming = false; + + if (maxTimeAcceptingConnections == 0 && maxSendTimePerConnection == 0 && maxRecvTimePerConnection == 0) + { + //they don't want to do anything now + return processedIncoming; + } + + AddRef(); //keep a reference to ourself in case we callback to the application and the application releases us. + + //first process outgoing on each connection, and finish establishing connections, if params say to + if (m_connectionListCount != 0 && maxSendTimePerConnection != 0) + { + // Send output from last heartbeat + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextConnection; + if (next) next->AddRef(); + if (con->GetStatus() == TcpConnection::StatusConnected) + { + Clock timer; + timer.start(); + while (!timer.isDone(maxSendTimePerConnection)) + { + int err = con->processOutgoing(); + + if (err > 0) + { + //couldn't finish processing last request, don't try more + break; + } + else if (err < 0) + { + break; + } + } con->Release(); - continue; - } - con->Release(); - } - else //inactive client in client list???? - { - removeConnection(con); - con->Release(); - continue; - } - } - - } - - //process incoming messages (including connect requests) - if (( - m_boundAsServer //if in server mode and want to spend time accepting clients - && maxTimeAcceptingConnections != 0 - ) - || - ( - m_connectionListCount != 0 //if there are connections and want to spend time receiving on them - && maxRecvTimePerConnection != 0 - ) - ) - { -#ifdef WIN32 - SOCKET maxfd = getMaxFD(); //re-calc maxfd every time select on WIN32 - - //select on all fd's - struct timeval timeout; - - fd_set tmpfds; - tmpfds = m_permfds; - timeout.tv_sec = 0; - timeout.tv_usec = 0; - int cnt = select(maxfd, &tmpfds, nullptr, nullptr, &timeout); // blocks for timeout - - - if (cnt > 0) - { - if (m_boundAsServer && maxTimeAcceptingConnections != 0) - {//activity on our socket means connect requests - - //see if are new incoming clients - if (FD_ISSET(m_socket, &tmpfds)) - { - //yep - Clock timer; - timer.start(); - while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) - { - //loop - } - } - } - - - - //process incoming client messages - if (maxRecvTimePerConnection != 0) - { - TcpConnection *next = nullptr; - for (TcpConnection *con = m_connectionList ; con != nullptr ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextConnection; - if (next) next->AddRef(); - - SOCKET fd = con->m_socket; - if (fd == INVALID_SOCKET) - { - //invalid socket in list?, check if is connecting, otherwise, Disconnect and discard - if (con->GetStatus() != TcpConnection::StatusNegotiating) - { - removeConnection(con); - con->Release(); - continue; - } - } - - if (FD_ISSET(fd, &tmpfds)) - { - Clock timer; - timer.start(); - while(!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) - { - int err = con->processIncoming(); - if (err >= 0) - { - processedIncoming = true; - } - - if (err > 0) - { - //couldn't finish processing last request, don't try more - break; - } - else if (err < 0) - { - break; - } - - }//while(!timer...) - }//if (FD_ISSET...) + } + else if (con->GetStatus() == TcpConnection::StatusNegotiating) + { + if (con->finishConnect() < 0) + { + con->Release(); + continue; + } con->Release(); - }//for (...) - } //maxRecvTimePerConnection != 0 - }//cnt > 0 + } + else //inactive client in client list???? + { + removeConnection(con); + con->Release(); + continue; + } + } + } + + //process incoming messages (including connect requests) + if (( + m_boundAsServer //if in server mode and want to spend time accepting clients + && maxTimeAcceptingConnections != 0 + ) + || + ( + m_connectionListCount != 0 //if there are connections and want to spend time receiving on them + && maxRecvTimePerConnection != 0 + ) + ) + { +#ifdef WIN32 + SOCKET maxfd = getMaxFD(); //re-calc maxfd every time select on WIN32 + + //select on all fd's + struct timeval timeout; + + fd_set tmpfds; + tmpfds = m_permfds; + timeout.tv_sec = 0; + timeout.tv_usec = 0; + int cnt = select(maxfd, &tmpfds, nullptr, nullptr, &timeout); // blocks for timeout + + if (cnt > 0) + { + if (m_boundAsServer && maxTimeAcceptingConnections != 0) + {//activity on our socket means connect requests + //see if are new incoming clients + if (FD_ISSET(m_socket, &tmpfds)) + { + //yep + Clock timer; + timer.start(); + while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) + { + //loop + } + } + } + + //process incoming client messages + if (maxRecvTimePerConnection != 0) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextConnection; + if (next) next->AddRef(); + + SOCKET fd = con->m_socket; + if (fd == INVALID_SOCKET) + { + //invalid socket in list?, check if is connecting, otherwise, Disconnect and discard + if (con->GetStatus() != TcpConnection::StatusNegotiating) + { + removeConnection(con); + con->Release(); + continue; + } + } + + if (FD_ISSET(fd, &tmpfds)) + { + Clock timer; + timer.start(); + while (!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) + { + int err = con->processIncoming(); + if (err >= 0) + { + processedIncoming = true; + } + + if (err > 0) + { + //couldn't finish processing last request, don't try more + break; + } + else if (err < 0) + { + break; + } + }//while(!timer...) + }//if (FD_ISSET...) + con->Release(); + }//for (...) + } //maxRecvTimePerConnection != 0 + }//cnt > 0 #else //on UNIX use poll - int numfds = m_connectionListCount; - int idx = 0; - if (m_boundAsServer) - { - numfds++; - idx++; - } + int numfds = m_connectionListCount; + int idx = 0; + if (m_boundAsServer) + { + numfds++; + idx++; + } - struct pollfd pollfds[numfds]; + struct pollfd pollfds[numfds]; - if (m_boundAsServer) - { - pollfds[0].fd = m_socket; - pollfds[0].events |= POLLIN; - } + if (m_boundAsServer) + { + pollfds[0].fd = m_socket; + pollfds[0].events |= POLLIN; + } - TcpConnection *next = nullptr; - for (TcpConnection *con = m_connectionList ; con != nullptr ; con = next, idx++) - { - next = con->m_nextConnection; - pollfds[idx].fd = con->m_socket; - pollfds[idx].events |= POLLIN; - pollfds[idx].events |= POLLHUP; - } - + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next, idx++) + { + next = con->m_nextConnection; + pollfds[idx].fd = con->m_socket; + pollfds[idx].events |= POLLIN; + pollfds[idx].events |= POLLHUP; + } - int cnt = poll(pollfds, numfds, 1); + int cnt = poll(pollfds, numfds, 1); - if(cnt == SOCKET_ERROR) - { - //poll not working? - //TODO: need to notify client somehow, don't think we can assume a fatal error here - } - else if (cnt > 0) - { - for (idx = 0; idx < numfds; idx++) - { - //find corresponding TcpConnection - //TODO: optimize, seriously, this is takes linear time, every time - TcpConnection *con = getConnection(pollfds[idx].fd); + if (cnt == SOCKET_ERROR) + { + //poll not working? + //TODO: need to notify client somehow, don't think we can assume a fatal error here + } + else if (cnt > 0) + { + for (idx = 0; idx < numfds; idx++) + { + //find corresponding TcpConnection + //TODO: optimize, seriously, this is takes linear time, every time + TcpConnection *con = getConnection(pollfds[idx].fd); - if (pollfds[idx].revents & POLLIN) - { - if (m_boundAsServer && maxTimeAcceptingConnections != 0 && pollfds[idx].fd == m_socket) - { - //new incoming clients - Clock timer; - timer.start(); - while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) - { - //loop - } + if (pollfds[idx].revents & POLLIN) + { + if (m_boundAsServer && maxTimeAcceptingConnections != 0 && pollfds[idx].fd == m_socket) + { + //new incoming clients + Clock timer; + timer.start(); + while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) + { + //loop + } - continue;//don't try to readmsgs from listening fd - } - - //process regular msg(s) - if (con == nullptr) - { - close(pollfds[idx].fd); - continue; - } + continue;//don't try to readmsgs from listening fd + } - Clock timer; - timer.start(); - con->AddRef();//so it can't get deleted while we are checking it's status - while(!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) - { - int err = con->processIncoming(); - if (err >= 0) - { - processedIncoming = true; - } + //process regular msg(s) + if (con == nullptr) + { + close(pollfds[idx].fd); + continue; + } - if (err > 0) - { - //couldn't finish processing last request, don't try more - break; - } - else if (err < 0) - { - break; - } + Clock timer; + timer.start(); + con->AddRef();//so it can't get deleted while we are checking it's status + while (!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) + { + int err = con->processIncoming(); + if (err >= 0) + { + processedIncoming = true; + } - }//while(!timer....) - con->Release(); - }//if(pollfds[... - else if (pollfds[idx].revents & POLLHUP) - { - if (con == nullptr) - { - close(pollfds[idx].fd); - continue; - } + if (err > 0) + { + //couldn't finish processing last request, don't try more + break; + } + else if (err < 0) + { + break; + } + }//while(!timer....) + con->Release(); + }//if(pollfds[... + else if (pollfds[idx].revents & POLLHUP) + { + if (con == nullptr) + { + close(pollfds[idx].fd); + continue; + } - //Disconnect client - con->Disconnect(); - } - }//for (idx=0.... - }//else if (cnt > 0) + //Disconnect client + con->Disconnect(); + } + }//for (idx=0.... + }//else if (cnt > 0) #endif - }//wanted to process incoming messages or connect requests + }//wanted to process incoming messages or connect requests - //now process any keepalives, if time to do that - if (m_params.keepAliveDelay > 0 && m_keepAliveTimer.isDone(m_params.keepAliveDelay)) - { - TcpConnection *next = nullptr; - for (TcpConnection *con = m_keepAliveList.m_beginList ; con != nullptr ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextKeepAliveConnection; - if (next) next->AddRef(); - - con->Send(nullptr, 0); //note: this request will move the connection from the keepAliveList to the aliveList - con->Release(); - } + //now process any keepalives, if time to do that + if (m_params.keepAliveDelay > 0 && m_keepAliveTimer.isDone(m_params.keepAliveDelay)) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_keepAliveList.m_beginList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextKeepAliveConnection; + if (next) next->AddRef(); - //now move the complete alive list over to the keepalive list to reset those timers - m_keepAliveList.m_beginList = m_aliveList.m_beginList; - m_aliveList.m_beginList = nullptr; + con->Send(nullptr, 0); //note: this request will move the connection from the keepAliveList to the aliveList + con->Release(); + } - //switch id's for those connections that were in the alive list last go - around - int tmpID = m_aliveList.m_listID; - m_aliveList.m_listID = m_keepAliveList.m_listID; - m_keepAliveList.m_listID = tmpID; + //now move the complete alive list over to the keepalive list to reset those timers + m_keepAliveList.m_beginList = m_aliveList.m_beginList; + m_aliveList.m_beginList = nullptr; - m_keepAliveTimer.reset(); - m_keepAliveTimer.start(); - } + //switch id's for those connections that were in the alive list last go - around + int tmpID = m_aliveList.m_listID; + m_aliveList.m_listID = m_keepAliveList.m_listID; + m_keepAliveList.m_listID = tmpID; - //now process any noDataCons, if time to do that - if (m_params.noDataTimeout > 0 && m_noDataTimer.isDone(m_params.noDataTimeout)) - { - TcpConnection *next = nullptr; - for (TcpConnection *con = m_noDataList.m_beginList ; con != nullptr ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextRecvDataConnection; - if (next) next->AddRef(); + m_keepAliveTimer.reset(); + m_keepAliveTimer.start(); + } - //time to disconnect this guy - con->Disconnect(); - con->Release(); - } + //now process any noDataCons, if time to do that + if (m_params.noDataTimeout > 0 && m_noDataTimer.isDone(m_params.noDataTimeout)) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_noDataList.m_beginList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextRecvDataConnection; + if (next) next->AddRef(); - //now move the complete data list over to the nodata list to reset those timers - m_noDataList.m_beginList = m_dataList.m_beginList; - m_dataList.m_beginList = nullptr; + //time to disconnect this guy + con->Disconnect(); + con->Release(); + } - //switch id's for those connections that were in the data list last go - around - int tmpID = m_dataList.m_listID; - m_dataList.m_listID = m_noDataList.m_listID; - m_noDataList.m_listID = tmpID; + //now move the complete data list over to the nodata list to reset those timers + m_noDataList.m_beginList = m_dataList.m_beginList; + m_dataList.m_beginList = nullptr; - m_noDataTimer.reset(); - m_noDataTimer.start(); - } + //switch id's for those connections that were in the data list last go - around + int tmpID = m_dataList.m_listID; + m_dataList.m_listID = m_noDataList.m_listID; + m_noDataList.m_listID = tmpID; - Release(); + m_noDataTimer.reset(); + m_noDataTimer.start(); + } - return processedIncoming; -} + Release(); -TcpConnection *TcpManager::EstablishConnection(const char *serverAddress, unsigned short serverPort, unsigned timeout) -{ - if (m_boundAsServer) - { - //can't open outgoing connections when in server mode - // use a different TcpManager to do that - return nullptr; - } + return processedIncoming; + } - if (m_connectionListCount >= m_params.maxConnections) - return(nullptr); + TcpConnection *TcpManager::EstablishConnection(const char *serverAddress, unsigned short serverPort, unsigned timeout) + { + if (m_boundAsServer) + { + //can't open outgoing connections when in server mode + // use a different TcpManager to do that + return nullptr; + } - // get server address - unsigned long address = inet_addr(serverAddress); - if (address == INADDR_NONE) - { - struct hostent * lphp; - lphp = gethostbyname(serverAddress); - if (lphp == nullptr) - return(nullptr); - address = ((struct in_addr *)(lphp->h_addr))->s_addr; - } - IPAddress destIP(address); + if (m_connectionListCount >= m_params.maxConnections) + return(nullptr); - TcpConnection *con = new TcpConnection(this, &m_allocator, m_params, destIP, serverPort, timeout); - con->AddRef();//for the client - to conform to UdpLibrary method - addNewConnection(con); + // get server address + unsigned long address = inet_addr(serverAddress); + if (address == INADDR_NONE) + { + struct hostent * lphp; + lphp = gethostbyname(serverAddress); + if (lphp == nullptr) + return(nullptr); + address = ((struct in_addr *)(lphp->h_addr))->s_addr; + } + IPAddress destIP(address); - return con; -} + TcpConnection *con = new TcpConnection(this, &m_allocator, m_params, destIP, serverPort, timeout); + con->AddRef();//for the client - to conform to UdpLibrary method + addNewConnection(con); -void TcpManager::addNewConnection(TcpConnection *con) -{ - con->AddRef(); + return con; + } + + void TcpManager::addNewConnection(TcpConnection *con) + { + con->AddRef(); #ifdef WIN32 //uses select - if (con->m_socket != INVALID_SOCKET) - FD_SET(con->m_socket, &m_permfds); + if (con->m_socket != INVALID_SOCKET) + FD_SET(con->m_socket, &m_permfds); #endif - con->m_nextConnection = m_connectionList; - con->m_prevConnection = nullptr; - if (m_connectionList != nullptr) - m_connectionList->m_prevConnection = con; - m_connectionList = con; - m_connectionListCount++; + con->m_nextConnection = m_connectionList; + con->m_prevConnection = nullptr; + if (m_connectionList != nullptr) + m_connectionList->m_prevConnection = con; + m_connectionList = con; + m_connectionListCount++; - con->m_nextKeepAliveConnection = m_aliveList.m_beginList; - con->m_prevKeepAliveConnection = nullptr; - if (m_aliveList.m_beginList != nullptr) - m_aliveList.m_beginList->m_prevKeepAliveConnection = con; - m_aliveList.m_beginList = con; - con->m_aliveListId = m_keepAliveList.m_listID;//start it out thinking it's already in the alive list, since it is + con->m_nextKeepAliveConnection = m_aliveList.m_beginList; + con->m_prevKeepAliveConnection = nullptr; + if (m_aliveList.m_beginList != nullptr) + m_aliveList.m_beginList->m_prevKeepAliveConnection = con; + m_aliveList.m_beginList = con; + con->m_aliveListId = m_keepAliveList.m_listID;//start it out thinking it's already in the alive list, since it is - con->m_nextRecvDataConnection = m_dataList.m_beginList; - con->m_prevRecvDataConnection = nullptr; - if (m_dataList.m_beginList != nullptr) - m_dataList.m_beginList->m_prevRecvDataConnection = con; - m_dataList.m_beginList = con; - con->m_recvDataListId = m_noDataList.m_listID;//start it out thinking it's already in the data list, since it is -} + con->m_nextRecvDataConnection = m_dataList.m_beginList; + con->m_prevRecvDataConnection = nullptr; + if (m_dataList.m_beginList != nullptr) + m_dataList.m_beginList->m_prevRecvDataConnection = con; + m_dataList.m_beginList = con; + con->m_recvDataListId = m_noDataList.m_listID;//start it out thinking it's already in the data list, since it is + } -void TcpManager::removeConnection(TcpConnection *con) -{ - if (!con->wasRemovedFromMgr()) - { - con->setRemovedFromMgr(); - m_connectionListCount--; - #ifdef WIN32 //select only used on win32 - if (con->m_socket != INVALID_SOCKET) - { - FD_CLR(con->m_socket, &m_permfds); - } - #endif - if (con->m_prevConnection != nullptr) - con->m_prevConnection->m_nextConnection = con->m_nextConnection; - if (con->m_nextConnection != nullptr) - con->m_nextConnection->m_prevConnection = con->m_prevConnection; - if (m_connectionList == con) - m_connectionList = con->m_nextConnection; - con->m_nextConnection = nullptr; - con->m_prevConnection = nullptr; + void TcpManager::removeConnection(TcpConnection *con) + { + if (!con->wasRemovedFromMgr()) + { + con->setRemovedFromMgr(); + m_connectionListCount--; +#ifdef WIN32 //select only used on win32 + if (con->m_socket != INVALID_SOCKET) + { + FD_CLR(con->m_socket, &m_permfds); + } +#endif + if (con->m_prevConnection != nullptr) + con->m_prevConnection->m_nextConnection = con->m_nextConnection; + if (con->m_nextConnection != nullptr) + con->m_nextConnection->m_prevConnection = con->m_prevConnection; + if (m_connectionList == con) + m_connectionList = con->m_nextConnection; + con->m_nextConnection = nullptr; + con->m_prevConnection = nullptr; - if (con->m_prevKeepAliveConnection != nullptr) - con->m_prevKeepAliveConnection->m_nextKeepAliveConnection = con->m_nextKeepAliveConnection; - if (con->m_nextKeepAliveConnection != nullptr) - con->m_nextKeepAliveConnection->m_prevKeepAliveConnection = con->m_prevKeepAliveConnection; + if (con->m_prevKeepAliveConnection != nullptr) + con->m_prevKeepAliveConnection->m_nextKeepAliveConnection = con->m_nextKeepAliveConnection; + if (con->m_nextKeepAliveConnection != nullptr) + con->m_nextKeepAliveConnection->m_prevKeepAliveConnection = con->m_prevKeepAliveConnection; - if (m_aliveList.m_beginList == con) - m_aliveList.m_beginList = con->m_nextKeepAliveConnection; - else if (m_keepAliveList.m_beginList == con) - m_keepAliveList.m_beginList = con->m_nextKeepAliveConnection; - con->m_nextKeepAliveConnection = nullptr; - con->m_prevKeepAliveConnection = nullptr; + if (m_aliveList.m_beginList == con) + m_aliveList.m_beginList = con->m_nextKeepAliveConnection; + else if (m_keepAliveList.m_beginList == con) + m_keepAliveList.m_beginList = con->m_nextKeepAliveConnection; + con->m_nextKeepAliveConnection = nullptr; + con->m_prevKeepAliveConnection = nullptr; + if (con->m_prevRecvDataConnection != nullptr) + con->m_prevRecvDataConnection->m_nextRecvDataConnection = con->m_nextRecvDataConnection; + if (con->m_nextRecvDataConnection != nullptr) + con->m_nextRecvDataConnection->m_prevRecvDataConnection = con->m_prevRecvDataConnection; + if (m_dataList.m_beginList == con) + m_dataList.m_beginList = con->m_nextRecvDataConnection; + else if (m_noDataList.m_beginList == con) + m_noDataList.m_beginList = con->m_nextRecvDataConnection; + con->m_nextRecvDataConnection = nullptr; + con->m_prevRecvDataConnection = nullptr; - if (con->m_prevRecvDataConnection != nullptr) - con->m_prevRecvDataConnection->m_nextRecvDataConnection = con->m_nextRecvDataConnection; - if (con->m_nextRecvDataConnection != nullptr) - con->m_nextRecvDataConnection->m_prevRecvDataConnection = con->m_prevRecvDataConnection; + con->Release(); + } + } - if (m_dataList.m_beginList == con) - m_dataList.m_beginList = con->m_nextRecvDataConnection; - else if (m_noDataList.m_beginList == con) - m_noDataList.m_beginList = con->m_nextRecvDataConnection; - con->m_nextRecvDataConnection = nullptr; - con->m_prevRecvDataConnection = nullptr; + void TcpManager::AddRef() + { + m_refCount++; + } + void TcpManager::Release() + { + if (--m_refCount == 0) + delete this; + } + IPAddress TcpManager::GetLocalIp() const + { + struct sockaddr_in addr_self; + memset(&addr_self, 0, sizeof(addr_self)); + socklen_t len = sizeof(addr_self); + getsockname(m_socket, (struct sockaddr *)&addr_self, &len); + return(IPAddress(addr_self.sin_addr.s_addr)); + } - con->Release(); - } -} - -void TcpManager::AddRef() -{ - m_refCount++; -} - -void TcpManager::Release() -{ - if (--m_refCount == 0) - delete this; -} - -IPAddress TcpManager::GetLocalIp() const -{ - struct sockaddr_in addr_self; - memset(&addr_self, 0, sizeof(addr_self)); - socklen_t len = sizeof(addr_self); - getsockname(m_socket, (struct sockaddr *)&addr_self, &len); - return(IPAddress(addr_self.sin_addr.s_addr)); - -} - -unsigned int TcpManager::GetLocalPort() const -{ - struct sockaddr_in addr_self; - memset(&addr_self, 0, sizeof(addr_self)); - socklen_t len = sizeof(addr_self); - getsockname(m_socket, (struct sockaddr *)&addr_self, &len); - return(ntohs(addr_self.sin_port)); -} - + unsigned int TcpManager::GetLocalPort() const + { + struct sockaddr_in addr_self; + memset(&addr_self, 0, sizeof(addr_self)); + socklen_t len = sizeof(addr_self); + getsockname(m_socket, (struct sockaddr *)&addr_self, &len); + return(ntohs(addr_self.sin_port)); + } #ifdef EXTERNAL_DISTRO }; -#endif - - +#endif \ No newline at end of file diff --git a/external/ours/library/crypto/src/shared/original/queue.cpp b/external/ours/library/crypto/src/shared/original/queue.cpp index 9ce378de..590b8899 100755 --- a/external/ours/library/crypto/src/shared/original/queue.cpp +++ b/external/ours/library/crypto/src/shared/original/queue.cpp @@ -17,16 +17,16 @@ public: next = 0; } - inline unsigned int MaxSize() const {return buf.size;} + inline unsigned int MaxSize() const { return buf.size; } inline unsigned int CurrentSize() const { - return m_tail-m_head; + return m_tail - m_head; } inline bool UsedUp() const { - return (m_head==MaxSize()); + return (m_head == MaxSize()); } inline void Clear() @@ -36,48 +36,48 @@ public: inline unsigned int Put(byte inByte) { - if (MaxSize()==m_tail) + if (MaxSize() == m_tail) return 0; - buf[m_tail++]=inByte; + buf[m_tail++] = inByte; return 1; } inline unsigned int Put(const byte *inString, unsigned int length) { - unsigned int l = STDMIN(length, MaxSize()-m_tail); - memcpy(buf+m_tail, inString, l); + unsigned int l = STDMIN(length, MaxSize() - m_tail); + memcpy(buf + m_tail, inString, l); m_tail += l; return l; } inline unsigned int Peek(byte &outByte) const { - if (m_tail==m_head) + if (m_tail == m_head) return 0; - outByte=buf[m_head]; + outByte = buf[m_head]; return 1; } inline unsigned int Peek(byte *target, unsigned int copyMax) const { - unsigned int len = STDMIN(copyMax, m_tail-m_head); - memcpy(target, buf+m_head, len); + unsigned int len = STDMIN(copyMax, m_tail - m_head); + memcpy(target, buf + m_head, len); return len; } inline unsigned int CopyTo(BufferedTransformation &target) const { - unsigned int len = m_tail-m_head; - target.Put(buf+m_head, len); + unsigned int len = m_tail - m_head; + target.Put(buf + m_head, len); return len; } inline unsigned int CopyTo(BufferedTransformation &target, unsigned int copyMax) const { - unsigned int len = STDMIN(copyMax, m_tail-m_head); - target.Put(buf+m_head, len); + unsigned int len = STDMIN(copyMax, m_tail - m_head); + target.Put(buf + m_head, len); return len; } @@ -111,14 +111,14 @@ public: inline unsigned int Skip(unsigned int skipMax) { - unsigned int len = STDMIN(skipMax, m_tail-m_head); + unsigned int len = STDMIN(skipMax, m_tail - m_head); m_head += len; return len; } inline byte operator[](unsigned int i) const { - return buf[m_head+i]; + return buf[m_head + i]; } ByteQueueNode *next; @@ -130,7 +130,7 @@ public: // ******************************************************** ByteQueue::ByteQueue(unsigned int m_nodeSize) - : m_nodeSize(0), m_lazyLength(0) + : m_nodeSize(0), m_lazyLength(0), m_lazyString(nullptr) { m_head = m_tail = new ByteQueueNode(m_nodeSize); } @@ -146,7 +146,7 @@ void ByteQueue::CopyFrom(const ByteQueue ©) m_nodeSize = copy.m_nodeSize; m_head = m_tail = new ByteQueueNode(*copy.m_head); - for (ByteQueueNode *current=copy.m_head->next; current; current=current->next) + for (ByteQueueNode *current = copy.m_head->next; current; current = current->next) { m_tail->next = new ByteQueueNode(*current); m_tail = m_tail->next; @@ -166,18 +166,18 @@ void ByteQueue::Destroy() { ByteQueueNode *next; - for (ByteQueueNode *current=m_head; current; current=next) + for (ByteQueueNode *current = m_head; current; current = next) { - next=current->next; + next = current->next; delete current; } } unsigned long ByteQueue::CurrentSize() const { - unsigned long size=0; + unsigned long size = 0; - for (ByteQueueNode *current=m_head; current; current=current->next) + for (ByteQueueNode *current = m_head; current; current = current->next) size += current->CurrentSize(); return size + m_lazyLength; @@ -185,7 +185,7 @@ unsigned long ByteQueue::CurrentSize() const bool ByteQueue::IsEmpty() const { - return m_head==m_tail && m_head->CurrentSize()==0 && m_lazyLength==0; + return m_head == m_tail && m_head->CurrentSize() == 0 && m_lazyLength == 0; } void ByteQueue::Clear() @@ -214,7 +214,7 @@ void ByteQueue::Put(const byte *inString, unsigned int length) FinalizeLazyPut(); unsigned int len; - while ((len=m_tail->Put(inString, length)) < length) + while ((len = m_tail->Put(inString, length)) < length) { m_tail->next = new ByteQueueNode(m_nodeSize); m_tail = m_tail->next; @@ -227,8 +227,8 @@ void ByteQueue::CleanupUsedNodes() { while (m_head != m_tail && m_head->UsedUp()) { - ByteQueueNode *temp=m_head; - m_head=m_head->next; + ByteQueueNode *temp = m_head; + m_head = m_head->next; delete temp; } @@ -302,7 +302,7 @@ unsigned long ByteQueue::Skip(unsigned long skipMax) unsigned long ByteQueue::TransferTo(BufferedTransformation &target, unsigned long transferMax) { unsigned long bytesLeft = transferMax; - for (ByteQueueNode *current=m_head; bytesLeft && current; current=current->next) + for (ByteQueueNode *current = m_head; bytesLeft && current; current = current->next) bytesLeft -= current->TransferTo(target, bytesLeft); CleanupUsedNodes(); @@ -320,7 +320,7 @@ unsigned long ByteQueue::TransferTo(BufferedTransformation &target, unsigned lon unsigned long ByteQueue::CopyTo(BufferedTransformation &target, unsigned long copyMax) const { unsigned long bytesLeft = copyMax; - for (ByteQueueNode *current=m_head; bytesLeft && current; current=current->next) + for (ByteQueueNode *current = m_head; bytesLeft && current; current = current->next) bytesLeft -= current->CopyTo(target, bytesLeft); if (bytesLeft && m_lazyLength) { @@ -409,11 +409,11 @@ bool ByteQueue::operator==(const ByteQueue &rhs) const byte ByteQueue::operator[](unsigned long i) const { - for (ByteQueueNode *current=m_head; current; current=current->next) + for (ByteQueueNode *current = m_head; current; current = current->next) { if (i < current->CurrentSize()) return (*current)[i]; - + i -= current->CurrentSize(); } @@ -461,8 +461,8 @@ unsigned long ByteQueue::Walker::TransferTo(BufferedTransformation &target, unsi unsigned long bytesLeft = transferMax; while (m_node) { - unsigned int len = STDMIN(bytesLeft, (unsigned long)m_node->CurrentSize()-m_offset); - target.Put(m_node->buf+m_node->m_head+m_offset, len); + unsigned int len = STDMIN(bytesLeft, (unsigned long)m_node->CurrentSize() - m_offset); + target.Put(m_node->buf + m_node->m_head + m_offset, len); m_position += len; bytesLeft -= len; @@ -497,4 +497,4 @@ unsigned long ByteQueue::Walker::CopyTo(BufferedTransformation &target, unsigned return Walker(*this).TransferTo(target, copyMax); } -NAMESPACE_END +NAMESPACE_END \ No newline at end of file diff --git a/external/ours/library/localization/src/shared/LocalizedStringTableReaderWriter.cpp b/external/ours/library/localization/src/shared/LocalizedStringTableReaderWriter.cpp index e7dfbf27..91ea3b7e 100755 --- a/external/ours/library/localization/src/shared/LocalizedStringTableReaderWriter.cpp +++ b/external/ours/library/localization/src/shared/LocalizedStringTableReaderWriter.cpp @@ -20,64 +20,64 @@ namespace LocalizedStringTableReaderWriterNamespace { - void unfubarMicrosoftInvalidTextCharacters (Unicode::String & str) + void unfubarMicrosoftInvalidTextCharacters(Unicode::String & str) { typedef std::pair FubarCharacterInfo; typedef std::pair FubarStringInfo; - static const FubarCharacterInfo FubarCharactersCourtesyMicrosoft [] = + static const FubarCharacterInfo FubarCharactersCourtesyMicrosoft[] = { - FubarCharacterInfo (139, '<'), - FubarCharacterInfo (155, '>'), + FubarCharacterInfo(139, '<'), + FubarCharacterInfo(155, '>'), - FubarCharacterInfo (8216, '\''), - FubarCharacterInfo (8217, '\''), - FubarCharacterInfo (8221, '"'), - FubarCharacterInfo (8220, '"'), - FubarCharacterInfo (149, '-'), - FubarCharacterInfo (150, '-'), - FubarCharacterInfo (151, '-'), - FubarCharacterInfo (152, '~') + FubarCharacterInfo(8216, '\''), + FubarCharacterInfo(8217, '\''), + FubarCharacterInfo(8221, '"'), + FubarCharacterInfo(8220, '"'), + FubarCharacterInfo(149, '-'), + FubarCharacterInfo(150, '-'), + FubarCharacterInfo(151, '-'), + FubarCharacterInfo(152, '~') }; - - static const int FubarCharactersCourtesyMicrosoftLength = sizeof (FubarCharactersCourtesyMicrosoft) / sizeof (FubarCharactersCourtesyMicrosoft[0]); - - static const FubarStringInfo FubarStringsCourtesyMicrosoft [] = + + static const int FubarCharactersCourtesyMicrosoftLength = sizeof(FubarCharactersCourtesyMicrosoft) / sizeof(FubarCharactersCourtesyMicrosoft[0]); + + static const FubarStringInfo FubarStringsCourtesyMicrosoft[] = { - FubarStringInfo (133, Unicode::narrowToWide ("...")), - //-- carriage return - FubarStringInfo (13, Unicode::narrowToWide ("")) + FubarStringInfo(133, Unicode::narrowToWide("...")), + //-- carriage return + FubarStringInfo(13, Unicode::narrowToWide("")) }; - - static const int FubarStringsCourtesyMicrosoftLength = sizeof (FubarStringsCourtesyMicrosoft) / sizeof (FubarStringsCourtesyMicrosoft[0]); - + + static const int FubarStringsCourtesyMicrosoftLength = sizeof(FubarStringsCourtesyMicrosoft) / sizeof(FubarStringsCourtesyMicrosoft[0]); + { for (int i = 0; i < FubarCharactersCourtesyMicrosoftLength; ++i) { - const Unicode::unicode_char_t correctCharacter = FubarCharactersCourtesyMicrosoft [i].second; - const Unicode::unicode_char_t fubarCharacter = FubarCharactersCourtesyMicrosoft [i].first; - + const Unicode::unicode_char_t correctCharacter = FubarCharactersCourtesyMicrosoft[i].second; + const Unicode::unicode_char_t fubarCharacter = FubarCharactersCourtesyMicrosoft[i].first; + size_t pos = 0; - while ((pos = str.find (fubarCharacter, pos)) != Unicode::String::npos) + while ((pos = str.find(fubarCharacter, pos)) != Unicode::String::npos) { - str [pos] = correctCharacter; + str[pos] = correctCharacter; ++pos; } } } - + { for (int i = 0; i < FubarStringsCourtesyMicrosoftLength; ++i) { - const Unicode::unicode_char_t fubarCharacter = FubarStringsCourtesyMicrosoft [i].first; - const Unicode::String & correctString = FubarStringsCourtesyMicrosoft [i].second; - + const Unicode::unicode_char_t fubarCharacter = FubarStringsCourtesyMicrosoft[i].first; + const Unicode::String & correctString = FubarStringsCourtesyMicrosoft[i].second; + size_t pos = 0; - - while ((pos = str.find (fubarCharacter, pos)) != Unicode::String::npos) + + while ((pos = str.find(fubarCharacter, pos)) != Unicode::String::npos) { - str.replace (pos, 1, correctString); - pos += correctString.size (); + str.replace(pos, 1, correctString); + pos += correctString.size(); } } } @@ -88,20 +88,18 @@ using namespace LocalizedStringTableReaderWriterNamespace; //----------------------------------------------------------------- -LocalizedStringTableRW::LocalizedStringTableRW (const Unicode::NarrowString & filename) : -LocalizedStringTable (filename), -m_idNameMap () +LocalizedStringTableRW::LocalizedStringTableRW(const Unicode::NarrowString & filename) : + LocalizedStringTable(filename), + m_idNameMap() { - } //----------------------------------------------------------------- -LocalizedStringTableRW::LocalizedStringTableRW (const LocalizedStringTable & rhs) : -LocalizedStringTable (rhs), -m_idNameMap () +LocalizedStringTableRW::LocalizedStringTableRW(const LocalizedStringTable & rhs) : + LocalizedStringTable(rhs), + m_idNameMap() { - } //----------------------------------------------------------------- @@ -112,26 +110,26 @@ bool LocalizedStringTableRW::str_write(AbstractFile & fl, LocalizedString & locs LocalizedString::id_type id = locstr.m_id; LocalizedString::crc_type crcSource = locstr.m_sourceCrc; - LocalizedString::id_type buflen = locstr.m_str.length (); + LocalizedString::id_type buflen = locstr.m_str.length(); - if (!fl.write (sizeof (LocalizedString::id_type), &id)) + if (!fl.write(sizeof(LocalizedString::id_type), &id)) return false; - if (!fl.write (sizeof (LocalizedString::crc_type), &crcSource)) + if (!fl.write(sizeof(LocalizedString::crc_type), &crcSource)) return false; - if (!fl.write (sizeof (LocalizedString::id_type), &buflen)) + if (!fl.write(sizeof(LocalizedString::id_type), &buflen)) return false; // TODO: swab this buffer - Unicode::unicode_char_t * buf = new Unicode::unicode_char_t [buflen+1]; + Unicode::unicode_char_t * buf = new Unicode::unicode_char_t[buflen + 1]; - assert (buf != nullptr); //lint !e1924 // c-style cast. MSVC bug + assert(buf != nullptr); //lint !e1924 // c-style cast. MSVC bug - buf [buflen] = 0; - memcpy (buf, locstr.m_str.c_str (), sizeof (Unicode::unicode_char_t) * buflen); + buf[buflen] = 0; + memcpy(buf, locstr.m_str.c_str(), sizeof(Unicode::unicode_char_t) * buflen); - if (buflen && !fl.write (buflen * sizeof (Unicode::unicode_char_t), buf)) + if (buflen && !fl.write(buflen * sizeof(Unicode::unicode_char_t), buf)) { delete[] buf; return false; @@ -148,48 +146,47 @@ bool LocalizedStringTableRW::write(AbstractFile & fl) const { // TODO: swab these values on big endian systems LocalizedString::id_type next_unique = m_nextUniqueId; - LocalizedString::id_type num_entries = m_map.size (); - - if (!fl.write (sizeof (LocalizedString::id_type), &next_unique)) + LocalizedString::id_type num_entries = m_map.size(); + + if (!fl.write(sizeof(LocalizedString::id_type), &next_unique)) return false; - - if (!fl.write (sizeof (LocalizedString::id_type), &num_entries)) + + if (!fl.write(sizeof(LocalizedString::id_type), &num_entries)) return false; // write the string table - + { - for (Map_t::const_iterator iter = m_map.begin (); iter != m_map.end (); ++iter) + for (Map_t::const_iterator iter = m_map.begin(); iter != m_map.end(); ++iter) { if (str_write(fl, *((*iter).second)) == false) return false; } } - + // write the string/id map { - for (NameMap_t::const_iterator iter = m_nameMap.begin (); iter != m_nameMap.end (); ++iter) + for (NameMap_t::const_iterator iter = m_nameMap.begin(); iter != m_nameMap.end(); ++iter) { - // TODO: swab all these values on big endian systems - LocalizedString::id_type id = (*iter).second; - LocalizedString::id_type buflen = (*iter).first.length (); + LocalizedString::id_type id = (*iter).second; + LocalizedString::id_type buflen = (*iter).first.length(); - if (!fl.write (sizeof (LocalizedString::id_type), &id)) - return false; - - if (!fl.write (sizeof (LocalizedString::id_type), &buflen)) + if (!fl.write(sizeof(LocalizedString::id_type), &id)) return false; - char * buf = new char [buflen + 1]; + if (!fl.write(sizeof(LocalizedString::id_type), &buflen)) + return false; - assert (buf != nullptr); //lint !e1924 // c-style cast. MSVC bug + char * buf = new char[buflen + 1]; - buf [buflen] = 0; + assert(buf != nullptr); //lint !e1924 // c-style cast. MSVC bug - memcpy (buf, (*iter).first.c_str (), buflen); + buf[buflen] = 0; - if (buflen && !fl.write (sizeof (char) * buflen, buf)) + memcpy(buf, (*iter).first.c_str(), buflen); + + if (buflen && !fl.write(sizeof(char) * buflen, buf)) { delete[] buf; buf = 0; @@ -204,75 +201,73 @@ bool LocalizedStringTableRW::write(AbstractFile & fl) const return true; } - // ---------------------------------------------------------------------- /** */ -LocalizedStringTableRW *LocalizedStringTableRW::loadRW (AbstractFileFactory & fileFactory, const Unicode::NarrowString & filename) +LocalizedStringTableRW *LocalizedStringTableRW::loadRW(AbstractFileFactory & fileFactory, const Unicode::NarrowString & filename) { char version = -1; - - AbstractFile * const fl = openLoadFile (fileFactory, filename, version); - + + AbstractFile * const fl = openLoadFile(fileFactory, filename, version); + if (fl == 0) return 0; - - LocalizedStringTableRW * table = 0; - if (!fl->isOpen ()) + LocalizedStringTableRW * table = nullptr; + + if (!fl->isOpen()) { - } else { switch (version) { case 0: - table = new LocalizedStringTableRW (filename); - assert (table != nullptr); //lint !e1924 // c-style cast. MSVC bug - - if (table->load_0000 (*fl) == false) + table = new LocalizedStringTableRW(filename); + assert(table != nullptr); //lint !e1924 // c-style cast. MSVC bug + + if (table->load_0000(*fl) == false) { delete table; - table = 0; + table = nullptr; } break; case 1: - table = new LocalizedStringTableRW (filename); - assert (table != nullptr); //lint !e1924 // c-style cast. MSVC bug - - if (table->load_0001 (*fl) == false) + table = new LocalizedStringTableRW(filename); + assert(table != nullptr); //lint !e1924 // c-style cast. MSVC bug + + if (table->load_0001(*fl) == false) { delete table; - table = 0; + table = nullptr; } break; default: - assert (true); //lint !e1924 // c-style cast. MSVC bug + assert(true); //lint !e1924 // c-style cast. MSVC bug break; } } - - delete fl; - - //Go through all the strings and un-microsoft-fubar them - for(Map_t::iterator mapIter = table->m_map.begin(); mapIter != table->m_map.end(); ++mapIter) - { - LocalizedString *str = (*mapIter).second; - Unicode::String & strRef = str->m_str; - LocalizedStringTableReaderWriterNamespace::unfubarMicrosoftInvalidTextCharacters(strRef); - } - // populate idNameMap + delete fl; + if (table) { - table->m_idNameMap.clear (); - - for (NameMap_t::const_iterator iter = table->m_nameMap.begin (); iter != table->m_nameMap.end (); ++iter) + //Go through all the strings and un-microsoft-fubar them + for (Map_t::iterator mapIter = table->m_map.begin(); mapIter != table->m_map.end(); ++mapIter) { - table->m_idNameMap.insert (IdNameMap_t::value_type ((*iter).second, (*iter).first)); + LocalizedString *str = (*mapIter).second; + Unicode::String & strRef = str->m_str; + LocalizedStringTableReaderWriterNamespace::unfubarMicrosoftInvalidTextCharacters(strRef); + } + + // populate idNameMap + table->m_idNameMap.clear(); + + for (NameMap_t::const_iterator iter = table->m_nameMap.begin(); iter != table->m_nameMap.end(); ++iter) + { + table->m_idNameMap.insert(IdNameMap_t::value_type((*iter).second, (*iter).first)); } } @@ -283,71 +278,71 @@ LocalizedStringTableRW *LocalizedStringTableRW::loadRW (AbstractFileFactory & fi /** */ -bool LocalizedStringTableRW::writeRW (AbstractFileFactory & fileFactory, const Unicode::NarrowString & filename) const +bool LocalizedStringTableRW::writeRW(AbstractFileFactory & fileFactory, const Unicode::NarrowString & filename) const { //Go through all the strings and un-microsoft-fubar them - for(Map_t::const_iterator mapIter = m_map.begin(); mapIter != m_map.end(); ++mapIter) + for (Map_t::const_iterator mapIter = m_map.begin(); mapIter != m_map.end(); ++mapIter) { LocalizedString *str = (*mapIter).second; Unicode::String & strRef = str->m_str; LocalizedStringTableReaderWriterNamespace::unfubarMicrosoftInvalidTextCharacters(strRef); } - - AbstractFile * const fl = fileFactory.createFile (filename.c_str (), "wb"); - + + AbstractFile * const fl = fileFactory.createFile(filename.c_str(), "wb"); + if (fl == 0) return false; - + bool retval = false; - - if (!fl->isOpen ()) + + if (!fl->isOpen()) { retval = false; } else { // TODO: swab magic if big endian - + magic_type local_magic = LocalizedStringTable::ms_MAGIC; - - if (!fl->write (sizeof (magic_type), &local_magic)) + + if (!fl->write(sizeof(magic_type), &local_magic)) { delete fl; return false; } - + char currentVersion = LocalizedStringTable::getCurrentVersion(); - if (!fl->write(sizeof (char), ¤tVersion)) + if (!fl->write(sizeof(char), ¤tVersion)) { delete fl; return false; } - + retval = write(*fl); } - - delete fl; + + delete fl; return retval; } //----------------------------------------------------------------- -LocalizedString * LocalizedStringTableRW::addString (const Unicode::String & str, Unicode::NarrowString & theNameResult) +LocalizedString * LocalizedStringTableRW::addString(const Unicode::String & str, Unicode::NarrowString & theNameResult) { - LocalizedString * const locstr = (m_map [m_nextUniqueId] = new LocalizedString (m_nextUniqueId, int(time(0)), str)); + LocalizedString * const locstr = (m_map[m_nextUniqueId] = new LocalizedString(m_nextUniqueId, int(time(0)), str)); - assert (locstr != nullptr); //lint !e1924 // c-style cast. MSVC bug + assert(locstr != nullptr); //lint !e1924 // c-style cast. MSVC bug char buf[64]; - sprintf (buf, "%03ld_default", m_nextUniqueId); + sprintf(buf, "%03ld_default", m_nextUniqueId); Unicode::NarrowString name(buf); - const std::pair retval = m_nameMap.insert (NameMap_t::value_type (name, m_nextUniqueId)); + const std::pair retval = m_nameMap.insert(NameMap_t::value_type(name, m_nextUniqueId)); - assert (retval.second == true); //lint !e1924 // c-style cast. MSVC bug - - m_idNameMap [locstr->getId ()] = name; + assert(retval.second == true); //lint !e1924 // c-style cast. MSVC bug + + m_idNameMap[locstr->getId()] = name; theNameResult = name; @@ -358,197 +353,193 @@ LocalizedString * LocalizedStringTableRW::addString (const Unicode::String & st //----------------------------------------------------------------- -LocalizedString * LocalizedStringTableRW::addString (LocalizedString * locstr, const Unicode::NarrowString & name, std::string & resultStr) +LocalizedString * LocalizedStringTableRW::addString(LocalizedString * locstr, const Unicode::NarrowString & name, std::string & resultStr) { - char buf [1024]; - const size_t id = locstr->getId (); - + char buf[1024]; + const size_t id = locstr->getId(); + { - Map_t::const_iterator it = m_map.find (id); - if (it != m_map.end ()) + Map_t::const_iterator it = m_map.find(id); + if (it != m_map.end()) { - const std::string * old_name = getNameById (id); + const std::string * old_name = getNameById(id); const LocalizedString * old_locstr = (*it).second; - const std::string old_str = old_locstr ? Unicode::wideToNarrow (old_locstr->getString ()) : std::string (); - - sprintf (buf, + const std::string old_str = old_locstr ? Unicode::wideToNarrow(old_locstr->getString()) : std::string(); + + sprintf(buf, "LocalizedStringTableRW::addString failed inserting duplicate id [%d]\n" "Existing string name=[%s], str=[%s]\n", - id, - old_name ? old_name->c_str () : "", - old_str.c_str ()); + id, + old_name ? old_name->c_str() : "", + old_str.c_str()); resultStr += buf; return 0; } } { - NameMap_t::const_iterator it = m_nameMap.find (name); - if (it != m_nameMap.end ()) + NameMap_t::const_iterator it = m_nameMap.find(name); + if (it != m_nameMap.end()) { - const size_t old_id = (*it).second; - const std::string * old_name = getNameById (old_id); - const LocalizedString * old_locstr = getLocalizedString (old_id); - const std::string old_str = old_locstr ? Unicode::wideToNarrow (old_locstr->getString ()) : std::string (); - - sprintf (buf, + const size_t old_id = (*it).second; + const std::string * old_name = getNameById(old_id); + const LocalizedString * old_locstr = getLocalizedString(old_id); + const std::string old_str = old_locstr ? Unicode::wideToNarrow(old_locstr->getString()) : std::string(); + + sprintf(buf, "LocalizedStringTableRW::addString failed inserting duplicate name [%s]\n" "Existing string id=[%d] name=[%s], str=[%s]\n", - name.c_str (), - id, - old_name ? old_name->c_str () : "", - old_str.c_str ()); + name.c_str(), + id, + old_name ? old_name->c_str() : "", + old_str.c_str()); resultStr += buf; return 0; } } { - IdNameMap_t::const_iterator it = m_idNameMap.find (id); - if (it != m_idNameMap.end ()) + IdNameMap_t::const_iterator it = m_idNameMap.find(id); + if (it != m_idNameMap.end()) { - const std::string & old_name = (*it).second; - const LocalizedString * old_locstr = getLocalizedString (id); - const std::string old_str = old_locstr ? Unicode::wideToNarrow (old_locstr->getString ()) : std::string (); - - sprintf (buf, + const std::string & old_name = (*it).second; + const LocalizedString * old_locstr = getLocalizedString(id); + const std::string old_str = old_locstr ? Unicode::wideToNarrow(old_locstr->getString()) : std::string(); + + sprintf(buf, "LocalizedStringTableRW::addString failed inserting duplicate name [%s]\n" "Existing string name=[%s], str=[%s]\n", - name.c_str (), - old_name.c_str (), - old_str.c_str ()); + name.c_str(), + old_name.c_str(), + old_str.c_str()); resultStr += buf; return 0; } } - m_map [id] = locstr; - m_nameMap [name] = locstr->getId (); - m_idNameMap [id] = name; + m_map[id] = locstr; + m_nameMap[name] = locstr->getId(); + m_idNameMap[id] = name; - m_nextUniqueId = std::max(m_nextUniqueId, locstr->getId () + 1); + m_nextUniqueId = std::max(m_nextUniqueId, locstr->getId() + 1); return locstr; } //---------------------------------------------------------------------- -LocalizedString * LocalizedStringTableRW::addString (LocalizedString * locstr, const Unicode::String & name, std::string & resultStr) +LocalizedString * LocalizedStringTableRW::addString(LocalizedString * locstr, const Unicode::String & name, std::string & resultStr) { - return addString (locstr, Unicode::wideToNarrow (name), resultStr); + return addString(locstr, Unicode::wideToNarrow(name), resultStr); } //----------------------------------------------------------------- -bool LocalizedStringTableRW::removeStringByName (const Unicode::NarrowString & name) +bool LocalizedStringTableRW::removeStringByName(const Unicode::NarrowString & name) { + NameMap_t::iterator find_iter_id = m_nameMap.find(name); - NameMap_t::iterator find_iter_id = m_nameMap.find (name); - - if (find_iter_id == m_nameMap.end ()) + if (find_iter_id == m_nameMap.end()) return false; const size_t id = (*find_iter_id).second; - Map_t::iterator find_iter_string = m_map.find (id); + Map_t::iterator find_iter_string = m_map.find(id); - assert (find_iter_string != m_map.end ()); //lint !e1924 // c-style cast. MSVC bug + assert(find_iter_string != m_map.end()); //lint !e1924 // c-style cast. MSVC bug - IdNameMap_t::iterator find_iter_id_map = m_idNameMap.find (id); + IdNameMap_t::iterator find_iter_id_map = m_idNameMap.find(id); - assert (find_iter_id_map != m_idNameMap.end ()); //lint !e1924 // c-style cast. MSVC bug + assert(find_iter_id_map != m_idNameMap.end()); //lint !e1924 // c-style cast. MSVC bug - m_nameMap.erase (find_iter_id); - m_map.erase (find_iter_string); - m_idNameMap.erase (find_iter_id_map); + m_nameMap.erase(find_iter_id); + m_map.erase(find_iter_string); + m_idNameMap.erase(find_iter_id_map); return true; } //----------------------------------------------------------------- -bool LocalizedStringTableRW::rename (const Unicode::NarrowString & name, const Unicode::NarrowString & newName) +bool LocalizedStringTableRW::rename(const Unicode::NarrowString & name, const Unicode::NarrowString & newName) { // if (name == newName) return false; // names that start with numerals are special - if (isdigit (newName [0])) + if (isdigit(newName[0])) return false; - - NameMap_t::iterator find_iter_id = m_nameMap.find (newName); - - // newName already exists - if (find_iter_id != m_nameMap.end ()) - { + NameMap_t::iterator find_iter_id = m_nameMap.find(newName); + + // newName already exists + if (find_iter_id != m_nameMap.end()) + { LocalizedString::id_type id = (*find_iter_id).second; - LocalizedString * locstr = getLocalizedString (id); + LocalizedString * locstr = getLocalizedString(id); static_cast(locstr); - return false; - + return false; } - - find_iter_id = m_nameMap.find (name); - + + find_iter_id = m_nameMap.find(name); + // old name does not exist - if (find_iter_id == m_nameMap.end ()) - return false; - + if (find_iter_id == m_nameMap.end()) + return false; + size_t id = (*find_iter_id).second; - - m_nameMap.erase (find_iter_id); - - const std::pair retval = m_nameMap.insert (NameMap_t::value_type (newName, id)); - - assert (retval.second == true); //lint !e1924 // c-style cast. MSVC bug - - m_idNameMap [id] = newName; - + + m_nameMap.erase(find_iter_id); + + const std::pair retval = m_nameMap.insert(NameMap_t::value_type(newName, id)); + + assert(retval.second == true); //lint !e1924 // c-style cast. MSVC bug + + m_idNameMap[id] = newName; + return retval.second == true; } //----------------------------------------------------------------- -void LocalizedStringTableRW::setName (const Unicode::NarrowString & name) +void LocalizedStringTableRW::setName(const Unicode::NarrowString & name) { m_name = name; } //----------------------------------------------------------------- -void LocalizedStringTableRW::prepareTable (const LocalizedStringTableRW & rhs) +void LocalizedStringTableRW::prepareTable(const LocalizedStringTableRW & rhs) { - m_idNameMap.clear (); - m_nameMap.clear (); - m_map.clear (); + m_idNameMap.clear(); + m_nameMap.clear(); + m_map.clear(); - m_idNameMap = rhs.m_idNameMap; - m_nameMap = rhs.m_nameMap; + m_idNameMap = rhs.m_idNameMap; + m_nameMap = rhs.m_nameMap; m_nextUniqueId = rhs.m_nextUniqueId; - m_name = rhs.m_name; + m_name = rhs.m_name; - for (Map_t::const_iterator iter = rhs.m_map.begin (); iter != rhs.m_map.end (); ++iter) + for (Map_t::const_iterator iter = rhs.m_map.begin(); iter != rhs.m_map.end(); ++iter) { const LocalizedString * rhs_locstr = (*iter).second; - LocalizedString * locstr = new LocalizedString (rhs_locstr->m_id, 0, rhs_locstr->m_str); + LocalizedString * locstr = new LocalizedString(rhs_locstr->m_id, 0, rhs_locstr->m_str); - assert (locstr != nullptr); //lint !e1924 // c-style cast. MSVC bug - m_map.insert (Map_t::value_type (locstr->getId (), locstr )); + assert(locstr != nullptr); //lint !e1924 // c-style cast. MSVC bug + m_map.insert(Map_t::value_type(locstr->getId(), locstr)); } } //----------------------------------------------------------------- -LocalizedString * LocalizedStringTableRW::getLocalizedStringByName (const Unicode::String & name) +LocalizedString * LocalizedStringTableRW::getLocalizedStringByName(const Unicode::String & name) { - return getLocalizedStringByName(Unicode::wideToNarrow (name)); + return getLocalizedStringByName(Unicode::wideToNarrow(name)); } - -// ====================================================================== +// ====================================================================== \ No newline at end of file