Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network/src/network/Server.cc @ 1775

Last change on this file since 1775 was 1775, checked in by scheusso, 16 years ago

we have a new gamestate concept now: dont transmit synchronisable header of objects, that dont get updated that tick. transmit objectids of deleted objects to delete them on the client too

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