Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

some missing files

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