Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/masterserver/src/libraries/network/Server.cc @ 7632

Last change on this file since 7632 was 7632, checked in by smerkli, 14 years ago

oops, forgot to rename the new lua function.

  • Property svn:eol-style set to native
File size: 11.9 KB
Line 
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:
23 *      Oliver Scheuss
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
43#define WIN32_LEAN_AND_MEAN
44#include <enet/enet.h>
45#include <cassert>
46#include <string>
47
48#include "util/Clock.h"
49#include "util/Debug.h"
50#include "core/ObjectList.h"
51#include "core/command/Executor.h"
52#include "packet/Chat.h"
53#include "packet/ClassID.h"
54#include "packet/DeleteObjects.h"
55#include "packet/FunctionIDs.h"
56#include "packet/Gamestate.h"
57#include "packet/Welcome.h"
58#include "ChatListener.h"
59#include "ClientInformation.h"
60#include "FunctionCallManager.h"
61#include "GamestateManager.h"
62
63namespace orxonox
64{
65  const unsigned int MAX_FAILURES = 20;
66
67  /**
68  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
69  *
70  */
71  Server::Server()
72  {
73    this->timeSinceLastUpdate_=0;
74  }
75
76  Server::Server(int port)
77  {
78    this->setPort( port );
79    this->timeSinceLastUpdate_=0;
80  }
81
82  /**
83  * Constructor
84  * @param port Port to listen on
85  * @param bindAddress Address to listen on
86  */
87  Server::Server(int port, const std::string& bindAddress)
88  {
89    this->setPort( port );
90    this->setBindAddress( bindAddress );
91    this->timeSinceLastUpdate_=0;
92  }
93
94  /**
95  * @brief Destructor
96  */
97  Server::~Server()
98  {
99  }
100
101  /**
102  * This function opens the server by creating the listener thread
103  */
104  void Server::open()
105  {
106    Host::setActive(true);
107    COUT(4) << "opening server" << endl;
108    this->openListener();
109    LANDiscoverable::setActivity(true);
110
111    /* TODO connect to master server here and say you're there */
112    return;
113  }
114
115  /**
116  * This function closes the server
117  */
118  void Server::close()
119  {
120    Host::setActive(false);
121    COUT(4) << "closing server" << endl;
122    this->disconnectClients();
123    this->closeListener();
124    LANDiscoverable::setActivity(false);
125    return;
126  }
127
128  bool Server::processChat(const std::string& message, unsigned int playerID)
129  {
130    ClientInformation *temp = ClientInformation::getBegin();
131    packet::Chat *chat;
132    while(temp){
133      chat = new packet::Chat(message, playerID);
134      chat->setClientID(temp->getID());
135      if(!chat->send())
136        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
137      temp = temp->next();
138    }
139//    COUT(1) << "Player " << playerID << ": " << message << std::endl;
140    return true;
141  }
142
143
144  /**
145  * Run this function once every tick
146  * calls processQueue and updateGamestate
147  * @param time time since last tick
148  */
149  void Server::update(const Clock& time)
150  {
151    // receive incoming packets
152    Connection::processQueue();
153
154    // receive and process incoming discovery packets
155    LANDiscoverable::update();
156
157    if ( ClientInformation::hasClients() )
158    {
159      // process incoming gamestates
160      GamestateManager::processGamestates();
161
162      // send function calls to clients
163      FunctionCallManager::sendCalls();
164
165      //this steers our network frequency
166      timeSinceLastUpdate_+=time.getDeltaTime();
167      if(timeSinceLastUpdate_>=NETWORK_PERIOD)
168      {
169        timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
170        updateGamestate();
171      }
172      sendPackets(); // flush the enet queue
173    }
174  }
175
176  bool Server::queuePacket(ENetPacket *packet, int clientID)
177  {
178    return ServerConnection::addPacket(packet, clientID);
179  }
180
181  /**
182   * @brief: returns ping time to client in milliseconds
183   */
184  unsigned int Server::getRTT(unsigned int clientID)
185  {
186    assert(ClientInformation::findClient(clientID));
187    return ClientInformation::findClient(clientID)->getRTT();
188  }
189
190  void Server::printRTT()
191  {
192    for( ClientInformation* temp=ClientInformation::getBegin(); temp!=0; temp=temp->next() )
193      COUT(0) << "Round trip time to client with ID: " << temp->getID() << " is " << temp->getRTT() << " ms" << endl;
194  }
195
196  /**
197   * @brief: return packet loss ratio to client (scales from 0 to 1)
198   */
199  double Server::getPacketLoss(unsigned int clientID)
200  {
201    assert(ClientInformation::findClient(clientID));
202    return ClientInformation::findClient(clientID)->getPacketLoss();
203  }
204
205  /**
206  * takes a new snapshot of the gamestate and sends it to the clients
207  */
208  void Server::updateGamestate()
209  {
210    if( ClientInformation::getBegin()==NULL )
211      //no client connected
212      return;
213    GamestateManager::update();
214    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
215    //std::cout << "updated gamestate, sending it" << std::endl;
216    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
217    sendGameState();
218    sendObjectDeletes();
219    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
220    //std::cout << "sent gamestate" << std::endl;
221  }
222
223  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
224    packet::Packet *p = packet::Packet::createPacket(packet, peer);
225    return p->process();
226  }
227
228  /**
229  * sends the gamestate
230  */
231  bool Server::sendGameState()
232  {
233//     COUT(5) << "Server: starting function sendGameState" << std::endl;
234//     ClientInformation *temp = ClientInformation::getBegin();
235//     bool added=false;
236//     while(temp != NULL){
237//       if( !(temp->getSynched()) ){
238//         COUT(5) << "Server: not sending gamestate" << std::endl;
239//         temp=temp->next();
240//         if(!temp)
241//           break;
242//         continue;
243//       }
244//       COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
245//       COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl;
246//       int cid = temp->getID(); //get client id
247//       packet::Gamestate *gs = GamestateManager::popGameState(cid);
248//       if(gs==NULL){
249//         COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
250//         temp = temp->next();
251//         continue;
252//       }
253//       //std::cout << "adding gamestate" << std::endl;
254//       gs->setClientID(cid);
255//       if ( !gs->send() ){
256//         COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
257//         temp->addFailure();
258//       }else
259//         temp->resetFailures();
260//       added=true;
261//       temp=temp->next();
262//       // gs gets automatically deleted by enet callback
263//     }
264    GamestateManager::sendGamestates();
265    return true;
266  }
267
268  bool Server::sendObjectDeletes()
269  {
270    ClientInformation *temp = ClientInformation::getBegin();
271    if( temp == NULL )
272      //no client connected
273      return true;
274    packet::DeleteObjects *del = new packet::DeleteObjects();
275    if(!del->fetchIDs())
276    {
277      delete del;
278      return true;  //everything ok (no deletes this tick)
279    }
280//     COUT(3) << "sending DeleteObjects" << std::endl;
281    while(temp != NULL){
282      if( !(temp->getSynched()) )
283      {
284        COUT(5) << "Server: not sending gamestate" << std::endl;
285        temp=temp->next();
286        continue;
287      }
288      int cid = temp->getID(); //get client id
289      packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
290      assert(cd);
291      cd->setClientID(cid);
292      if ( !cd->send() )
293        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
294      temp=temp->next();
295      // gs gets automatically deleted by enet callback
296    }
297    delete del;
298    return true;
299  }
300
301
302  void Server::addPeer(ENetEvent *event)
303  {
304    static unsigned int newid=1;
305
306    COUT(2) << "Server: adding client" << std::endl;
307    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
308    if(!temp)
309    {
310      COUT(2) << "Server: could not add client" << std::endl;
311    }
312    temp->setID(newid);
313    temp->setPeer(event->peer);
314
315    // inform all the listeners
316    ClientConnectionListener::broadcastClientConnected(newid);
317
318    ++newid;
319
320    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
321    createClient(temp->getID());
322}
323
324  void Server::removePeer(ENetEvent *event)
325  {
326    COUT(4) << "removing client from list" << std::endl;
327    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
328    if(!client)
329      return;
330    else
331    {
332      //ServerConnection::disconnectClient( client );
333      //ClientConnectionListener::broadcastClientDisconnected( client->getID() ); //this is done in ClientInformation now
334      delete client;
335    }
336  }
337
338  bool Server::createClient(int clientID)
339  {
340    ClientInformation *temp = ClientInformation::findClient(clientID);
341    if(!temp)
342    {
343      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
344      return false;
345    }
346    COUT(5) << "Con.Man: creating client id: " << temp->getID() << std::endl;
347
348    // synchronise class ids
349    syncClassid(temp->getID());
350
351    // now synchronise functionIDs
352    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
353    fIDs->setClientID(clientID);
354    bool b = fIDs->send();
355    assert(b);
356
357    temp->setSynched(true);
358    COUT(4) << "sending welcome" << std::endl;
359    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
360    w->setClientID(temp->getID());
361    b = w->send();
362    assert(b);
363    packet::Gamestate *g = new packet::Gamestate();
364    g->setClientID(temp->getID());
365    b = g->collectData(0,0x1);
366    if(!b)
367      return false; //no data for the client
368    b = g->compressData();
369    assert(b);
370    b = g->send();
371    assert(b);
372    return true;
373  }
374
375  void Server::disconnectClient( ClientInformation *client )
376  {
377    ServerConnection::disconnectClient( client );
378    GamestateManager::removeClient(client);
379    // inform all the listeners
380    // ClientConnectionListener::broadcastClientDisconnected(client->getID()); // this is done in ClientInformation now
381  }
382
383  bool Server::chat(const std::string& message)
384  {
385      return this->sendChat(message, Host::getPlayerID());
386  }
387
388  bool Server::broadcast(const std::string& message)
389  {
390      return this->sendChat(message, CLIENTID_UNKNOWN);
391  }
392
393  bool Server::sendChat(const std::string& message, unsigned int clientID)
394  {
395    ClientInformation *temp = ClientInformation::getBegin();
396    packet::Chat *chat;
397    while(temp)
398    {
399      chat = new packet::Chat(message, clientID);
400      chat->setClientID(temp->getID());
401      if(!chat->send())
402        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
403      temp = temp->next();
404    }
405//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
406    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
407      it->incomingChat(message, clientID);
408
409    return true;
410  }
411
412  void Server::syncClassid(unsigned int clientID)
413  {
414    int failures=0;
415    packet::ClassID *classid = new packet::ClassID();
416    classid->setClientID(clientID);
417    while(!classid->send() && failures < 10){
418      failures++;
419    }
420    assert(failures<10);
421    COUT(4) << "syncClassid:\tall synchClassID packets have been sent" << std::endl;
422  }
423
424}
Note: See TracBrowser for help on using the repository browser.