Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/network/Server.cc @ 3133

Last change on this file since 3133 was 3102, checked in by scheusso, 15 years ago

fixed some problems when changing the gamestate (from menu to server i.e.)

  • Property svn:eol-style set to native
File size: 12.9 KB
RevLine 
[1502]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
[3084]23 *      Oliver Scheuss
[1502]24 *   Co-authors:
25 *      ...
26 *
27 */
28
29//
30// C++ Implementation: Server
31//
32// Description:
33//
34//
35// Author:  Oliver Scheuss, (C) 2007
36//
37// Copyright: See COPYING file that comes with this distribution
38//
39//
40
41#include "Server.h"
42
[2773]43#include <enet/enet.h>
[1502]44#include <iostream>
[1755]45#include <cassert>
[1502]46
47
48#include "ConnectionManager.h"
[2087]49#include "ClientConnectionListener.h"
[1735]50#include "GamestateManager.h"
[1502]51#include "ClientInformation.h"
52#include "util/Sleep.h"
[2896]53#include "core/Clock.h"
[1534]54#include "core/ConsoleCommand.h"
[1752]55#include "core/CoreIncludes.h"
[1747]56#include "core/Iterator.h"
[1735]57#include "packet/Chat.h"
58#include "packet/Packet.h"
59#include "packet/Welcome.h"
[1907]60#include "packet/DeleteObjects.h"
[2773]61#include "util/Convert.h"
[2087]62#include "ChatListener.h"
[3084]63#include "FunctionCallManager.h"
64#include "packet/FunctionIDs.h"
[1502]65
[3084]66
[2171]67namespace orxonox
[1502]68{
[2087]69  const unsigned int MAX_FAILURES = 20;
[1747]70
[1502]71  /**
72  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
73  *
74  */
75  Server::Server() {
76    timeSinceLastUpdate_=0;
[1735]77    connection = new ConnectionManager();
78    gamestates_ = new GamestateManager();
[1502]79  }
[1747]80
[1502]81  Server::Server(int port){
82    timeSinceLastUpdate_=0;
[1735]83    connection = new ConnectionManager(port);
84    gamestates_ = new GamestateManager();
[1502]85  }
86
87  /**
88  * Constructor
89  * @param port Port to listen on
90  * @param bindAddress Address to listen on
91  */
[2087]92  Server::Server(int port, const std::string& bindAddress) {
[1502]93    timeSinceLastUpdate_=0;
[1735]94    connection = new ConnectionManager(port, bindAddress);
95    gamestates_ = new GamestateManager();
[1502]96  }
97
98  /**
99  * Constructor
100  * @param port Port to listen on
101  * @param bindAddress Address to listen on
102  */
103  Server::Server(int port, const char *bindAddress) {
104    timeSinceLastUpdate_=0;
[1735]105    connection = new ConnectionManager(port, bindAddress);
106    gamestates_ = new GamestateManager();
[1502]107  }
[2087]108
[1907]109  /**
110  * @brief Destructor
111  */
112  Server::~Server(){
113    if(connection)
114      delete connection;
115    if(gamestates_)
116      delete gamestates_;
117  }
[1502]118
119  /**
120  * This function opens the server by creating the listener thread
121  */
122  void Server::open() {
123    connection->createListener();
124    return;
125  }
126
127  /**
128  * This function closes the server
129  */
130  void Server::close() {
131    connection->quitListener();
132    return;
133  }
134
[2087]135  bool Server::processChat(const std::string& message, unsigned int playerID){
[1735]136    ClientInformation *temp = ClientInformation::getBegin();
[1907]137    packet::Chat *chat;
[1735]138    while(temp){
[1907]139      chat = new packet::Chat(message, playerID);
[1735]140      chat->setClientID(temp->getID());
141      if(!chat->send())
142        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
[1907]143      temp = temp->next();
[1735]144    }
[2087]145//    COUT(1) << "Player " << playerID << ": " << message << std::endl;
[1907]146    return true;
[1502]147  }
148
149
150  /**
151  * Run this function once every tick
152  * calls processQueue and updateGamestate
153  * @param time time since last tick
154  */
[2896]155  void Server::update(const Clock& time) {
[1502]156    processQueue();
[3084]157    gamestates_->processGamestates();
[1502]158    //this steers our network frequency
[2896]159    timeSinceLastUpdate_+=time.getDeltaTime();
[2087]160    if(timeSinceLastUpdate_>=NETWORK_PERIOD){
161      timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
[1502]162      updateGamestate();
[3084]163      FunctionCallManager::sendCalls();
[1502]164    }
165  }
[1747]166
[1735]167  bool Server::queuePacket(ENetPacket *packet, int clientID){
168    return connection->addPacket(packet, clientID);
169  }
[2087]170 
171  /**
172   * @brief: returns ping time to client in milliseconds
173   */
174  unsigned int Server::getPing(unsigned int clientID){
175    assert(ClientInformation::findClient(clientID));
176    return ClientInformation::findClient(clientID)->getRTT();
177  }
[1502]178
179  /**
[2087]180   * @brief: return packet loss ratio to client (scales from 0 to 1)
181   */
182  double Server::getPacketLoss(unsigned int clientID){
183    assert(ClientInformation::findClient(clientID));
184    return ClientInformation::findClient(clientID)->getPacketLoss();
185  }
186 
187  /**
[1502]188  * processes all the packets waiting in the queue
189  */
190  void Server::processQueue() {
191    ENetEvent *event;
192    while(!connection->queueEmpty()){
193      //std::cout << "Client " << clientID << " sent: " << std::endl;
194      //clientID here is a reference to grab clientID from ClientInformation
195      event = connection->getEvent();
196      if(!event)
197        continue;
198      assert(event->type != ENET_EVENT_TYPE_NONE);
199      switch( event->type ) {
200      case ENET_EVENT_TYPE_CONNECT:
201        COUT(3) << "processing event_Type_connect" << std::endl;
202        addClient(event);
203        break;
204      case ENET_EVENT_TYPE_DISCONNECT:
[1735]205        if(ClientInformation::findClient(&event->peer->address))
[1502]206          disconnectClient(event);
207        break;
208      case ENET_EVENT_TYPE_RECEIVE:
[1735]209        if(!processPacket(event->packet, event->peer))
210          COUT(3) << "processing incoming packet failed" << std::endl;
[1502]211        break;
[1556]212      default:
213        break;
[1502]214      }
215      delete event;
216      //if statement to catch case that packetbuffer is empty
217    }
218  }
219
220  /**
221  * takes a new snapshot of the gamestate and sends it to the clients
222  */
223  void Server::updateGamestate() {
[2662]224//     if( ClientInformation::getBegin()==NULL )
225      //no client connected
226//       return;
[1735]227    gamestates_->update();
[1534]228    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
[1502]229    //std::cout << "updated gamestate, sending it" << std::endl;
230    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
231    sendGameState();
[1907]232    sendObjectDeletes();
[1534]233    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
[1502]234    //std::cout << "sent gamestate" << std::endl;
235  }
236
[1735]237  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
238    packet::Packet *p = packet::Packet::createPacket(packet, peer);
239    return p->process();
240  }
[1747]241
[1502]242  /**
243  * sends the gamestate
244  */
245  bool Server::sendGameState() {
246    COUT(5) << "Server: starting function sendGameState" << std::endl;
[1735]247    ClientInformation *temp = ClientInformation::getBegin();
[1502]248    bool added=false;
249    while(temp != NULL){
250      if( !(temp->getSynched()) ){
251        COUT(5) << "Server: not sending gamestate" << std::endl;
252        temp=temp->next();
[1735]253        if(!temp)
254          break;
[1502]255        //think this works without continue
256        continue;
257      }
[1534]258      COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
[1502]259      COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl;
260      int gid = temp->getGamestateID(); //get gamestate id
261      int cid = temp->getID(); //get client id
262      COUT(5) << "Server: got acked (gamestate) ID from clientlist: " << gid << std::endl;
[1735]263      packet::Gamestate *gs = gamestates_->popGameState(cid);
[1502]264      if(gs==NULL){
265        COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
[2087]266        temp = temp->next();
[1502]267        continue;
268      }
269      //std::cout << "adding gamestate" << std::endl;
[1735]270      gs->setClientID(cid);
271      if ( !gs->send() ){
[1747]272        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
[1502]273        temp->addFailure();
274      }else
275        temp->resetFailures();
276      added=true;
277      temp=temp->next();
[1735]278      // gs gets automatically deleted by enet callback
[1502]279    }
280    return true;
281  }
[1747]282
[1907]283  bool Server::sendObjectDeletes(){
284    ClientInformation *temp = ClientInformation::getBegin();
[2662]285    if( temp == NULL )
286      //no client connected
287      return true;
[1907]288    packet::DeleteObjects *del = new packet::DeleteObjects();
289    if(!del->fetchIDs())
290      return true;  //everything ok (no deletes this tick)
291//     COUT(3) << "sending DeleteObjects" << std::endl;
292    while(temp != NULL){
293      if( !(temp->getSynched()) ){
294        COUT(5) << "Server: not sending gamestate" << std::endl;
295        temp=temp->next();
296        continue;
297      }
298      int cid = temp->getID(); //get client id
299      packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
300      assert(cd);
301      cd->setClientID(cid);
302      if ( !cd->send() )
303        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
304      temp=temp->next();
305      // gs gets automatically deleted by enet callback
306    }
307    return true;
308  }
[1747]309
[1907]310
[1502]311  bool Server::addClient(ENetEvent *event){
[2087]312    static unsigned int newid=1;
313
314    COUT(2) << "Server: adding client" << std::endl;
[1735]315    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
[1502]316    if(!temp){
317      COUT(2) << "Server: could not add client" << std::endl;
318      return false;
319    }
[2087]320    /*if(temp==ClientInformation::getBegin()) { //not good if you use anything else than insertBack
321      newid=1;
[1502]322    }
323    else
[2087]324      newid=temp->prev()->getID()+1;*/
325    temp->setID(newid);
[1502]326    temp->setPeer(event->peer);
[2087]327
328    // inform all the listeners
[2171]329    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
[2087]330    while(listener){
331      listener->clientConnected(newid);
332      listener++;
333    }
334
335    newid++;
336
[1502]337    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
338    return createClient(temp->getID());
[2087]339}
[1747]340
[1502]341  bool Server::createClient(int clientID){
[1735]342    ClientInformation *temp = ClientInformation::findClient(clientID);
[1502]343    if(!temp){
344      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
345      return false;
346    }
[3084]347    COUT(5) << "Con.Man: creating client id: " << temp->getID() << std::endl;
348   
349    // synchronise class ids
[1502]350    connection->syncClassid(temp->getID());
[3084]351   
352    // now synchronise functionIDs
353    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
354    fIDs->setClientID(clientID);
355    bool b = fIDs->send();
356    assert(b);
357   
[1502]358    temp->setSynched(true);
[3084]359    COUT(4) << "sending welcome" << std::endl;
[1735]360    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
361    w->setClientID(temp->getID());
[3084]362    b = w->send();
[1907]363    assert(b);
[1751]364    packet::Gamestate *g = new packet::Gamestate();
365    g->setClientID(temp->getID());
[3102]366    b = g->collectData(0,0x1);
[2087]367    if(!b)
368      return false; //no data for the client
[1907]369    b = g->compressData();
370    assert(b);
371    b = g->send();
372    assert(b);
[1502]373    return true;
374  }
[1747]375
[1502]376  bool Server::disconnectClient(ENetEvent *event){
377    COUT(4) << "removing client from list" << std::endl;
378    //return removeClient(head_->findClient(&(peer->address))->getID());
[1747]379
[1502]380    //boost::recursive_mutex::scoped_lock lock(head_->mutex_);
[1735]381    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
[1502]382    if(!client)
383      return false;
[1751]384    gamestates_->removeClient(client);
[2087]385
386// inform all the listeners
[2171]387    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
[2087]388    while(listener){
389      listener->clientDisconnected(client->getID());
390      listener++;
[1502]391    }
[2087]392
393    return ClientInformation::removeClient(event->peer);
[1502]394  }
395
396  void Server::disconnectClient(int clientID){
[1735]397    ClientInformation *client = ClientInformation::findClient(clientID);
[1502]398    if(client)
399      disconnectClient(client);
400  }
401  void Server::disconnectClient( ClientInformation *client){
402    connection->disconnectClient(client);
[1735]403    gamestates_->removeClient(client);
[1502]404  }
[2087]405
406  bool Server::chat(const std::string& message){
407      return this->sendChat(message, Host::getPlayerID());
408  }
409
410  bool Server::broadcast(const std::string& message){
411      return this->sendChat(message, CLIENTID_UNKNOWN);
412  }
413
414  bool Server::sendChat(const std::string& message, unsigned int clientID){
[1907]415    ClientInformation *temp = ClientInformation::getBegin();
416    packet::Chat *chat;
417    while(temp){
[2087]418      chat = new packet::Chat(message, clientID);
[1907]419      chat->setClientID(temp->getID());
420      if(!chat->send())
421        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
422      temp = temp->next();
423    }
[2087]424//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
[2171]425    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
[2087]426      it->incomingChat(message, clientID);
427
[1907]428    return true;
429  }
[1747]430
[1502]431}
Note: See TracBrowser for help on using the repository browser.