Vegastrike 0.5.1 rc1  1.0
Original sources for Vegastrike Evolved
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
NetClient Class Reference

#include <netclient.h>

Public Member Functions

 NetClient ()
 
void Reinitialize ()
 
 ~NetClient ()
 
int connectLoad (string user, string pass, string &error)
 
vector< string > * loginSavedGame (int ship=0)
 
void startGame ()
 
void SetConfigServerAddress (string &host, unsigned short &port)
 
void GetCurrentServerAddress (string &host, unsigned short &port)
 
void SetCurrentServerAddress (string host, unsigned short port)
 
const vector< string > & shipSelections ()
 
bool selectShip (unsigned int ship)
 
int authenticate ()
 
int loginAuth (string str_callsign, string str_passwd, string &error)
 
int loginLoop (string &error)
 
vector< string > & loginAcctLoop (string str_callsign, string str_passwd)
 
void loginAccept (Packet &p1)
 
void loginChooseShip (Packet &p1)
 
SOCKETALT init (const char *addr, unsigned short port, string &error)
 
VsnetHTTPSocketinit_acct (const std::string &addr)
 
void synchronizeTime (SOCKETALT *)
 
void setCallsign (char *calls)
 
void setCallsign (string calls)
 
string getCallsign ()
 
void setUnit (Unit *un)
 
UnitgetUnit ()
 
unsigned int getLag ()
 
int isTime ()
 
SOCKETALTlogout (bool leaveUDP)
 
void Respawn (ObjSerial clientname)
 
void saveRequest ()
 
void dieRequest ()
 
int checkMsg (Packet *outpacket)
 
void send (Cmd cmd, NetBuffer &netbuf, int mode, const char *file, int line)
 
void sendCustom (string cmd, string args, string id)
 
void sendPosition (const ClientState *cs)
 
void sendCloak (bool engage)
 
void sendAlive ()
 
void inGame ()
 
bool isInGame ()
 
Transformation Interpolate (Unit *un, double addtime)
 
void scanRequest (Unit *target)
 
void targetRequest (Unit *target)
 
void respawnRequest ()
 
void textMessage (const string &data)
 
void fireRequest (ObjSerial serial, const vector< int > &mount_indicies, char mis)
 
void unfireRequest (ObjSerial serial, const vector< int > &mount_indicies)
 
void cargoRequest (ObjSerial buyer, ObjSerial seller, const std::string &cargo, unsigned int quantity, int mountOffset, int subunitOffset)
 
void shipRequest (const std::string &cargo, unsigned char type)
 
void missionRequest (unsigned short packetType, string mission, int pos)
 
void communicationRequest (const class CommunicationMessage &c, ObjSerial sendTo)
 
void downloadZoneInfo ()
 
void AddObjects (NetBuffer &netbuf)
 
ClientPtr AddClientObject (Unit *un, ObjSerial cltserial=0)
 
bool jumpRequest (string newsystem, ObjSerial jumpserial)
 
bool readyToJump ()
 
void unreadyToJump ()
 
void dockRequest (ObjSerial utdw_serial)
 
void undockRequest (ObjSerial utdw_serial)
 
void createNetComm (float minfreq, float maxfreq, bool video, bool secured, string method)
 
void destroyNetComm ()
 
void startCommunication ()
 
void stopCommunication ()
 
void startWebcamTransfer ()
 
void stopWebcamTransfer ()
 
void sendWebcamPicture ()
 
char * getWebcamCapture ()
 
char * getWebcamFromNetwork (int &length)
 
void increaseFrequency ()
 
void decreaseFrequency ()
 
float getSelectedFrequency ()
 
float getCurrentFrequency ()
 
void switchSecured ()
 
void switchWebcam ()
 
bool hasWebcam ()
 
void sendTextMessage (string message)
 
bool IsNetcommActive () const
 
bool IsNetcommSecured () const
 

Static Public Member Functions

static void Reconnect (std::string srvipaddr, unsigned short port)
 
static void CleanUp ()
 

Public Attributes

ObjSerial serial
 

Detailed Description

Definition at line 45 of file accountserver.cpp.

Constructor & Destructor Documentation

NetClient::NetClient ( )

Definition at line 145 of file netclient.cpp.

References SocketSet::addDownloadManager(), getNewTime(), POSH_GetArchString(), and FileUtil::use_crypto.

146 {
147  keeprun = 1;
148  clt_tcp_sock = new SOCKETALT;
149  clt_udp_sock = new SOCKETALT;
150  deltatime = 0;
151  game_unit = NULL;
152  latest_timestamp = 0;
153  //old_time = 0;
154  cur_time = getNewTime();
155  enabled = 0;
156  nbclients = 0;
157  jumpok = false;
158  ingame = false;
159 #ifdef CRYPTO
160  FileUtil::use_crypto = true;
161 #endif
162 
163  NetComm = NULL;
164 
165  _downloadManagerClient.reset( new VsnetDownload::Client::Manager( _sock_set ) );
166  _sock_set.addDownloadManager( _downloadManagerClient );
167 
168 #ifdef CRYPTO
169  cout<<endl<<endl<<POSH_GetArchString()<<endl;
170 #endif
171 }
NetClient::~NetClient ( )

Definition at line 173 of file netclient.cpp.

174 {
175  if (NetComm != NULL) {
176  delete NetComm;
177  NetComm = NULL;
178  }
179  if (clt_tcp_sock) delete clt_tcp_sock; //UDP sockets don't seem to like being deleted.
180  //if (clt_udp_sock) { delete clt_udp_sock; }
181 }

Member Function Documentation

ClientPtr NetClient::AddClientObject ( Unit un,
ObjSerial  cltserial = 0 
)

Definition at line 125 of file netclient_clients.cpp.

References _Universe, Universe::activeStarSystem(), StarSystem::AddUnit(), Unit::BackupState(), COUT, Unit::getFlightgroup(), Unit::getFullname(), getNetworkUnit(), Unit::GetSerial(), UnitContainer::GetUnit(), i, Mount::INACTIVE, isLocalSerial(), Unit::mounts, Flightgroup::name, Unit::name, Unit::old_state, Unit::PrimeOrders(), Unit::SetNetworkMode(), Unit::SetSerial(), and UnitContainer::SetUnit().

Referenced by AddObjects(), and Respawn().

126 {
127  un->PrimeOrders(); //Allow you to communicate with it.
128  if (!cltserial)
129  cltserial = un->GetSerial();
130  {
131  Flightgroup *fg;
132  fg = un->getFlightgroup();
133  string fgname;
134  if (fg) fgname = ", fg "+fg->name;
135  COUT<<" >>> ENTERING CLIENT =( "<<cltserial
136  <<fgname<<" )= -----------------"<<endl;
137  }
138  ClientPtr clt = Clients.get( cltserial );
139  if (clt) {
140  //Client may exist if it jumped from a starsystem to another of if killed and respawned
141  COUT<<"Existing client #"<<cltserial<<endl;
142  } else if (!cltserial) {
143  COUT<<"Local client with serial 0: "<<un->name<<", "<<un->getFullname()<<endl;
144  return clt;
145  } else {
146  clt = Clients.insert( cltserial, new Client );
147  nbclients++;
148  COUT<<"New client #"<<cltserial<<" - now "<<nbclients<<" clients in system"<<endl;
149  }
150  if ( !isLocalSerial( cltserial ) ) {
151  clt->game_unit.SetUnit( un );
152  //Set all weapons to inactive
153  vector< Mount >
154  ::iterator i = un->mounts.begin(); //note to self: if vector<Mount *> is ever changed to vector<Mount> remove the const_ from the const_iterator
155  for (; i != un->mounts.end(); ++i)
156  (*i).status = Mount::INACTIVE;
157  un->SetNetworkMode( true );
158  un->SetSerial( cltserial );
159  //COUT<<"Addclient 4"<<endl;
160  un->BackupState();
161  clt->last_packet = un->old_state;
162  clt->prediction->InitInterpolation( un, un->old_state, 0, this->deltatime );
164  } else {
165  Unit *myun = this->game_unit.GetUnit();
166  Unit *cltun = clt->game_unit.GetUnit();
167  if ( cltun == NULL || cltserial != cltun->GetSerial() )
168  clt->game_unit.SetUnit( un ? un : getNetworkUnit( cltserial ) );
169  if ( myun == NULL || cltserial != myun->GetSerial() )
170  this->game_unit.SetUnit( un ? un : getNetworkUnit( cltserial ) );
171  }
172  return clt;
173 }
void NetClient::AddObjects ( NetBuffer netbuf)

Definition at line 198 of file netclient_clients.cpp.

References ZoneMgr::AddAsteroid, ZoneMgr::AddClient, AddClientObject(), ZoneMgr::AddMissile, ZoneMgr::AddNebula, ZoneMgr::AddPlanet, ZoneMgr::AddUnit, COUT, ZoneMgr::End, NetBuffer::getChar(), NetBuffer::getData(), UnitUtil::getFactionName(), Unit::getFullname(), NetBuffer::getOffset(), NetBuffer::getSerial(), Unit::GetSerial(), NetBuffer::getSize(), int, Unit::name, UnitFactory::parseAsteroidBuffer(), UnitFactory::parseMissileBuffer(), UnitFactory::parseNebulaBuffer(), UnitFactory::parsePlanetBuffer(), UnitFactory::parseUnitBuffer(), and serial.

Referenced by downloadZoneInfo().

