Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 1752 was 1752, checked in by landauf, 16 years ago
  • removed #include "core/CoreIncludes.h" from Gamestate.h and put it into the .cc files
  • removed a warning in Client.cc
  • Property svn:eol-style set to native
File size: 12.4 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, (C) 2007
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#include <iostream>
44
45
46#include "ConnectionManager.h"
47#include "GamestateManager.h"
48#include "ClientInformation.h"
49#include "util/Sleep.h"
50#include "objects/SpaceShip.h"
51#include "core/ConsoleCommand.h"
52#include "core/CoreIncludes.h"
53#include "core/Iterator.h"
54#include "packet/Chat.h"
55#include "packet/Packet.h"
56#include "packet/Welcome.h"
57#include <util/Convert.h>
58
59namespace network
60{
61  #define MAX_FAILURES 20;
62  #define NETWORK_FREQUENCY 30
63
64  /**
65  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
66  *
67  */
68  Server::Server() {
69    timeSinceLastUpdate_=0;
70    connection = new ConnectionManager();
71    gamestates_ = new GamestateManager();
72    isServer_ = true;
73  }
74
75  Server::Server(int port){
76    timeSinceLastUpdate_=0;
77    connection = new ConnectionManager(port);
78    gamestates_ = new GamestateManager();
79    isServer_ = true;
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, std::string bindAddress) {
88    timeSinceLastUpdate_=0;
89    connection = new ConnectionManager(port, bindAddress);
90    gamestates_ = new GamestateManager();
91    isServer_ = true;
92  }
93
94  /**
95  * Constructor
96  * @param port Port to listen on
97  * @param bindAddress Address to listen on
98  */
99  Server::Server(int port, const char *bindAddress) {
100    timeSinceLastUpdate_=0;
101    connection = new ConnectionManager(port, bindAddress);
102    gamestates_ = new GamestateManager();
103    isServer_ = true;
104  }
105
106  /**
107  * This function opens the server by creating the listener thread
108  */
109  void Server::open() {
110    connection->createListener();
111    return;
112  }
113
114  /**
115  * This function closes the server
116  */
117  void Server::close() {
118    connection->quitListener();
119    return;
120  }
121
122  bool Server::processChat(packet::Chat *message, unsigned int clientID){
123    ClientInformation *temp = ClientInformation::getBegin();
124    while(temp){
125      message->setClientID(temp->getID());
126      if(!message->send())
127        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
128      temp = temp->next();
129    }
130    return message->process();
131  }
132
133  /**
134  * This function sends out a message to all clients
135  * @param msg message
136  * @return true/false
137  */
138  bool Server::sendChat(packet::Chat *chat) {
139    //TODO: change this (no informations about who wrote a message)
140    assert(0);
141    ClientInformation *temp = ClientInformation::getBegin();
142    while(temp){
143      chat->setClientID(temp->getID());
144      if(!chat->send())
145        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
146    }
147    return chat->process();;
148  }
149
150  /**
151  * This function sends out a message to all clients
152  * @param msg message
153  * @return true/false
154  */
155//   bool Server::sendChat(const char *msg) {
156//     char *message = new char [strlen(msg)+10+1];
157//     sprintf(message, "Player %d: %s", CLIENTID_SERVER, msg);
158//     COUT(1) << message << std::endl;
159//     ENetPacket *packet = packet_gen.chatMessage(message);
160//     COUT(5) <<"Server: adding Packets" << std::endl;
161//     return connection->addPacketAll(packet);
162//   }
163
164  /**
165  * Run this function once every tick
166  * calls processQueue and updateGamestate
167  * @param time time since last tick
168  */
169  void Server::tick(float time) {
170    processQueue();
171    //this steers our network frequency
172    timeSinceLastUpdate_+=time;
173    if(timeSinceLastUpdate_>=(1./NETWORK_FREQUENCY)){
174      timeSinceLastUpdate_=(float)((int)(timeSinceLastUpdate_*NETWORK_FREQUENCY))/timeSinceLastUpdate_;
175//      timeSinceLastUpdate_-=1./NETWORK_FREQUENCY;
176      gamestates_->processGamestates();
177      updateGamestate();
178    }
179    /*while(timeSinceLastUpdate_>1./NETWORK_FREQUENCY)
180      timeSinceLastUpdate_-=1./NETWORK_FREQUENCY;*/
181//     usleep(5000); // TODO remove
182    return;
183  }
184
185  bool Server::queuePacket(ENetPacket *packet, int clientID){
186    return connection->addPacket(packet, clientID);
187  }
188
189  /**
190  * processes all the packets waiting in the queue
191  */
192  void Server::processQueue() {
193    ENetEvent *event;
194    while(!connection->queueEmpty()){
195      //std::cout << "Client " << clientID << " sent: " << std::endl;
196      //clientID here is a reference to grab clientID from ClientInformation
197      event = connection->getEvent();
198      if(!event)
199        continue;
200      assert(event->type != ENET_EVENT_TYPE_NONE);
201      switch( event->type ) {
202      case ENET_EVENT_TYPE_CONNECT:
203        COUT(3) << "processing event_Type_connect" << std::endl;
204        addClient(event);
205        break;
206      case ENET_EVENT_TYPE_DISCONNECT:
207        if(ClientInformation::findClient(&event->peer->address))
208          disconnectClient(event);
209        break;
210      case ENET_EVENT_TYPE_RECEIVE:
211        if(!processPacket(event->packet, event->peer))
212          COUT(3) << "processing incoming packet failed" << std::endl;
213        break;
214      default:
215        break;
216      }
217      delete event;
218      //if statement to catch case that packetbuffer is empty
219    }
220  }
221
222  /**
223  * takes a new snapshot of the gamestate and sends it to the clients
224  */
225  void Server::updateGamestate() {
226    gamestates_->update();
227    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
228    //std::cout << "updated gamestate, sending it" << std::endl;
229    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
230    sendGameState();
231    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
232    //std::cout << "sent gamestate" << std::endl;
233  }
234
235  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
236    packet::Packet *p = packet::Packet::createPacket(packet, peer);
237    return p->process();
238  }
239
240  /**
241  * sends the gamestate
242  */
243  bool Server::sendGameState() {
244    COUT(5) << "Server: starting function sendGameState" << std::endl;
245    ClientInformation *temp = ClientInformation::getBegin();
246    bool added=false;
247    while(temp != NULL){
248      if( !(temp->getSynched()) ){
249        COUT(5) << "Server: not sending gamestate" << std::endl;
250        temp=temp->next();
251        if(!temp)
252          break;
253        //think this works without continue
254        continue;
255      }
256      COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
257      COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl;
258      int gid = temp->getGamestateID(); //get gamestate id
259      int cid = temp->getID(); //get client id
260      COUT(5) << "Server: got acked (gamestate) ID from clientlist: " << gid << std::endl;
261      packet::Gamestate *gs = gamestates_->popGameState(cid);
262      if(gs==NULL){
263        COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
264        continue;
265      }
266      //std::cout << "adding gamestate" << std::endl;
267      gs->setClientID(cid);
268      if ( !gs->send() ){
269        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
270        temp->addFailure();
271      }else
272        temp->resetFailures();
273      added=true;
274      temp=temp->next();
275      // gs gets automatically deleted by enet callback
276    }
277    /*if(added) {
278      //std::cout << "send gamestates from server.cc in sendGameState" << std::endl;
279      return connection->sendPackets();
280    }*/
281    //COUT(5) << "Server: had no gamestates to send" << std::endl;
282    return true;
283  }
284
285//   void Server::processChat( chat *data, int clientId){
286//     char *message = new char [strlen(data->message)+10+1];
287//     sprintf(message, "Player %d: %s", clientId, data->message);
288//     COUT(1) << message << std::endl;
289//     ENetPacket *pck = packet_gen.chatMessage(message);
290//     connection->addPacketAll(pck);
291//     delete[] data->message;
292//     delete data;
293//   }
294
295  bool Server::addClient(ENetEvent *event){
296    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
297    if(!temp){
298      COUT(2) << "Server: could not add client" << std::endl;
299      return false;
300    }
301    if(temp==ClientInformation::getBegin()) { //not good if you use anything else than insertBack
302      temp->setID(1);
303    }
304    else
305      temp->setID(temp->prev()->getID()+1);
306    temp->setPeer(event->peer);
307    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
308    return createClient(temp->getID());
309  }
310
311  bool Server::createClient(int clientID){
312    ClientInformation *temp = ClientInformation::findClient(clientID);
313    if(!temp){
314      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
315      return false;
316    }
317    COUT(4) << "Con.Man: creating client id: " << temp->getID() << std::endl;
318    connection->syncClassid(temp->getID());
319    COUT(5) << "creating spaceship for clientid: " << temp->getID() << std::endl;
320    // TODO: this is only a hack, untill we have a possibility to define default player-join actions
321    if(!createShip(temp))
322      COUT(2) << "Con.Man. could not create ship for clientid: " << clientID << std::endl;
323    else
324      COUT(3) << "created spaceship" << std::endl;
325    temp->setSynched(true);
326    COUT(3) << "sending welcome" << std::endl;
327    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
328    w->setClientID(temp->getID());
329    assert(w->send());
330    packet::Gamestate *g = new packet::Gamestate();
331    g->setClientID(temp->getID());
332    assert(g->collectData(0));
333    assert(g->compressData());
334    assert(g->send());
335    return true;
336  }
337
338  bool Server::createShip(ClientInformation *client){
339    if(!client)
340      return false;
341    orxonox::Identifier* id = ID("SpaceShip");
342    if(!id){
343      COUT(4) << "We could not create the SpaceShip for client: " << client->getID() << std::endl;
344      return false;
345    }
346    orxonox::SpaceShip *no = dynamic_cast<orxonox::SpaceShip *>(id->fabricate());
347    no->classID = id->getNetworkID();
348    client->setShipID(no->objectID);
349    no->setPosition(orxonox::Vector3(0,0,80));
350    no->setScale(10);
351    //no->setYawPitchRoll(orxonox::Degree(-90),orxonox::Degree(-90),orxonox::Degree(0));
352    no->setMesh("assff.mesh");
353    no->setMaxSpeed(500);
354    no->setMaxSideAndBackSpeed(50);
355    no->setMaxRotation(1.0);
356    no->setTransAcc(200);
357    no->setRotAcc(3.0);
358    no->setTransDamp(75);
359    no->setRotDamp(1.0);
360    no->setCamera(std::string("cam_") + convertToString(client->getID()));
361    no->create();
362
363    return true;
364  }
365
366  bool Server::disconnectClient(ENetEvent *event){
367    COUT(4) << "removing client from list" << std::endl;
368    //return removeClient(head_->findClient(&(peer->address))->getID());
369
370    //boost::recursive_mutex::scoped_lock lock(head_->mutex_);
371    orxonox::ObjectList<orxonox::SpaceShip>::iterator it = orxonox::ObjectList<orxonox::SpaceShip>::begin();
372    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
373    if(!client)
374      return false;
375    gamestates_->removeClient(client);
376    while(it){
377      if(it->objectID!=client->getShipID()){
378        ++it;
379        continue;
380      }
381      orxonox::ObjectList<orxonox::SpaceShip>::iterator temp=it;
382      ++it;
383      delete  *temp;
384      return ClientInformation::removeClient(event->peer);
385    }
386    return false;
387  }
388
389  void Server::disconnectClient(int clientID){
390    ClientInformation *client = ClientInformation::findClient(clientID);
391    if(client)
392      disconnectClient(client);
393  }
394  void Server::disconnectClient( ClientInformation *client){
395    connection->disconnectClient(client);
396    gamestates_->removeClient(client);
397  }
398
399}
Note: See TracBrowser for help on using the repository browser.