199 {
200  char subcmd;
201  /*
202  * std::set<ObjSerial> enteredSerials;
203  * for (unsigned int i=0;i<_Universe->numPlayers();++i) {
204  * Unit*un=_Universe->AccessCockpit(i)->GetParent();
205  * if(un) enteredSerials.insert(un->GetSerial());
206  * }
207  */
208  //Loop until the end of the buffer
209  int offset = netbuf.getOffset();
210  while ( ( subcmd = netbuf.getChar() ) != ZoneMgr::End ) {
211  int noffset = netbuf.getOffset();
212  if (noffset == offset) {
213  COUT<<"ERROR Premature end of AddObjects buffer "<<std::hex
214  <<std::string( netbuf.getData(), netbuf.getSize() )<<std::endl;
215 
216  break;
217  }
218  offset = noffset; //to make sure we aren't at end of truncated buf
219  Unit *newunit = NULL;
220  ObjSerial serial = 0;
221  switch (subcmd)
222  {
223  case ZoneMgr::AddClient:
224  serial = netbuf.getSerial();
225 //enteredSerials.insert(serial);
226  newunit = this->enterClient( netbuf, serial );
227  break;
228  case ZoneMgr::AddUnit:
229  newunit = UnitFactory::parseUnitBuffer( netbuf );
230  AddClientObject( newunit );
231 //enteredSerials.insert(newunit->GetSerial());
232  break;
233  case ZoneMgr::AddNebula:
234  newunit = (Unit*) UnitFactory::parseNebulaBuffer( netbuf );
235  AddClientObject( newunit );
236 //enteredSerials.insert(newunit->GetSerial());
237  break;
238  case ZoneMgr::AddPlanet:
239  newunit = (Unit*) UnitFactory::parsePlanetBuffer( netbuf );
240  AddClientObject( newunit );
241 //enteredSerials.insert(newunit->GetSerial());
242  break;
244  newunit = (Unit*) UnitFactory::parseAsteroidBuffer( netbuf );
245  AddClientObject( newunit );
246 //enteredSerials.insert(newunit->GetSerial());
247  break;
248  case ZoneMgr::AddMissile:
249  newunit = (Unit*) UnitFactory::parseMissileBuffer( netbuf );
250  AddClientObject( newunit );
251 //enteredSerials.insert(newunit->GetSerial());
252  break;
253  default:
254  cerr<<"WARNING : Unknown sub "<<(int) subcmd<<" command in AddObjects"<<endl;
255  break;
256  }
257  if (newunit) {
258  serial = newunit->GetSerial();
259  cerr<<" *** Adding Unit "<<serial<<" "<<UnitUtil::getFactionName( newunit )<<" "<<newunit->getFullname()<<"; "
260  <<newunit->name.get()<<endl;
261  }
262  }
263  //NETFIXME: What is the point of killing off all non-networked units all the time?
264  /*
265  * Unit *un;
266  * for (un_iter it = UniverseUtil::getUnitList();
267  * un=(*it);
268  * ) {
269  * ++it;
270  * if (enteredSerials.find(un->GetSerial())==enteredSerials.end()) {
271  * un->Kill();//doesnt belong here..not an allowed serial
272  * //NETFIXME could result in star system being killed off one by one--need to differentiate that
273  * }
274  * }
275  */
276 }
int NetClient::authenticate ( )

Definition at line 26 of file netclient_login.cpp.

References NetBuffer::addString(), CMD_LOGIN, COUT, NetBuffer::getData(), Packet::getDataLength(), NetBuffer::getDataLength(), Packet::getHeaderLength(), VegaConfig::getVariable(), global_password, global_username, PSEUDO__LINE__, Packet::send(), SENDRELIABLE, and vs_config.

27 {
28  COUT<<" enter "<<__PRETTY_FUNCTION__<<endl;
29 
30  Packet packet2;
31  string str_callsign, str_passwd;
32  NetBuffer netbuf;
33 
34  //Get the name and password from vegastrike.config
35  //Maybe someday use a default Guest account if no callsign or password is provided thus allowing
36  //Player to wander but not interact with the universe
37  this->callsign = str_callsign = vs_config->getVariable( "player", "callsign", "" );
38  this->password = str_passwd = vs_config->getVariable( "player", "password", "" );
39  if ( global_username.length() )
40  this->callsign = global_username;
41  if ( global_password.length() )
42  this->password = global_password;
43  if ( str_callsign.length() && str_passwd.length() ) {
44  netbuf.addString( str_callsign );
45  netbuf.addString( str_passwd );
46 
47  packet2.send( CMD_LOGIN, 0,
48  netbuf.getData(), netbuf.getDataLength(),
49  SENDRELIABLE, NULL, *this->clt_tcp_sock,
50  __FILE__, PSEUDO__LINE__( 165 ) );
51  COUT<<"Send login for player <"<<str_callsign<<">:<*******"
52  "> - buffer length : "<<packet2.getDataLength()
53  <<" (+"<<packet2.getHeaderLength()<<" header len"<<endl;
54  } else {
55  cerr<<"Callsign and/or password not specified in vegastrike.config, please check this."<<endl<<endl;
56  return -1;
57  }
58  return 0;
59 }
void NetClient::cargoRequest ( ObjSerial  buyer,
ObjSerial  seller,
const std::string &  cargo,
unsigned int  quantity,
int  mountOffset,
int  subunitOffset 
)

Definition at line 107 of file netclient_devices.cpp.

References NetBuffer::addInt32(), NetBuffer::addSerial(), NetBuffer::addString(), CMD_CARGOUPGRADE, UnitContainer::GetUnit(), send(), and SENDRELIABLE.

Referenced by Unit::AddCargo(), Unit::RemoveCargo(), and Unit::UpAndDownGrade().

113 {
114  NetBuffer netbuf;
115  Unit *un = this->game_unit.GetUnit();
116  if (!un) return;
117  netbuf.addSerial( buyer ); //If the buyer is the player, it is buying cargo.
118  netbuf.addSerial( seller ); //If seller is the player, it is selling cargo.
119  netbuf.addInt32( quantity );
120  netbuf.addString( cargo );
121  netbuf.addInt32( (unsigned int) (mountOffset) );
122  netbuf.addInt32( (unsigned int) (subunitOffset) );
123 
124  send( CMD_CARGOUPGRADE, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
125 }
int NetClient::checkMsg ( Packet outpacket)

Definition at line 367 of file netclient.cpp.

References CleanUp(), SOCKETALT::isActive(), NetworkCommunication::IsActive(), NetworkCommunication::SendSound(), and UniverseUtil::startMenuInterface().

368 {
369  int ret = 0;
370  string jpeg_str( "" );
371  timeval tv;
372  tv.tv_sec = 0;
373  tv.tv_usec = 0;
374  if ( clt_tcp_sock->isActive() || clt_udp_sock->isActive() )
375  ret = recvMsg( outpacket, &tv );
376  if (ret == -1) {
377  NetClient::CleanUp(); //Kill networking!!!
378  UniverseUtil::startMenuInterface( false, "Connection to VegaServer closed." );
379  return -1;
380  }
381  //If we have network communications enabled and webcam support enabled we grab an image
382  if ( NetComm != NULL && NetComm->IsActive() )
383  //Here also send samples
384  NetComm->SendSound( *this->clt_tcp_sock, this->serial );
385  return ret;
386 }
void NetClient::CleanUp ( )
static

Definition at line 1492 of file netclient.cpp.

References _Universe, logout(), Network, and Universe::numPlayers().

Referenced by BaseComputer::actionConfirmedLoadGame(), checkMsg(), NetActionConfirm::confirmedJoinGame(), NetActionConfirm::finalizeJoinGame(), and GameMenu::processSinglePlayerButton().

1493 {
1494  if (Network) {
1495  for (unsigned int i = 0; i < _Universe->numPlayers(); ++i)
1496  Network[i].logout( false );
1497  delete[] Network;
1498  Network = NULL;
1499  }
1500 }
void NetClient::communicationRequest ( const class CommunicationMessage c,
ObjSerial  sendTo 
)

Definition at line 223 of file netclient_devices.cpp.

References NetBuffer::addChar(), NetBuffer::addInt32(), NetBuffer::addSerial(), CMD_COMM, CommunicationMessage::curstate, CommunicationMessage::edgenum, CommunicationMessage::prevstate, send(), and SENDRELIABLE.

224 {
225  NetBuffer netbuf;
226  netbuf.addSerial( sendTo );
227  int edge = c.edgenum;
228  if (edge > 127)
229  edge = -1;
230  netbuf.addChar( edge );
231  if (edge == -1)
232  netbuf.addInt32( c.curstate );
233  else
234  netbuf.addInt32( c.prevstate );
235  send( CMD_COMM, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
236 }
int NetClient::connectLoad ( string  user,
string  pass,
string &  error 
)

Definition at line 653 of file netclient_login.cpp.

References bootstrap_draw(), error, GetCurrentServerAddress(), VegaConfig::getVariable(), init(), init_acct(), localSerials, loginAcctLoop(), loginAuth(), SOCKETALT::valid(), and vs_config.

Referenced by NetActionConfirm::confirmedJoinGame(), and Reconnect().

654 {
655  localSerials.resize( 0 );
656  bootstrap_draw( "#cc66ffNETWORK: Initializing...", NULL );
657  cout<<"NETWORK: Initializing..."<<endl;
658  string srvipadr;
659  unsigned short port;
660  bool ret = false;
661  //Are we using the directly account server to identify us ?
662  GetCurrentServerAddress( srvipadr, port );
663  if (!port) {
664  //using account server.
665  string srvipadr = vs_config->getVariable( "network", "account_server_url", "http://localhost/cgi-bin/accountserver.py" );
666  bootstrap_draw( "#cc66ffNETWORK: Connecting to account server.", NULL );
667  cout<<"NETWORK: Connecting to account server."<<endl;
668  init_acct( srvipadr );
669  vector< string > &savetmp = loginAcctLoop( username, passwd );
670  //We don't expect a saved game...
671  if ( savetmp.size() >= 2 && savetmp[0].empty() ) {
672  //But this is the way the acctserver code indicates an error.
673  error = savetmp[1];
674  return 0;
675  }
676  bootstrap_draw( "#cc66ffNETWORK: Connecting to VegaServer.", NULL );
677  cout<<"NETWORK: Connecting to VegaServer."<<endl;
678  ret = init( NULL, 0, error ).valid();
679  } else {
680  //Or are we going through a game server to do so ?
681  bootstrap_draw( "#cc66ffNETWORK: Connecting to VegaServer.", NULL );
682  cout<<"NETWORK: Connecting to VegaServer."<<endl;
683  ret = init( srvipadr.c_str(), port, error ).valid();
684  }
685  if (ret == false) {
686  //If network initialization fails, exit
687  if ( error.empty() ) error = "Network connection error";
688  if ( !this->error_message.empty() )
689  error += "\n"+this->error_message;
690  cout<<"Error: "<<error<<endl;
691  return 0;
692  }
693  cout<<"Successfully connected!";
694  //sleep( 3);
695  cout<<"Waiting for player "<<username<<": login response..."<<endl;
696  bootstrap_draw( "#cc66ffNETWORK: Successful connection! Waiting to log in.", NULL );
697  int loggedin = loginAuth( username, passwd, error );
698  if ( !this->error_message.empty() ) {
699  cout<<"Warning: "<<this->error_message<<endl;
700  if ( !error.empty() )
701  error += "\n";
702  error += this->error_message;
703  }
704  return loggedin;
705 }
void NetClient::createNetComm ( float  minfreq,
float  maxfreq,
bool  video,
bool  secured,
string  method 
)

Definition at line 254 of file netclient_devices.cpp.

255 {
256  if (NetComm != NULL) {
257  current_freq = minfreq;
258  selected_freq = maxfreq;
259  this->NetComm = new NetworkCommunication( minfreq, maxfreq, video, secured, method );
260  }
261 }
void NetClient::decreaseFrequency ( )

Definition at line 306 of file netclient_devices.cpp.

References NetworkCommunication::MaxFreq(), and NetworkCommunication::MinFreq().

Referenced by FlyByKeyboard::Execute().

307 {
308  if (NetComm != NULL) {
309  if ( current_freq == NetComm->MinFreq() )
310  current_freq = NetComm->MaxFreq();
311  else
312  current_freq -= .1;
313  }
314 }
void NetClient::destroyNetComm ( )

Definition at line 263 of file netclient_devices.cpp.

264 {
265  if (NetComm != NULL) {
266  delete NetComm;
267  NetComm = NULL;
268  }
269 }
void NetClient::dieRequest ( )

Definition at line 178 of file netclient_devices.cpp.

References CMD_KILL, UnitContainer::GetUnit(), send(), and SENDRELIABLE.

Referenced by NetActionConfirm::confirmedNetDie(), and UniverseUtil::loadGame().

179 {
180  //Send a packet with CMD_DOCK with serial and an ObjSerial = unit_to_dock_with_serial
181  NetBuffer netbuf;
182  Unit *un = this->game_unit.GetUnit();
183  if (!un) return;
184  cerr<<"SENDING A KILL REQUEST FOR PLAYER "<<callsign<<endl;
185  send( CMD_KILL, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
186 }
void NetClient::dockRequest ( ObjSerial  utdw_serial)

Definition at line 202 of file netclient_devices.cpp.

References NetBuffer::addSerial(), CMD_DOCK, send(), and SENDRELIABLE.

Referenced by CrashForceDock(), and Unit::Dock().

203 {
204  //Send a packet with CMD_DOCK with serial and an ObjSerial = unit_to_dock_with_serial
205  NetBuffer netbuf;
206 
207  cerr<<"SENDING A DOCK REQUEST FOR UNIT "<<utdw_serial<<endl;
208  netbuf.addSerial( utdw_serial );
209  send( CMD_DOCK, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
210 }
void NetClient::downloadZoneInfo ( )

Definition at line 181 of file netclient_clients.cpp.

References AddObjects(), COUT, VsnetDownload::Client::Buffer::done(), VsnetDownload::Client::Buffer::getBuffer(), VsnetDownload::Client::Buffer::getSize(), and VSFileSystem::ZoneBuffer.

Referenced by StarSystem::ProcessPendingJumps().

182 {
183  char tbuf[1024];
184  sprintf( tbuf, "%d", this->zone );
185  COUT<<__PRETTY_FUNCTION__<<" zone: "<<tbuf<<endl;
186  VsnetDownload::Client::Buffer buf( *this->clt_tcp_sock, tbuf, VSFileSystem::ZoneBuffer );
187  _downloadManagerClient->addItem( &buf );
188  timeval timeout = {10, 0};
189  while ( !buf.done() )
190  if (recvMsg( NULL, &timeout ) <= 0)
191  //NETFIXME: What if timeout or error occurs?
192  break;
193  const char *tmp = (char*) buf.getBuffer().get();
194  NetBuffer netbuf( tmp, buf.getSize() );
195  this->AddObjects( netbuf );
196 }
void NetClient::fireRequest ( ObjSerial  serial,
const vector< int > &  mount_indicies,
char  mis 
)

Definition at line 83 of file netclient_devices.cpp.

References NetBuffer::addChar(), NetBuffer::addInt32(), NetBuffer::addSerial(), CMD_FIREREQUEST, i, send(), and SENDRELIABLE.

Referenced by Unit::Fire().

84 {
85  NetBuffer netbuf;
86 
87  netbuf.addSerial( serial );
88  netbuf.addChar( mis );
89  netbuf.addInt32( mount_indicies.size() );
90  for (unsigned int i = 0; i < mount_indicies.size(); ++i)
91  netbuf.addInt32( mount_indicies[i] );
92  //NETFIXME: Use UDP for fire requests? or only from server->other clients
93  send( CMD_FIREREQUEST, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
94 }
string NetClient::getCallsign ( )
inline

Definition at line 182 of file netclient.h.

Referenced by BaseComputer::constructControls(), and createObjects().

183  {
184  return this->callsign;
185  }
float NetClient::getCurrentFrequency ( )

Definition at line 331 of file netclient_devices.cpp.

332 {
333  return this->current_freq;
334 }
void NetClient::GetCurrentServerAddress ( string &  host,
unsigned short &  port 
)

Definition at line 316 of file netclient_login.cpp.

Referenced by connectLoad(), and BaseComputer::constructControls().

317 {
318  addr = this->_serverip;
319  port = this->_serverport;
320 }
unsigned int NetClient::getLag ( )
inline

Definition at line 197 of file netclient.h.

Referenced by VDU::Draw().

198  {
199  return (unsigned int) (deltatime*1000);
200  }
float NetClient::getSelectedFrequency ( )

Definition at line 326 of file netclient_devices.cpp.

327 {
328  return this->selected_freq;
329 }
Unit* NetClient::getUnit ( )
inline

Definition at line 190 of file netclient.h.

References UnitContainer::GetUnit().

Referenced by BaseComputer::constructControls().

191  {
192  return game_unit.GetUnit();
193  }
char * NetClient::getWebcamCapture ( )

Definition at line 359 of file netclient_devices.cpp.

References NetworkCommunication::GetWebcamCapture().

360 {
361  if (NetComm != NULL)
362  return NetComm->GetWebcamCapture();
363  return NULL; //We have no choice...
364 }
char * NetClient::getWebcamFromNetwork ( int length)

Definition at line 366 of file netclient_devices.cpp.

References NetworkCommunication::GetWebcamFromNetwork().

367 {
368  if (NetComm != NULL)
369  return NetComm->GetWebcamFromNetwork( length );
370  return NULL; //We have no choice...
371 }
bool NetClient::hasWebcam ( )

Definition at line 396 of file netclient_devices.cpp.

References NetworkCommunication::HasWebcam().

397 {
398  return NetComm->HasWebcam();
399 }
void NetClient::increaseFrequency ( )

Definition at line 316 of file netclient_devices.cpp.

References NetworkCommunication::MaxFreq(), and NetworkCommunication::MinFreq().

Referenced by FlyByKeyboard::Execute().

317 {
318  if (NetComm != NULL) {
319  if ( current_freq == NetComm->MaxFreq() )
320  current_freq = NetComm->MinFreq();
321  else
322  current_freq += .1;
323  }
324 }
void NetClient::inGame ( )

Definition at line 600 of file netclient_clients.cpp.

References CMD_ADDCLIENT, COUT, UnitContainer::GetUnit(), Unit::Position(), send(), SENDRELIABLE, serial, and Unit::SetSerial().

Referenced by StarSystem::ProcessPendingJumps(), Reconnect(), and startGame().

601 {
602  NetBuffer netbuf;
603  Unit *un = this->game_unit.GetUnit();
604  if (!un)
605  cout<<"Trying to ingame dead unit";
606  //ClientState cs( this->serial, un->curr_physical_state, un->Velocity, Vector(0,0,0), 0);
607  //HERE SEND INITIAL CLIENTSTATE !! NOT NEEDED ANYMORE -> THE SERVER ALREADY KNOWS
608  //netbuf.addClientState( cs);
609  send( CMD_ADDCLIENT, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
610  un->SetSerial( this->serial );
611  COUT<<"Sending ingame with serial #"<<this->serial<<endl;
612  this->ingame = true;
613  cerr<<"STARTING LOCATION : x="<<un->Position().i<<",y="<<un->Position().j<<",z="<<un->Position().k<<endl;
614 }
SOCKETALT NetClient::init ( const char *  addr,
unsigned short  port,
string &  error 
)

Definition at line 376 of file netclient_login.cpp.

References CLIENT_NETVERSION, CMD_CONNECT, COUT, NetUITCP::createSocket(), SOCKETALT::disconnect(), NetUIUDP::disconnectSaveUDP(), VegaConfig::getVariable(), NETWORK_ATOM, PSEUDO__LINE__, Packet::send(), SENDRELIABLE, VSThread::start(), SOCKETALT::valid(), and vs_config.

Referenced by connectLoad().

377 {
378  if ( clt_tcp_sock && clt_tcp_sock->valid() ) clt_tcp_sock->disconnect( "NC_init_tcp" );
379  if ( clt_udp_sock && clt_udp_sock->valid() ) NetUIUDP::disconnectSaveUDP( *clt_udp_sock );
380  lastsave.clear();
381  netversion = 0;
382  if (addr == NULL) {
383  addr = _serverip.c_str();
384  port = _serverport;
385  }
386  COUT<<" enter "<<__PRETTY_FUNCTION__
387  <<" with "<<addr<<":"<<port<<endl;
388 
389  _sock_set.start();
390 
391  string strnetatom;
392  strnetatom = vs_config->getVariable( "network", "network_atom", "" );
393  if (strnetatom == "")
394  NETWORK_ATOM = 0.2;
395  else
396  NETWORK_ATOM = (double) atof( strnetatom.c_str() );
397  *this->clt_tcp_sock = NetUITCP::createSocket( addr, port, _sock_set );
398  this->lossy_socket = this->clt_tcp_sock;
399  if ( !clt_tcp_sock->valid() )
400  return *this->clt_tcp_sock;
401  COUT<<"created TCP socket ("<<addr<<","<<port<<") -> "<<this->clt_tcp_sock<<endl;
402 
403  /*
404  * if( this->authenticate() == -1)
405  * {
406  * perror( "Error login in ");
407  * return -1;
408  * }
409  */
410  Packet join;
411  join.send( CMD_CONNECT, CLIENT_NETVERSION, "", 0, SENDRELIABLE, NULL,
412  *this->clt_tcp_sock, __FILE__, PSEUDO__LINE__( 407 ) );
413  this->enabled = 1;
414 
415  string login_tostr = vs_config->getVariable( "network", "connecttimeout", "10" );
416  timeval tv = {atoi( login_tostr.c_str() ), 0};
417  int timeout = 0;
418  Packet packet;
419  while (!timeout) {
420  int recvd = this->recvMsg( &packet, &tv );
421  if (recvd == 0) {
422  error = "Connection to game server timed out!";
423  timeout = 1;
424  } else if (recvd < 0) {
425  char str[127];
426  sprintf( str, "NETWORK ERROR in recieving socket (error number %d)!!!",
427 #ifdef _WIN32
428  WSAGetLastError()
429 #else
430  errno
431 #endif
432  );
433  error = str;
434  timeout = 1;
435  } else if (this->netversion) {
436  break;
437  }
438  }
439  if (!this->netversion) {
440  if ( error.empty() )
441  error = "Unable to receive a valid version from this server.";
442  timeout = 1;
443  }
444  if (timeout)
445  clt_tcp_sock->disconnect( "NCinit_timedout" );
446  return *this->clt_tcp_sock;
447 }
VsnetHTTPSocket * NetClient::init_acct ( const std::string &  addr)

Definition at line 356 of file netclient_login.cpp.

References COUT, and VSThread::start().

Referenced by connectLoad().

357 {
358  COUT<<" enter "<<__PRETTY_FUNCTION__
359  <<" with "<<addr<<endl;
360 
361  _sock_set.start();
362 
363  cout<<"Initializing connection to account server..."<<endl;
364  acct_sock = new VsnetHTTPSocket( addr, _sock_set );
365  COUT<<"accountserver on socket "<<acct_sock<<" done."<<endl;
366 
367  return acct_sock;
368 }
Transformation NetClient::Interpolate ( Unit un,
double  addtime 
)

Definition at line 1579 of file netclient.cpp.

References Unit::curr_physical_state, and Unit::GetSerial().

Referenced by GameUnit< UnitType >::UpdatePhysics2().

1580 {
1581  if (!un) return Transformation();
1582 //return un->curr_physical_state;
1583 //NETFIXME: Interpolation is kind of borked...?
1584  ClientPtr clt = Clients.get( un->GetSerial() );
1585  Transformation trans;
1586  if (clt) {
1587  clt->elapsed_since_packet += addtime;
1588  trans = clt->prediction->Interpolate( un, clt->elapsed_since_packet );
1589 //cerr << " *** interpolate "<<un->getFullname()<<","<<un->GetSerial()<<" (" << trans.position.i << ", " << trans.position.j << ", " << trans.position.k << ")"<<endl;
1590 //cerr << " *** INTERPOLATE (" << un->curr_physical_state.position.i << ", " << un->curr_physical_state.position.j << ", " << un->curr_physical_state.position.k << "): next deltatime=" << clt->getNextDeltatime() << ", deltatime=" << clt->getDeltatime() << ", this-deltatime=" << this->deltatime << ", elapsed since packet=" << clt->elapsed_since_packet << "\n => (" << trans.position.i << ", " << trans.position.j << ", " << trans.position.k << ") Vel = (" << un->Velocity.i << ", " << un->Velocity.j << ", " << un->Velocity.k << ")" << std::endl;
1591  } else {
1592  trans = un->curr_physical_state;
1593  }
1594  return trans;
1595 }
bool NetClient::isInGame ( )
inline

Definition at line 220 of file netclient.h.

221  {
222  return this->ingame;
223  }
bool NetClient::IsNetcommActive ( ) const

Definition at line 373 of file netclient_devices.cpp.

References NetworkCommunication::IsActive().

374 {
375  return this->NetComm == NULL ? false : this->NetComm->IsActive();
376 }
bool NetClient::IsNetcommSecured ( ) const

Definition at line 378 of file netclient_devices.cpp.

References NetworkCommunication::IsSecured().

379 {
380  bool ret = false;
381  if (this->NetComm != NULL)
382  ret = this->NetComm->IsSecured();
383  return ret;
384 }
int NetClient::isTime ( )

Definition at line 340 of file netclient.cpp.

References getNewTime(), and NETWORK_ATOM.

341 {
342  int ret = 0;
343  //COUT<<"cur_time="<<cur_time<<" - elapsed="<<GetElapsedTime()<<endl;
344  if ( (getNewTime()-cur_time) > NETWORK_ATOM ) {
345  cur_time = getNewTime();
346  ret = 1;
347  }
348  return ret;
349 }
bool NetClient::jumpRequest ( string  newsystem,
ObjSerial  jumpserial 
)

Definition at line 135 of file netclient_devices.cpp.

References CMD_JUMP, UnitContainer::GetUnit(), send(), and SENDRELIABLE.

Referenced by StarSystem::JumpTo().

136 {
137  NetBuffer netbuf;
138  Unit *un = this->game_unit.GetUnit();
139  if (!un) return false;
140  /*
141  * netbuf.addString( newsystem);
142  * netbuf.addSerial( jumpserial);
143  * netbuf.addShort( un->getStarSystem()->GetZone());
144  * #ifdef CRYPTO
145  * unsigned char * hash = new unsigned char[FileUtil::Hash.DigestSize()];
146  * bool autogen;
147  * FileUtil::HashFileCompute( VSFileSystem::GetCorrectStarSysPath( newsystem+".system", autogen), hash, SystemFile);
148  * netbuf.addBuffer( hash, FileUtil::Hash.DigestSize());
149  * #endif
150  */
151  send( CMD_JUMP, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
152  //NO, WE MUST NOT BLOCK THE GAME WHILE WE ARE WAITING FOR SERVER AUTH
153  //Should wait for jump authorization
154  /*
155  * this->PacketLoop( CMD_JUMP);
156  * bool ret;
157  * if( this->jumpok)
158  * ret = true;
159  * else
160  * ret = false;
161  *
162  * jumpok = false;
163  */
164 
165  return true;
166 }
void NetClient::loginAccept ( Packet p1)

Definition at line 207 of file netclient_login.cpp.

References _Universe, bootstrap_draw(), COUT, Universe::current_stardate, VsnetDownload::Client::NoteFile::done(), f, VSFileSystem::GetCorrectStarSysPath(), Packet::getData(), Packet::getDataLength(), StarDate::GetFullTrekDate(), Packet::getSerial(), FileUtil::HashCompare(), StarDate::InitTrek(), localSerials, serial, and VSFileSystem::SystemFile.

208 {
209  using namespace VSFileSystem;
210  NetBuffer netbuf( p1.getData(), p1.getDataLength() );
211 
212  Packet pckt;
213  this->serial = p1.getSerial();
214  COUT<<">>> LOGIN ACCEPTED =( serial #"<<serial<<" )= --------------------------------------"<<endl;
215  {
216  char msg[100];
217  sprintf( msg, "#cc66ffNETWORK: Login Accepted. Serial number is %d. Downloading system file...", serial );
218  bootstrap_draw( msg, NULL );
219  }
220  //Should receive player's data (savegame) from server if there is a save
221  localSerials.push_back( serial );
222 
223  string datestr = netbuf.getString();
224  _Universe->current_stardate.InitTrek( datestr );
225  cerr<<"Stardate initialized"<<endl;
226  cerr<<"WE ARE ON STARDATE "<<datestr<<" - converted : "
228  lastsave.push_back( netbuf.getString() );
229  lastsave.push_back( netbuf.getString() );
230  unsigned char *digest = 0;
231  unsigned short digest_length;
232 
233  /*
234  * // Get universe file... not too useful.
235  * // But this is a good example of using VsnetDownload download manager.
236  *
237  * // Get the galaxy file from buffer with relative path to datadir !
238  * digest_length = netbuf.getShort();
239  * string univfile = netbuf.getString();
240  * if (digest_length) {
241  * digest = netbuf.getBuffer( digest_length );
242  * #ifdef CRYPTO
243  * cerr<<"Initial system = "<<VSFileSystem::datadir+univfile<<" - File Hash = "<<digest<<endl;
244  * // Compare to local hash and ask for the good file if we don't have it or bad version
245  * if( !FileUtil::HashCompare( univfile, digest, UniverseFile))
246  * {
247  * VsnetDownload::Client::NoteFile f( this->clt_tcp_sock, univfile, VSFileSystem::UniverseFile);
248  * _downloadManagerClient->addItem( &f);
249  * timeval timeout={10,0};
250  * while( !f.done())
251  * {
252  * if (recvMsg( NULL, &timeout )<=0) {
253  * //NETFIXME: What to do if the download times out?
254  * break;
255  * }
256  * }
257  * }
258  * #endif
259  * }
260  */
261 
262  //Get the initial system file...
263  string sysfile = netbuf.getString();
264  bool downloadsystem = true;
265  bool autogen;
266  string fullsys = VSFileSystem::GetCorrectStarSysPath( sysfile, autogen );
267  if ( fullsys.empty() ) fullsys = sysfile;
268  digest_length = netbuf.getShort();
269  COUT<<"Initial system = "<<fullsys;
270  if (digest_length) {
271  digest = netbuf.getBuffer( digest_length );
272 #ifdef CRYPTO
273  cerr<<" - File Hash = "<<digest;
274  if ( FileUtil::HashCompare( fullsys, digest, SystemFile ) )
275  downloadsystem = false;
276 #endif
277  }
278  //Set the zone number
279  this->zone = netbuf.getShort();
280  //Did the hash compare fail?
281  if (downloadsystem) {
282  cerr<<": Downloading system from server..."<<endl;
283  VsnetDownload::Client::NoteFile f( fullsys, *this->clt_tcp_sock, sysfile, VSFileSystem::SystemFile );
284  _downloadManagerClient->addItem( &f );
285  timeval timeout = {10, 0};
286  while ( !f.done() )
287  if (recvMsg( NULL, &timeout ) <= 0)
288  //NETFIXME: what to do if timeout elapses...
289  break;
290  }
291  cout<<endl;
292 }
vector< string > & NetClient::loginAcctLoop ( string  str_callsign,
string  str_passwd 
)

Definition at line 139 of file netclient_login.cpp.

References ACCT_LOGIN_DATA, addSimpleChar(), addSimpleString(), COUT, VegaConfig::getVariable(), newtime, queryTime(), VsnetOSS::recv(), VsnetHTTPSocket::sendstr(), vs_config, and SocketSet::waste_time().

Referenced by connectLoad().

140 {
141  COUT<<"enter "<<"NetClient::loginAcctLoop"<<endl;
142 
143  this->error_message = string();
144 
145  std::string netbuf;
146  addSimpleChar( netbuf, ACCT_LOGIN_DATA );
147  //memset( buffer, 0, tmplen+1);
148  addSimpleString( netbuf, str_callsign );
149  addSimpleString( netbuf, str_passwd );
150 
151  COUT<<"Buffering to send with LOGIN_DATA for "<<str_callsign<<endl;
152  //PacketMem m( netbuf.getData(), netbuf.getDataLength(), PacketMem::LeaveOwnership );
153  //m.dump( cerr, 3 );
154  acct_sock->sendstr( netbuf );
155  /*
156  * packet2.send( LOGIN_DATA, 0,
157  * netbuf.getData(), netbuf.getDataLength(),
158  * SENDRELIABLE, NULL, this->acct_sock,
159  * __FILE__, PSEUDO__LINE__(378) );
160  */
161  //Now the loop
162  int timeout = 0, recv = 0;
163  //int ret=0;
164 
165  Packet packet;
166 
167  double initial = queryTime();
168  double newtime = 0;
169  double elapsed = 0;
170  string login_tostr = vs_config->getVariable( "network", "logintimeout", "20" );
171  int login_to = atoi( login_tostr.c_str() );
172  while (!timeout && !recv) {
173  //If we have no response in "login_to" seconds -> fails
174  newtime = queryTime();
175  elapsed = newtime-initial;
176  //COUT<<elapsed<<" seconds since login request"<<endl;
177  if (elapsed > login_to) {
178  //lastsave.push_back( "");
179  COUT<<"!!! NETWORK ERROR : Connection to account server timed out !!!"<<endl;
180  timeout = 1;
181  break;
182  }
183  recv = checkAcctMsg();
184  _sock_set.waste_time( 0, 40000 );
185  }
186  COUT<<"End of loginAcct loop"<<endl;
187  //globalsaves should be empty otherwise we filled it with an empty string followed by the error message
188  if (lastsave.empty() || lastsave[0] != "") {
189  //this->callsign = str_callsign;
190  //savefiles = globalsaves;
191  COUT<<"Trying to connect to game server..."<<endl
192  <<"\tIP="<<_serverip<<":"<<_serverport<<endl;
193  }
194  return lastsave;
195 }
int NetClient::loginAuth ( string  str_callsign,
string  str_passwd,
string &  error 
)

Definition at line 67 of file netclient_login.cpp.

References NetBuffer::addString(), CMD_LOGIN, COUT, NetBuffer::getData(), Packet::getDataLength(), NetBuffer::getDataLength(), loginLoop(), PSEUDO__LINE__, Packet::send(), and SENDRELIABLE.

Referenced by connectLoad().

68 {
69  COUT<<"enter "<<"NetClient::loginLoop"<<endl;
70  lastsave.clear();
71  ship_select_list.clear();
72 
73  Packet packet2;
74  NetBuffer netbuf;
75 
76  //memset( buffer, 0, tmplen+1);
77  netbuf.addString( str_callsign );
78  netbuf.addString( str_passwd );
79 
80  packet2.send( CMD_LOGIN, 0,
81  netbuf.getData(), netbuf.getDataLength(),
82  SENDRELIABLE, NULL, *this->clt_tcp_sock,
83  __FILE__, PSEUDO__LINE__( 316 ) );
84  COUT<<"Sent login for player <"<<str_callsign<<">:<*******"
85  <<">"<<endl
86  <<" - buffer length : "<<packet2.getDataLength()<<endl;
87  this->callsign = str_callsign;
88  this->password = str_passwd;
89  //Now the loop
90  return loginLoop( error );
91 }
void NetClient::loginChooseShip ( Packet p1)

Definition at line 197 of file netclient_login.cpp.

References Packet::getData(), Packet::getDataLength(), and i.

198 {
199  NetBuffer netbuf( p1.getData(), p1.getDataLength() );
200  ship_select_list.clear();
201  unsigned short numShips = netbuf.getShort();
202  ship_select_list.reserve( numShips );
203  for (int i = 0; i < numShips; i++)
204  ship_select_list.push_back( netbuf.getString() );
205 }
int NetClient::loginLoop ( string &  error)

Definition at line 93 of file netclient_login.cpp.

References COUT, VegaConfig::getVariable(), VsnetOSS::recv(), and vs_config.

Referenced by loginAuth(), and selectShip().

94 {
95  int timeout = 0, recv = 0;
96  //int ret=0;
97 
98  Packet packet;
99 
100  string login_tostr = vs_config->getVariable( "network", "logintimeout", "100" );
101  timeval tv = {atoi( login_tostr.c_str() ), 0};
102  while (!timeout) {
103  recv = this->recvMsg( &packet, &tv );
104  if (recv == 0) {
105  error = "NETWORK ERROR : Login procedeure timed out.";
106  timeout = 1;
107  } else if (recv < 0) {
108  char str[127];
109  sprintf( str, "NETWORK ERROR in recieving login data (error number %d)!!!",
110 #ifdef _WIN32
111  WSAGetLastError()
112 #else
113  errno
114 #endif
115  );
116  error = (str);
117  timeout = 1;
118  } else {
119  break;
120  }
121  }
122  COUT<<"End of login loop"<<endl;
123  if (lastsave.empty() || lastsave[0] == "") {
124  if ( ship_select_list.empty() )
125  error = "Login failure!";
126  return ship_select_list.size();
127  }
128  //cout<<"GLOBALSAVES[0] : "
129  //cout<<"GLOBALSAVES[1] : "<<globalsaves[1]<<endl;
130  return 1;
131 }
vector< string > * NetClient::loginSavedGame ( int  ship = 0)

Definition at line 706 of file netclient_login.cpp.

References selectShip().

Referenced by Reconnect().

707 {
708  if ( !selectShip( ship ) )
709  return NULL;
710  /************* NETWORK PART ***************/
711 
712  return &lastsave;
713 }
SOCKETALT * NetClient::logout ( bool  leaveUDP)

Definition at line 1464 of file netclient.cpp.

References CMD_LOGOUT, SOCKETALT::disconnect(), NetUIUDP::disconnectSaveUDP(), SOCKETALT::get_fd(), Mission::getNthPlayerMission(), Unit::GetSerial(), UnitContainer::GetUnit(), Network, PSEUDO__LINE__, Packet::send(), SENDRELIABLE, Mission::terminateMission(), and SOCKETALT::valid().

Referenced by CleanUp(), and Reconnect().

1465 {
1466  keeprun = 0;
1467  Packet p;
1468  if (clt_tcp_sock->valid() && clt_tcp_sock->get_fd() != -1) {
1469  Unit *un = this->game_unit.GetUnit();
1470  if (un) {
1471  p.send( CMD_LOGOUT, un->GetSerial(),
1472  (char*) NULL, 0,
1473  SENDRELIABLE, NULL, *this->clt_tcp_sock,
1474  __FILE__, PSEUDO__LINE__( 1382 ) );
1475  timeval tv = {10, 0};
1476  recvMsg( &p, &tv );
1477  }
1478  clt_tcp_sock->disconnect( "Closing connection to server" );
1479  }
1480  Mission *mis;
1481  //Can't figure out how to get cockpit number?
1482  while ( ( mis = Mission::getNthPlayerMission( (this-Network), 0 ) ) )
1483  mis->terminateMission();
1484  if (!leaveUDP)
1485  NetUIUDP::disconnectSaveUDP( *clt_udp_sock );
1486 //clt_udp_sock->disconnect( "Closing UDP connection to server");
1487  else if (lossy_socket == clt_udp_sock)
1488  return clt_udp_sock;
1489  return NULL;
1490 }
void NetClient::missionRequest ( unsigned short  packetType,
string  mission,
int  pos 
)

Definition at line 212 of file netclient_devices.cpp.

References NetBuffer::addInt32(), NetBuffer::addShort(), NetBuffer::addString(), CMD_MISSION, send(), and SENDRELIABLE.

Referenced by BaseComputer::acceptMission().

213 {
214  NetBuffer netbuf;
215 
216  netbuf.addShort( packetType );
217  netbuf.addString( mission );
218  netbuf.addInt32( pos );
219 
220  send( CMD_MISSION, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
221 }
bool NetClient::readyToJump ( )

Definition at line 168 of file netclient_devices.cpp.

169 {
170  return jumpok;
171 }
void NetClient::Reconnect ( std::string  srvipaddr,
unsigned short  port 
)
static

Definition at line 1502 of file netclient.cpp.

References _Universe, Universe::AccessCockpit(), Universe::clearAllSystems(), connectLoad(), COUT, getNewTime(), UniverseUtil::hideSplashScreen(), inGame(), k, localSerials, loginSavedGame(), logout(), Network, Universe::numPlayers(), Reinitialize(), Respawn(), SetConfigServerAddress(), SetCurrentServerAddress(), UniverseUtil::showSplashScreen(), UniverseUtil::startMenuInterface(), synchronizeTime(), and Cockpit::TimeOfLastCollision.

1503 {
1504  vector< string > usernames;
1505  vector< string > passwords;
1506  vector< SOCKETALT* >udp;
1507  unsigned int i;
1508  if (!Network)
1510  for (i = 0; i < _Universe->numPlayers(); ++i) {
1511  usernames.push_back( Network[i].callsign );
1512  passwords.push_back( Network[i].password );
1513  SOCKETALT *udpsocket = Network[i].logout( true );
1514  if (udpsocket)
1515  udp.push_back( udpsocket );
1516  else
1517  udp.push_back( NULL );
1518  Network[i].disconnect();
1519  }
1521  localSerials.resize( 0 );
1522  for (i = 0; i < _Universe->numPlayers(); ++i)
1523  Network[i].Reinitialize();
1525  //necessary? usually we would ask acctserver for it .. or pass it in NetClient::getConfigServerAddress(srvipadr, port);
1526  for (unsigned int k = 0; k < _Universe->numPlayers(); ++k) {
1527  string err;
1528  if ( !srvipadr.empty() )
1529  Network[k].SetCurrentServerAddress( srvipadr, port );
1530  else
1531  Network[k].SetConfigServerAddress( srvipadr, port );
1532  int response = Network[k].connectLoad( usernames[k], passwords[k], err );
1533  if (response == 0) {
1534  COUT<<"Network login error: \n"<<err<<endl;
1535  UniverseUtil::startMenuInterface( false, "Jumping to system, but got a login error: \n\n"+err );
1536  return;
1537  }
1538  vector< string > *loginResp = Network[k].loginSavedGame( 0 );
1539  if (!loginResp) {
1540  COUT<<"Failed to get a ship";
1541  UniverseUtil::startMenuInterface( false, "Jumping to system, but failed to get a ship!" );
1542  return;
1543  }
1544  cout<<" logged in !"<<endl;
1545  Network[k].Respawn( Network[k].serial );
1546  Network[k].synchronizeTime( udp[k] );
1548  Network[k].inGame();
1549  }
1551 }
void NetClient::Reinitialize ( )

Definition at line 116 of file netclient.cpp.

References getNewTime(), and FileUtil::use_crypto.

Referenced by Reconnect().

117 {
118  deltatime = 0;
119  game_unit = NULL;
120  latest_timestamp = 0;
121  keeprun = 1;
122  //old_time = 0;
123  cur_time = getNewTime();
124  enabled = 0;
125  nbclients = 0;
126  jumpok = false;
127  ingame = false;
128 #ifdef CRYPTO
129  FileUtil::use_crypto = true;
130 #endif
131 
132  NetComm = NULL;
133  lastsave.resize( 0 );
134  //_downloadManagerClient.reset( new VsnetDownload::Client::Manager( _sock_set ) );
135  //_sock_set.addDownloadManager( _downloadManagerClient );
136  _serverip = "";
137  _serverport = 0;
138  callsign = password = "";
139  this->Clients = ClientsMap();
140 
141  delete clt_tcp_sock;
142  clt_tcp_sock = new SOCKETALT;
143  //leave UDP well-enough alone
144 }
void NetClient::Respawn ( ObjSerial  clientname)

Definition at line 390 of file netclient.cpp.

References _Universe, Universe::AccessCockpit(), Cockpit::activeStarSystem, Universe::activeStarSystem(), AddClientObject(), StarSystem::AddUnit(), Background::Cache(), Universe::clearAllSystems(), CP_FRONT, UnitFactory::createUnit(), Cockpit::credits, Universe::CurrentCockpit(), Cockpit::fg, Flightgroup::flightgroup_nr, Background::BackgroundClone::FreeClone(), Universe::GenerateStarSystem(), StarSystem::getBackground(), FactionUtil::GetFactionIndex(), Cockpit::GetParent(), SaveGame::GetPlayerFaction(), Cockpit::GetUnitFileName(), VegaConfig::getVariable(), UniverseUtil::hideSplashScreen(), localSerials, Flightgroup::nr_ships, Flightgroup::nr_ships_left, Universe::numPlayers(), XMLSupport::parse_float(), SaveGame::ParseSaveGame(), Universe::popActiveStarSystem(), Universe::pushActiveStarSystem(), QVector, Cockpit::savegame, Universe::SetActiveCockpit(), Cockpit::SetParent(), Unit::SetPosAndCumPos(), Unit::SetSerial(), SaveGame::SetStarSystem(), UnitContainer::SetUnit(), Cockpit::SetView(), SwitchUnits2(), Cockpit::UnpackUnitInfo(), Vector, vs_config, and Cockpit::zoomfactor.

Referenced by Reconnect().

391 {
392  unsigned int whichcp;
393  for (whichcp = 0; whichcp < _Universe->numPlayers(); ++whichcp)
394  if (_Universe->AccessCockpit( whichcp )->GetParent() == NULL)
395  break;
396  if ( whichcp == _Universe->numPlayers() ) {
397  whichcp = 0;
398  cerr<<"Error could not find blank cockpit to respawn into\n";
399  }
400  QVector pos( 0, 0, 0 );
401  bool setplayerXloc;
402  string mysystem;
403  Cockpit *cp = _Universe->AccessCockpit( whichcp );
404  vector< string > packedInfo;
405 
406  static float initialzoom = XMLSupport::parse_float( vs_config->getVariable( "graphics", "inital_zoom_factor", "2.25" ) );
407  cp->zoomfactor = initialzoom;
408  cp->savegame->SetStarSystem( mysystem );
409  cp->savegame->ParseSaveGame( "",
410  mysystem,
411  "",
412  pos,
413  setplayerXloc,
414  cp->credits,
415  packedInfo,
416  whichcp,
417  lastsave[0],
418  false );
419  string fullsysname = mysystem+".system";
420  StarSystem *ss;
421 
422  cp->UnpackUnitInfo(packedInfo);
423 
424  {
425  Background::BackgroundClone savedtextures = {
426  {NULL, NULL, NULL, NULL, NULL, NULL, NULL}
427  };
428  Background *tmp = NULL;
429  if ( _Universe->activeStarSystem() ) {
431  savedtextures = tmp->Cache();
432  }
434  ss = _Universe->GenerateStarSystem( fullsysname.c_str(), "", Vector( 0, 0, 0 ) );
435  if (tmp)
436  savedtextures.FreeClone();
437  }
439  unsigned int oldcp = _Universe->CurrentCockpit();
441  std::string unkeyname = cp->GetUnitFileName();
442  int fgsnumber = 0;
443  if (cp->fg) {
444  fgsnumber = cp->fg->flightgroup_nr++;
445  cp->fg->nr_ships++;
446  cp->fg->nr_ships_left++;
447  }
448  Unit *un = UnitFactory::createUnit( unkeyname.c_str(), false, FactionUtil::GetFactionIndex(
449  cp->savegame->GetPlayerFaction() ), std::string(
450  "" ), cp->fg, fgsnumber, &lastsave[1], newserial );
451  un->SetSerial( newserial );
452  //fighters[a]->faction = FactionUtil::GetFactionIndex( cp->savegame->GetPlayerFaction());
453  cp->SetParent( un, unkeyname.c_str(), "", pos );
454  un->SetPosAndCumPos( pos );
455  this->game_unit.SetUnit( un );
456  localSerials.push_back( newserial );
457  ss->AddUnit( un );
458  AddClientObject( un, newserial );
459  SwitchUnits2( un );
460  cp->SetView( CP_FRONT );
462  _Universe->SetActiveCockpit( oldcp );
465 }
void NetClient::respawnRequest ( )

Definition at line 294 of file netclient_login.cpp.

References CMD_RESPAWN, NetBuffer::getData(), NetBuffer::getDataLength(), PSEUDO__LINE__, Packet::send(), and SENDRELIABLE.

Referenced by Cockpit::Update().

295 {
296  Packet packet2;
297  NetBuffer netbuf;
298  //No data.
299  packet2.send( CMD_RESPAWN, 0,
300  netbuf.getData(), netbuf.getDataLength(),
301  SENDRELIABLE, NULL, *this->clt_tcp_sock,
302  __FILE__, PSEUDO__LINE__( 165 ) );
303 }
void NetClient::saveRequest ( )

Definition at line 188 of file netclient_devices.cpp.

References _Universe, CMD_SAVEACCOUNTS, SaveNetUtil::GetSaveStrings(), UnitContainer::GetUnit(), send(), SENDRELIABLE, and Universe::whichPlayerStarship().

Referenced by NetActionConfirm::confirmedNetSaveGame(), and UniverseUtil::saveGame().

189 {
190  //Send a packet with CMD_DOCK with serial and an ObjSerial = unit_to_dock_with_serial
191  NetBuffer netbuf;
192  Unit *un = this->game_unit.GetUnit();
193  if (!un) return;
194  cerr<<"SENDING A SAVE REQUEST FOR PLAYER "<<callsign<<endl;
195  send( CMD_SAVEACCOUNTS, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
196 
197  int cpnum = _Universe->whichPlayerStarship( un );
198  if (cpnum >= 0 && lastsave.size() >= 2 && this->netversion < 4960)
199  SaveNetUtil::GetSaveStrings( cpnum, lastsave[0], lastsave[1], true );
200 }
void NetClient::scanRequest ( Unit target)

Definition at line 54 of file netclient_devices.cpp.

References NetBuffer::addSerial(), CMD_SCAN, Unit::GetSerial(), UnitContainer::GetUnit(), send(), and SENDRELIABLE.

55 {
56  Packet p;
57  NetBuffer netbuf;
58  Unit *un = this->game_unit.GetUnit();
59  if (!un) return;
60  netbuf.addSerial( target->GetSerial() );
61  //Shold people be allowed to scan units in other zones?
62 //netbuf.addShort( un->activeStarSystem->GetZone());
63 
64  send( CMD_SCAN, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
65 }
bool NetClient::selectShip ( unsigned int  ship)

Definition at line 627 of file netclient_login.cpp.

References NetBuffer::addShort(), NetBuffer::addString(), CMD_CHOOSESHIP, NetBuffer::getData(), NetBuffer::getDataLength(), loginLoop(), PSEUDO__LINE__, Packet::send(), and SENDRELIABLE.

Referenced by loginSavedGame().

628 {
629  if (lastsave.empty() || lastsave[0] == "") {
630  NetBuffer netbuf;
631  string shipname;
632  netbuf.addShort( (unsigned short) ship );
633  if ( ship < ship_select_list.size() )
634  shipname = ship_select_list[ship];
635  netbuf.addString( shipname );
636  Packet p;
637  p.send( CMD_CHOOSESHIP, 0, netbuf.getData(), netbuf.getDataLength(), SENDRELIABLE,
638  NULL, *clt_tcp_sock, __FILE__, PSEUDO__LINE__( 628 ) );
639  string err;
640  int ret = loginLoop( err );
641  if (ret != 1 || lastsave.size() < 2 || lastsave[0] == "") {
642  cout<<"Error in CHOOSEHIP: "<<err
643  <<"choice="<<ship<<"("<<shipname<<"), max="<<ret<<endl;
644  return false;
645  }
646  }
647  return true;
648 }
void NetClient::send ( Cmd  cmd,
NetBuffer netbuf,
int  mode,
const char *  file,
int  line 
)

Definition at line 12 of file netclient_devices.cpp.

References accountXML::file, NetBuffer::getData(), NetBuffer::getDataLength(), Unit::GetSerial(), UnitContainer::GetUnit(), Packet::send(), SENDANDFORGET, and serial.

Referenced by cargoRequest(), communicationRequest(), dieRequest(), dockRequest(), fireRequest(), inGame(), jumpRequest(), missionRequest(), saveRequest(), scanRequest(), sendCloak(), sendCustom(), sendPosition(), shipRequest(), targetRequest(), undockRequest(), and unfireRequest().

13 {
14  Unit *un = this->game_unit.GetUnit();
15  int serial = 0;
16  if (un)
17  serial = un->GetSerial();
18  Packet p;
19  p.send( cmd, serial,
20  netbuf.getData(), netbuf.getDataLength(),
21  mode, NULL,
22  *( (mode&SENDANDFORGET) ? this->lossy_socket : this->clt_tcp_sock ),
23  file, line );
24 }
void NetClient::sendAlive ( )

Definition at line 622 of file netclient_clients.cpp.

References CMD_PING, Unit::GetSerial(), UnitContainer::GetUnit(), PSEUDO__LINE__, Packet::send(), and SENDANDFORGET.

623 {
624  /* WE NEED PING PACKET EVEN IN TCP MODE : THAT ALLOWS US TO COMPUTE A "SEMI-PING" TIME BETWEEN SERVER AND CLIENTS
625  * if( clt_sock.isTcp() == false )
626  * {
627  */
628  Unit *un = this->game_unit.GetUnit();
629  if (!un)
630  return;
631  Packet p;
632  p.send( CMD_PING, un->GetSerial(),
633  (char*) NULL, 0,
634  SENDANDFORGET, NULL, *this->lossy_socket,
635  __FILE__, PSEUDO__LINE__( 414 ) );
636  //}
637 }
void NetClient::sendCloak ( bool  engage)

Definition at line 31 of file netclient_devices.cpp.

References NetBuffer::addChar(), CMD_CLOAK, send(), and SENDRELIABLE.

Referenced by GameUnit< UnitType >::Cloak().

32 {
33  NetBuffer netbuf;
34 
35  netbuf.addChar( engage ? 1 : 0 );
36  //Shold people be allowed to scan units in other zones?
37 //netbuf.addShort( un->activeStarSystem->GetZone());
38 
39  send( CMD_CLOAK, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
40 }
void NetClient::sendCustom ( string  cmd,
string  args,
string  id 
)

Definition at line 42 of file netclient_devices.cpp.

References NetBuffer::addString(), CMD_CUSTOM, send(), and SENDRELIABLE.

Referenced by UniverseUtil::sendCustom().

43 {
44  NetBuffer netbuf;
45 
46  netbuf.addString( command );
47  netbuf.addString( args );
48  netbuf.addString( id );
49 
50  send( CMD_CUSTOM, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
51 }
void NetClient::sendPosition ( const ClientState cs)

Definition at line 316 of file netclient_clients.cpp.

References NetBuffer::addChar(), NetBuffer::addClientState(), NetBuffer::addSerial(), NetBuffer::addVector(), aim_assist(), CMD_POSUPDATE, COUT, ClientState::getPosition(), ClientState::getSerial(), Unit::GetSerial(), ClientState::getSpecMult(), UnitContainer::GetUnit(), VegaConfig::getVariable(), Unit::graphicOptions, Unit::InRange(), Unit::graphic_options::InWarp, XMLSupport::parse_bool(), send(), SENDANDFORGET, Unit::Target(), and vs_config.

Referenced by GameUnit< UnitType >::UpdatePhysics2().

317 {
318  Unit *un = this->game_unit.GetUnit();
319  if (!un)
320  return;
321  //Serial in ClientState is updated in UpdatePhysics code at ClientState creation (with pos, veloc...)
322  NetBuffer netbuf;
323  static bool debugPos = XMLSupport::parse_bool( vs_config->getVariable( "network", "debug_position_interpolation", "false" ) );
324  //Send the client state
325  if (debugPos) COUT<<"Sending ClientState == ";
326  if (debugPos) (*cs).display();
327  netbuf.addSerial( cs->getSerial() );
328  netbuf.addClientState( (*cs) );
329  if (netversion > 4960)
330  netbuf.addChar( cs->getSpecMult() > 1.0 ? 1 : 0 );
331  static bool aim_assist = XMLSupport::parse_bool( vs_config->getVariable( "network", "aim_assist", "true" ) );
332  Unit *targ;
333  if ( ( targ = un->Target() ) != NULL && aim_assist && un->Target()->GetSerial() != 0 /*networked unit*/ ) {
334  if (un->InRange( targ ) && !targ->graphicOptions.InWarp && !un->graphicOptions.InWarp) {
335  netbuf.addSerial( targ->GetSerial() );
336  netbuf.addVector( ( targ->Position()-cs->getPosition() ).Cast() );
337  netbuf.addVector( targ->Velocity );
338  }
339  }
340  send( CMD_POSUPDATE, netbuf, SENDANDFORGET, __FILE__, __LINE__ );
341 }
void NetClient::sendTextMessage ( string  message)

Definition at line 336 of file netclient_devices.cpp.

References NetworkCommunication::IsActive(), and NetworkCommunication::SendMessage().

337 {
338  //Only send if netcomm is active and we are connected on a frequency
339  if ( NetComm != NULL && NetComm->IsActive() )
340  NetComm->SendMessage( *this->clt_tcp_sock, this->serial, message );
341 }
void NetClient::sendWebcamPicture ( )
void NetClient::setCallsign ( char *  calls)
inline

Definition at line 174 of file netclient.h.

175  {
176  this->callsign = string( calls );
177  }
void NetClient::setCallsign ( string  calls)
inline

Definition at line 178 of file netclient.h.

179  {
180  this->callsign = calls;
181  }
void NetClient::SetConfigServerAddress ( string &  host,
unsigned short &  port 
)

Definition at line 328 of file netclient_login.cpp.

References VegaConfig::getVariable(), XMLSupport::parse_bool(), and vs_config.

Referenced by bootstrap_main_loop(), NetActionConfirm::confirmedJoinGame(), and Reconnect().

329 {
330  bool use_acctserver = XMLSupport::parse_bool( vs_config->getVariable( "network", "use_account_server", "false" ) );
331  if (use_acctserver) {
332  this->_serverport = port = 0;
333  this->_serverip = addr = vs_config->getVariable( "network", "account_server_url",
334  "http://localhost/cgi-bin/accountserver.py" );
335  cout<<endl<<"Account Server URL : "<<addr<<endl<<endl;
336  return;
337  }
338  int port_tmp;
339  string srvport = vs_config->getVariable( "network", "server_port", "6777" );
340  port_tmp = atoi( srvport.c_str() );
341  if (port_tmp > 65535 || port_tmp < 0)
342  port_tmp = 0;
343  port = (unsigned short) port_tmp;
344 
345  addr = vs_config->getVariable( "network", "server_ip", "" );
346  this->_serverip = addr;
347  this->_serverport = port;
348  cout<<endl<<"Server IP : "<<addr<<" - port : "<<srvport<<endl<<endl;
349 }
void NetClient::SetCurrentServerAddress ( string  host,
unsigned short  port 
)

Definition at line 322 of file netclient_login.cpp.

Referenced by Reconnect().

323 {
324  this->_serverip = addr;
325  this->_serverport = port;
326 }
void NetClient::setUnit ( Unit un)
inline

Definition at line 186 of file netclient.h.

References UnitContainer::SetUnit().

Referenced by createObjects().

187  {
188  game_unit.SetUnit( un );
189  }
void NetClient::shipRequest ( const std::string &  cargo,
unsigned char  type 
)

Definition at line 127 of file netclient_devices.cpp.

References NetBuffer::addChar(), NetBuffer::addString(), CMD_SHIPDEALER, send(), and SENDRELIABLE.

Referenced by buyShip(), and sellShip().

128 {
129  NetBuffer netbuf;
130  netbuf.addString( cargo );
131  netbuf.addChar( type );
132  send( CMD_SHIPDEALER, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
133 }
const vector< string >& NetClient::shipSelections ( )
inline

Definition at line 154 of file netclient.h.

Referenced by NetActionConfirm::confirmedJoinGame().

155  {
156  return ship_select_list;
157  }
void NetClient::startCommunication ( )

Definition at line 271 of file netclient_devices.cpp.

References NetBuffer::addChar(), NetBuffer::addFloat(), CMD_STARTNETCOMM, NetBuffer::getData(), NetBuffer::getDataLength(), NetworkCommunication::HasPortaudio(), NetworkCommunication::HasWebcam(), NetworkCommunication::InitSession(), NetworkCommunication::IsSecured(), PSEUDO__LINE__, Packet::send(), SENDRELIABLE, and serial.

Referenced by FlyByKeyboard::Execute().

272 {
273  if (NetComm != NULL) {
274  char webcam_support = NetComm->HasWebcam();
275  char portaudio_support = NetComm->HasPortaudio();
276  selected_freq = current_freq;
277  NetBuffer netbuf;
278  netbuf.addFloat( selected_freq );
279  netbuf.addChar( NetComm->IsSecured() );
280  netbuf.addChar( webcam_support );
281  netbuf.addChar( portaudio_support );
282  NetComm->InitSession( selected_freq );
283  //cerr<<"Session started."<<endl;
284  //cerr<<"Grabbing an image"<<endl;
285  Packet p;
286  p.send( CMD_STARTNETCOMM, serial, netbuf.getData(), netbuf.getDataLength(), SENDRELIABLE, NULL, *this->clt_tcp_sock,
287  __FILE__, PSEUDO__LINE__( 1565 ) );
288  cerr<<"Starting communication session\n\n"<<endl;
289  //NetComm->GrabImage();
290  }
291 }
void NetClient::startGame ( )

Definition at line 715 of file netclient_login.cpp.

References _Universe, Universe::AccessCockpit(), bootstrap_draw(), Universe::clearAllSystems(), CopySavedShips(), Universe::createCockpit(), createObjects(), inGame(), Universe::Init(), Universe::numPlayers(), SaveGame::ParseSaveGame(), QVector, Cockpit::savegame, SaveGame::SetStarSystem(), synchronizeTime(), and Vector.

Referenced by NetActionConfirm::finalizeJoinGame().

716 {
717  vector< string >savedships;
718  QVector pos;
719  //useless.
720  string mysystem;
721  string savefiles;
722  bool setplayerXloc = false;
723  float credits = 0.0;
724  vector< StarSystem* >ss;
725  vector< QVector > playerNloc;
726  vector< string >playersaveunit;
727  vector< vector< string > >vecstr;
728 
729  bootstrap_draw( "#cc66ffNETWORK: Checking for UDP connection.", NULL );
730  cout<<"NETWORK: Checking for UDP connection."<<endl;
731  synchronizeTime( NULL );
732  cout<<" logged in !"<<endl;
733 
734  bootstrap_draw( "#cc66ffNETWORK: Loading player ship.", NULL );
735  cout<<"NETWORK: Loading player ship."<<endl;
736  if (_Universe->numPlayers() == 0)
737  _Universe->createCockpit( callsign );
739  _Universe->AccessCockpit( 0 )->savegame->SetStarSystem( string() );
741  mysystem,
742  "",
743  pos,
744  setplayerXloc,
745  credits,
746  savedships,
747  0,
748  lastsave[0],
749  false );
750 
751  ss.push_back( _Universe->Init( mysystem, Vector( 0, 0, 0 ), string() ) );
752 
753  CopySavedShips( callsign, 0, savedships, true );
754  playersaveunit.push_back( savedships[0] );
755  if (setplayerXloc)
756  playerNloc.push_back( pos );
757  else
758  playerNloc.push_back( QVector( FLT_MAX, FLT_MAX, FLT_MAX ) );
759  vecstr.push_back( lastsave );
760  createObjects( playersaveunit, ss, playerNloc, vecstr );
761  bootstrap_draw( "#cc66ffNETWORK: Loading system.", NULL );
762  cout<<"NETWORK: Loading system."<<endl;
763  inGame();
764  //PacketLoop(CMD_ADDEDYOU); // Wait for the command before stopping.
765 }
void NetClient::startWebcamTransfer ( )

Definition at line 349 of file netclient_devices.cpp.

References NetworkCommunication::StartWebcamTransfer().

Referenced by VDU::SwitchMode().

350 {
351  this->NetComm->StartWebcamTransfer();
352 }
void NetClient::stopCommunication ( )

Definition at line 293 of file netclient_devices.cpp.

References NetBuffer::addFloat(), CMD_STOPNETCOMM, NetworkCommunication::DestroySession(), NetBuffer::getData(), NetBuffer::getDataLength(), PSEUDO__LINE__, Packet::send(), SENDRELIABLE, and serial.

Referenced by FlyByKeyboard::Execute().

294 {
295  if (NetComm != NULL) {
296  NetBuffer netbuf;
297  netbuf.addFloat( selected_freq );
298  Packet p;
299  p.send( CMD_STOPNETCOMM, serial, netbuf.getData(), netbuf.getDataLength(), SENDRELIABLE, NULL, *this->clt_tcp_sock,
300  __FILE__, PSEUDO__LINE__( 1578 ) );
301  NetComm->DestroySession();
302  cerr<<"Stopped communication session"<<endl;
303  }
304 }
void NetClient::stopWebcamTransfer ( )

Definition at line 354 of file netclient_devices.cpp.

References NetworkCommunication::StopWebcamTransfer().

Referenced by VDU::SwitchMode().

355 {
356  this->NetComm->StopWebcamTransfer();
357 }
void NetClient::switchSecured ( )

Definition at line 386 of file netclient_devices.cpp.

References NetworkCommunication::SwitchSecured().

Referenced by FlyByKeyboard::Execute().

387 {
388  if (NetComm != NULL)
389  NetComm->SwitchSecured();
390 }
void NetClient::switchWebcam ( )

Definition at line 391 of file netclient_devices.cpp.

References NetworkCommunication::SwitchWebcam().

Referenced by FlyByKeyboard::Execute().

392 {
393  if (NetComm != NULL)
394  NetComm->SwitchWebcam();
395 }
void NetClient::synchronizeTime ( SOCKETALT udpsock)

Definition at line 462 of file netclient_login.cpp.

References _Universe, Universe::AccessCockpit(), NetBuffer::addShort(), CMD_SERVERTIME, COUT, NetUIUDP::createSocket(), NetUIUDP::disconnectSaveUDP(), UniverseUtil::exp(), Packet::getCommand(), NetBuffer::getData(), Packet::getData(), Packet::getDataLength(), NetBuffer::getDataLength(), NetBuffer::getDouble(), VegaConfig::getVariable(), i, SOCKETALT::isTcp(), NetUIBase::lookupHost(), Universe::numPlayers(), XMLSupport::parse_int(), PSEUDO__LINE__, queryTime(), VsnetOSS::recv(), Packet::send(), SENDRELIABLE, SOCKETALT::set_block(), SOCKETALT::set_nonblock(), setNewTime(), SOCKETALT::setRemoteAddress(), Cockpit::TimeOfLastCollision, VSRandom::uniformInc(), SOCKETALT::valid(), vs_config, and vsrandom.

Referenced by Reconnect(), and startGame().

463 {
464  int i = 0;
465  int timeout = 0;
466  int recv;
467  timeval tv = {1, 0}; //Timeout after 1 second, request send again.
468  double ping; //use deltaTime?
469  double pingavg = 0.;
470  double timeavg = 0.;
471  std::map< double, double >times; //sorted container.
472  double initialTime = queryTime();
473  static int NUM_TIMES = XMLSupport::parse_int( vs_config->getVariable( "network", "servertime_calibration", "10" ) );
474  static int UDP_TIMEOUT = XMLSupport::parse_int( vs_config->getVariable( "network", "udp_timeout", "1" ) );
475  static int clt_port_read = XMLSupport::parse_int( vs_config->getVariable( "network", "udp_listen_port", "6778" ) );
476  if (clt_port_read > 65535 || clt_port_read <= 0)
477  clt_port_read = 0;
478  static int clt_port_read_max = XMLSupport::parse_int( vs_config->getVariable( "network", "udp_listen_port_max", "6778" ) );
479  if (clt_port_read_max > 65535 || clt_port_read_max <= 0)
480  clt_port_read_max = clt_port_read;
481  unsigned short clt_port = (unsigned short) clt_port_read;
482  unsigned short clt_port_max = (unsigned short) clt_port_read_max;
483  if (clt_port_max < clt_port)
484  clt_port_max = clt_port;
485  static string nettransport = vs_config->getVariable( "network", "transport", "udp" );
486 
487  //std::string addr;
488  unsigned short port = this->_serverport;
489  //getConfigServerAddress(addr, port);
490  if ( !( udpsock != NULL && udpsock->setRemoteAddress( NetUIBase::lookupHost( this->_serverip.c_str(), port ) ) ) ) {
491  do
492  *this->clt_udp_sock = NetUIUDP::createSocket( this->_serverip.c_str(), port, clt_port, _sock_set );
493  while ( ( !this->clt_udp_sock->valid() ) && (clt_port++) );
494  } else {
495  this->clt_udp_sock = udpsock;
496  }
497  COUT<<"created UDP socket ("<<this->_serverip<<","<<port<<", listen on "<<clt_port<<") -> "<<this->clt_udp_sock<<endl;
498  if (nettransport == "udp") {
499  //NETFIXME: Keep trying ports until a connection is established.
500  COUT<<"Default lossy transport configured to UDP."<<endl;
501  this->lossy_socket = clt_udp_sock;
502  } else {
503  COUT<<"Default lossy transport configured to TCP (behind firewall)."<<endl;
504  this->lossy_socket = clt_tcp_sock;
505  clt_port = 0;
506  }
507  this->clt_tcp_sock->set_block();
508  this->clt_udp_sock->set_block();
509  //Wait for NUM_TIMES (10) successful tries, or 10 consecutive 1-second timeouts
510  //(we use UDP on the response (SENDANDFORGET) to improve timing accuracy).
511  while (i < NUM_TIMES && timeout < UDP_TIMEOUT) {
512  Packet packet;
513  NetBuffer outData;
514  outData.addShort( clt_port );
515  packet.send( CMD_SERVERTIME, 0,
516  outData.getData(), outData.getDataLength(), //No data.
517  SENDRELIABLE, NULL, *this->clt_tcp_sock,
518  __FILE__, PSEUDO__LINE__( 343 ) );
519  recv = this->recvMsg( &packet, &tv );
520  //If we have no response.
521  if (recv <= 0) {
522  COUT<<"synchronizeTime() Timed out"<<endl;
523  ++timeout;
524  if (timeout >= UDP_TIMEOUT) {
525  if (this->lossy_socket->isTcp() == false) {
526  if (clt_port < clt_port_max && !udpsock) {
527  NetUIUDP::disconnectSaveUDP( *this->clt_udp_sock );
528  *this->clt_udp_sock = NetUIUDP::createSocket( this->_serverip.c_str(), port, clt_port, _sock_set );
529  clt_port++;
530  COUT<<"Trying UDP port "<<clt_port<<"."<<endl;
531  } else {
532  //no UDP requests made it, fallback to TCP.
533  this->lossy_socket = this->clt_tcp_sock;
534  clt_port = 0;
535  COUT<<"Setting default lossy transport to TCP (UDP timeout)."<<endl;
536  }
537  timeout = 0;
538  }
539  }
540  } else if (packet.getCommand() == CMD_SERVERTIME) {
541  //NETFIXME: obtain actual ping time
542  //ping = getPingTime( &tv );
543  ping = exp( vsrandom.uniformInc( -10, 0 ) );
544  if (ping > 0 && ping < 1.) {
545  ++i;
546  NetBuffer data( packet.getData(), packet.getDataLength() );
547  double serverTime = data.getDouble();
548  double currentTime = queryTime();
549  serverTime += initialTime-currentTime;
550  times.insert( std::multimap< double, double >::value_type( ping, serverTime-ping ) );
551  timeout = 0;
552  } else {
553  ++timeout;
554  }
555  }
556  }
557  this->clt_tcp_sock->set_nonblock();
558  this->clt_udp_sock->set_nonblock();
559 //std::sort(times[0], times[i]);
560  if (i >= NUM_TIMES) {
561  int mid = i/2;
562  double median = 0.;
563  double tot = 0.;
564  int location = 0;
565  std::map< double, double >::const_iterator iter;
566  for (iter = times.begin(); iter != times.end(); ++iter) {
567  if (location == mid) {
568  median = iter->first;
569  if (i%2 == 1) {
570  ++iter;
571  median += iter->first;
572  }
573  break;
574  }
575  ++location;
576  }
577  if (i%2 == 1)
578  median /= 2;
579  for (iter = times.begin(); iter != times.end(); ++iter) {
580  double wdiff = exp( -10*(median-iter->first)*(median-iter->first) );
581  pingavg += wdiff*iter->first;
582  timeavg += wdiff*iter->second;
583  tot += wdiff;
584  }
585  pingavg /= tot;
586  timeavg /= tot;
587  } else {
588  COUT<<"Error in time synchronization: connection ended or timed out.";
589  }
590  this->deltatime = pingavg;
591  double newTime = timeavg+queryTime()-initialTime;
592  COUT<<"Setting time to: New time: "<<newTime<<endl;
593  setNewTime( newTime );
594  for (unsigned int cpnum = 0; cpnum < _Universe->numPlayers(); cpnum++)
595  //Seems like a bad idea... shouldn't this rely on SIMULATION_ATOM?
596  _Universe->AccessCockpit( cpnum )->TimeOfLastCollision = -200;
597  cur_time = newTime;
598 }
void NetClient::targetRequest ( Unit target)

Definition at line 68 of file netclient_devices.cpp.

References NetBuffer::addSerial(), CMD_TARGET, Unit::computer, Unit::GetSerial(), UnitContainer::GetUnit(), send(), SENDRELIABLE, UnitContainer::SetUnit(), and Unit::Computer::target.

Referenced by ChooseTargets(), and getNearestTargetUnit().

69 {
70  NetBuffer netbuf;
71  Unit *un = this->game_unit.GetUnit();
72  if (!un) return;
73  netbuf.addSerial( target->GetSerial() );
74 
75  send( CMD_TARGET, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
76  if (target->GetSerial() == 0)
77  //not networked unit
78  un->computer.target.SetUnit( target );
79 }
void NetClient::textMessage ( const string &  data)

Definition at line 304 of file netclient_login.cpp.

References NetBuffer::addString(), CMD_TXTMESSAGE, NetBuffer::getData(), NetBuffer::getDataLength(), PSEUDO__LINE__, Packet::send(), and SENDRELIABLE.

Referenced by CockpitKeys::TextMessageCallback().

305 {
306  Packet packet2;
307  NetBuffer netbuf;
308  netbuf.addString( data );
309  //No data.
310  packet2.send( CMD_TXTMESSAGE, 0,
311  netbuf.getData(), netbuf.getDataLength(),
312  SENDRELIABLE, NULL, *this->clt_tcp_sock,
313  __FILE__, PSEUDO__LINE__( 165 ) );
314 }
void NetClient::undockRequest ( ObjSerial  utdw_serial)

Definition at line 238 of file netclient_devices.cpp.

References NetBuffer::addSerial(), CMD_UNDOCK, send(), and SENDRELIABLE.

Referenced by BaseInterface::Room::Launch::Click(), and Unit::UnDock().

239 {
240  //Send a packet with CMD_UNDOCK with serial and an ObjSerial = unit_to_undock_with_serial
241  NetBuffer netbuf;
242 
243  cerr<<"SENDING A UNDOCK NOTIFICATION FOR UNIT "<<utdw_serial<<endl;
244  netbuf.addSerial( utdw_serial );
245  send( CMD_UNDOCK, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
246 }
void NetClient::unfireRequest ( ObjSerial  serial,
const vector< int > &  mount_indicies 
)

Definition at line 96 of file netclient_devices.cpp.

References NetBuffer::addInt32(), NetBuffer::addSerial(), CMD_UNFIREREQUEST, i, send(), and SENDRELIABLE.

Referenced by Unit::UnFire().

97 {
98  NetBuffer netbuf;
99 
100  netbuf.addSerial( serial );
101  netbuf.addInt32( mount_indicies.size() );
102  for (unsigned int i = 0; i < mount_indicies.size(); ++i)
103  netbuf.addInt32( mount_indicies[i] );
104  send( CMD_UNFIREREQUEST, netbuf, SENDRELIABLE, __FILE__, __LINE__ );
105 }
void NetClient::unreadyToJump ( )

Definition at line 173 of file netclient_devices.cpp.

Referenced by StarSystem::ProcessPendingJumps().

174 {
175  jumpok = false;
176 }

Member Data Documentation


The documentation for this class was generated from the following files: