home *** CD-ROM | disk | FTP | other *** search
/ Enter 2005 March / ENTER.ISO / files / fwp-0.0.6-win32-installer.exe / Server.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2005-01-22  |  30.9 KB  |  1,076 lines

  1. #include "Server.h"
  2.  
  3. #include "Network.h"
  4.  
  5.  
  6. #include "PacketHandler.h"
  7. #include "log.h"
  8. #include "Game.h"
  9. #include "random.h"
  10. #include <string.h>
  11.  
  12. Server::Server(){
  13. //    ipAddress = NULL;
  14.     socket = NULL;
  15.  
  16.     si.protocolVersion = NETWORK_PROTOCOL_VERSION;
  17.     si.numClients = 0;
  18.     si.maxClients = Network::info.var.server_maxClients;
  19.     strcpy(si.name, Network::info.var.server_name);
  20.     strcpy(si.description, Network::info.var.server_description);
  21.     strcpy(si.arena, Game::info.var.arena);
  22.     si.gamemode = Game::info.var.mode;
  23.     si.ghostTime = Game::info.var.ghostTime;
  24.  
  25.     si.optionFlags = 0;
  26.     if( Game::info.var.useArenaCycle )
  27.         si.optionFlags |= PACKET_OPTION_FLAG_GAME_USE_ARENA_CYCLE;
  28.     if( Game::info.var.enableFriendlyFire )
  29.         si.optionFlags |= PACKET_OPTION_FLAG_GAME_ENABLE_FRIENDLY_FIRE;
  30.  
  31.     for(int i=0;i<NETWORK_MAX_CLIENTS;i++){
  32.         clients[i] = NULL;
  33.     }
  34.     localClient = NULL;
  35.  
  36.     lastPingMillis = SDL_GetTicks();
  37.     lastPlayerinfoMillis = SDL_GetTicks()+100;    // THINKABOUTME: damit nicht zusammen gesendet wird?
  38.     lastGamestateMillis = SDL_GetTicks();    // THINKABOUTME: damit nicht zusammen gesendet wird?
  39. }
  40.  
  41. Server::~Server(){
  42.     for(int i=0;i<NETWORK_MAX_CLIENTS;i++){
  43.         if(clients[i] != NULL && clients[i] != localClient)
  44.             delete clients[i];
  45.  
  46.  
  47.     }
  48. }
  49.  
  50.  
  51. bool Server::openPort(){
  52.  
  53.     socket = SDLNet_UDP_Open(Network::info.var.server_port);
  54.     if(socket == NULL){
  55.         error("(in Server::openPort()): SDLNet_UDP_Open() failed: %s.\n\n", SDLNet_GetError());
  56.         return false;
  57.     }
  58.  
  59.     if(SDLNet_ResolveHost(&ipAddress, Network::info.var.server_hostName, Network::info.var.server_port) == -1){
  60.         error("(in Server::openPort()): SDLNet_ResolveHost() failed: %s.\n\n", SDLNet_GetError());
  61.         SDLNet_UDP_Close(socket);
  62.         return false;
  63.     }
  64.  
  65. //    ipAddress.host = 0x0100007F;
  66. //    ipAddress.port = Network::info.var.serverPort;
  67. //    printf("server addr: %s:%d\n", SDLNet_ResolveIP(&ipAddress), ipAddress.port);
  68.  
  69.     return true;
  70. }
  71.  
  72. bool Server::closePort(){
  73.     SDLNet_UDP_Close(socket);
  74.  
  75.     return true;
  76. }
  77.  
  78.  
  79. bool Server::disconnectAllClients(const char* reason){
  80. //    IPaddress ip;
  81. //    ip.host = 0;
  82. //    ip.port = 0;
  83.  
  84.     if( localClient != NULL ){    // remove the local client first...
  85.         removeClient(localClient);    // if game::shutdown was called this has been already done!
  86.     }
  87.     
  88.     // ... and send a disconnect packet to all others
  89.     disconnectPacket_t d;
  90.     strcpy(d.reason, reason);
  91.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_DISCONNECT, this->ipAddress, &d, sizeof(d));
  92.     if( p == NULL ){
  93.         error("(in Server::disconnectAllClients()): Couldn't alloc packet.\n\n");
  94.         return false;
  95.  
  96.     }
  97.  
  98.  
  99.     if( !sendToAllClients(p) ){
  100.         return false;
  101.     }
  102.  
  103.     SDLNet_FreePacket(p);
  104.  
  105.     return true;
  106. }
  107.  
  108. bool Server::disconnectClient(Client* client, const char* reason){
  109.  
  110.     if( client == localClient ){
  111.         warn("(in Server::disconnectClient()): Disconnecting local client!\n\n");
  112.     }
  113.     if( clients[client->clientId] == NULL ){
  114.         error("(in Server::disconnectClient()): Client is not connected to this server.\n\n");
  115.         return false;
  116.     }
  117.     
  118.     // ... and send a disconnect packet to all others
  119.     disconnectPacket_t d;
  120.     d.clientId = client->clientId;
  121.     strncpy(d.reason, reason, CON_MAX_STRING_LENGTH);
  122.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_DISCONNECT, client->ipAddress, &d, sizeof(d));
  123.     if( p == NULL ){
  124.         error("(in Server::disconnectClient()): Couldn't alloc packet.\n\n");
  125.         return false;
  126.     }
  127.  
  128.     if( !sendToClient(client, p) ){
  129.         error("(in Server::disconnectClient()): Couldn't send packet.\n\n");
  130.         SDLNet_FreePacket(p);
  131.         return false;
  132.     }
  133.     SDLNet_FreePacket(p);
  134.  
  135.     removeClient(client);
  136.  
  137.     // inform the other clients
  138.     clientDisconnectedPacket_t cd;
  139.     cd.clientId = d.clientId;
  140.     strncpy(cd.reason, reason, CON_MAX_STRING_LENGTH);
  141.     p = PacketHandler::wrapPacket(PACKET_TYPE_CLIENT_DISCONNECTED, this->ipAddress, &cd, sizeof(cd));
  142.     if( !sendToAllOtherRemoteClients(client, p) ){
  143.         error("(in Server::handleDisconnect()): Couldn't send packet.\n\n");
  144.         SDLNet_FreePacket(p);
  145.         return false;
  146.     }
  147.     SDLNet_FreePacket(p);
  148.  
  149.     log("'%s' disconnected (reason: %s).\n", client->ci.name, reason);
  150.  
  151.  
  152.     return true;
  153. }
  154.  
  155.  
  156. int Server::addClient(Client* client){
  157.     for(int i=0;i<si.maxClients;i++){
  158.         if(clients[i] == NULL){
  159.             clients[i] = client;
  160.             si.numClients++;
  161.             return i;
  162.         }
  163.     }
  164.  
  165.     return -1;
  166. }
  167.  
  168. void Server::removeClient(Client* client){
  169.     for(int i=0;i<si.maxClients;i++){
  170.         if(clients[i] == client){
  171. //            removeClientFromAllTeams(client);
  172.             if(clients[i] != localClient){
  173.                 delete clients[i];
  174.             }
  175.             clients[i] = NULL;
  176.             si.numClients--;
  177.         }
  178.     }
  179. }
  180.  
  181. void Server::checkClientName(char* name, char* newName){
  182.     strncpy(newName, name, CLIENT_MAX_NAME_LENGTH);
  183.     int number = 1;
  184.  
  185.     for(int i=0;i<si.maxClients;i++){
  186.         if(clients[i] != NULL && !strcmp(newName, clients[i]->ci.name) ){
  187.             sprintf(newName, "%s (%i)", name, number);
  188.             number++;
  189.             i = 0;
  190.         }
  191.     }
  192. }
  193.  
  194. bool Server::hasFreeSlots(){
  195. //    for(int i=0;i<maxClients;i++){
  196. //        if(clients[i] == NULL)
  197. //            return true;
  198. //    }
  199. //    return false;
  200.     return (si.numClients < si.maxClients);
  201. }
  202.  
  203. Client* Server::getClientByPacket(UDPpacket* packet){
  204.     for(int i=0;i<si.maxClients;i++){
  205.         if(clients[i] != NULL && clients[i]->ipAddress.host == packet->address.host && clients[i]->ipAddress.port == packet->address.port)
  206.             return clients[i];
  207.     }
  208.  
  209.     return NULL;
  210. }
  211.  
  212. Client* Server::getClientByName(const char* name){
  213.     for(int i=0;i<si.maxClients;i++){
  214.         if(clients[i] != NULL && streq(name, clients[i]->ci.name) )
  215.             return clients[i];
  216.     }
  217.  
  218.     return NULL;
  219. }
  220.  
  221. void Server::resetClients(){
  222.     for(int i=0;i<si.maxClients;i++){
  223.         if( clients[i] != NULL ){
  224.             clients[i]->ci.score = 0;
  225.             clients[i]->ci.kills = 0;
  226.             clients[i]->ci.deaths = 0;
  227.             clients[i]->ci.team = GAME_TEAM_SPECTATORS;
  228.             clients[i]->cs.armor = 0;
  229.             clients[i]->cs.energy = 0;
  230.             clients[i]->vehicle = NULL;
  231.  
  232.             clients[i]->lastPingMillis = SDL_GetTicks();
  233.         }
  234.     }
  235. }
  236.  
  237. bool Server::sendToClient(Client* client, UDPpacket* packet){
  238.     packet->address.host = client->ipAddress.host;
  239.     packet->address.port = client->ipAddress.port;
  240.     if( !Network::sendPacket(socket, packet) ){
  241.         error("(in Server::sendToClient()): Couldn't send packet.\n\n");
  242.         return false;
  243.     }
  244.     return true;
  245. }
  246.  
  247. bool Server::sendToAllClients(UDPpacket* packet){
  248.     for(int i=0;i<si.maxClients;i++){
  249.         if(clients[i] != NULL){
  250.             packet->address.host = clients[i]->ipAddress.host;
  251.             packet->address.port = clients[i]->ipAddress.port;
  252.             if( !SDLNet_UDP_Send(socket, -1, packet) ){
  253.                 error("(in Server::sendToAllClients()): SDLNet_UDP_Send() failed: %s.\n\n", SDLNet_GetError());
  254.                 return false;
  255.             }
  256.         }
  257.     }
  258.     return true;
  259. }
  260.  
  261. bool Server::sendToAllRemoteClients(UDPpacket* packet){
  262.     for(int i=0;i<si.maxClients;i++){
  263.         if(clients[i] != NULL && clients[i] != localClient){
  264.             packet->address.host = clients[i]->ipAddress.host;
  265.             packet->address.port = clients[i]->ipAddress.port;
  266.             if( !SDLNet_UDP_Send(socket, -1, packet) ){
  267.                 error("(in Server::sendToAllRemoteClients()): SDLNet_UDP_Send() failed: %s.\n\n", SDLNet_GetError());
  268.                 return false;
  269.             }
  270.         }
  271.     }
  272.     return true;
  273. }
  274.  
  275. bool Server::sendToAllOtherRemoteClients(Client* c, UDPpacket* packet){
  276.     for(int i=0;i<si.maxClients;i++){
  277.         if(clients[i] != NULL && clients[i] != c && clients[i] != localClient){
  278.             packet->address.host = clients[i]->ipAddress.host;
  279.             packet->address.port = clients[i]->ipAddress.port;
  280.             if( !SDLNet_UDP_Send(socket, -1, packet) ){
  281.                 error("(in Server::sendToAllOtherRemoteClients()): SDLNet_UDP_Send() failed: %s.\n\n", SDLNet_GetError());
  282.                 return false;
  283.             }
  284.         }
  285.     }
  286.     return true;
  287. }
  288.  
  289.  
  290.  
  291. void Server::sendGamestate(){
  292.     int i;
  293.     unsigned long currentMillis = SDL_GetTicks();
  294.  
  295.     gamestatePacket_t gs;
  296.  
  297.     for(i=0;i<si.maxClients;i++){
  298.         Client* c = clients[i];
  299.         if(c != NULL){
  300.             if( c->vehicle != NULL ){    // alive -> tja, ?
  301.                 vectorCopy3d(c->vehicle->pos, c->cs.pos);
  302.                 vectorCopy3d(c->vehicle->dir, c->cs.dir);
  303.                 vectorCopy3d(c->vehicle->up, c->cs.up);
  304.                 vectorCopy3d(c->vehicle->vel_inp, c->cs.vel);
  305.                 c->cs.armor = (unsigned char)c->vehicle->armor;
  306.                 c->cs.energy = (unsigned char)c->vehicle->energy;
  307.             }else{ // dead -> nothing?
  308.                 c->cs.armor = 0;
  309.                 c->cs.energy = 0;
  310.             }
  311.  
  312.             gs.clientIds[i] = i;
  313.             gs.cs[i] = c->cs;
  314.         }else{
  315.             gs.clientIds[i] = -1;
  316.         }
  317.     }
  318.  
  319.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_GAMESTATE, this->ipAddress, &gs, sizeof(gs));
  320.     if( !sendToAllRemoteClients(p) ){
  321.         error("(in Server::sendPackets()): Couldn't send gamestate packet.\n\n");
  322.         SDLNet_FreePacket(p);
  323.         return;
  324.     }
  325. /*
  326.     for(i=0;i<si.maxClients;i++){
  327.         if( clients[i] != NULL && clients[i] != localClient && clients[i]->lastSpawnMillis != 0 ){
  328.             p->address.host = clients[i]->ipAddress.host;
  329.             p->address.port = clients[i]->ipAddress.port;
  330.             if( !SDLNet_UDP_Send(socket, -1, p) ){
  331.                 error("(in Server::sendGamestate()): SDLNet_UDP_Send() failed: %s.\n\n", SDLNet_GetError());
  332.                 return;
  333.             }
  334.         }
  335.     }
  336. */
  337.     SDLNet_FreePacket(p);
  338.  
  339.     lastGamestateMillis = currentMillis;
  340. }
  341.  
  342. void Server::sendPlayerinfo(){
  343.     unsigned long currentMillis = SDL_GetTicks();
  344.  
  345.     playerinfoPacket_t pi;
  346.  
  347.     // fill pi
  348.     for(int i=0;i<si.maxClients;i++){
  349.         if(clients[i] != NULL){
  350.             pi.clientIds[i] = i;
  351.  
  352.             clients[i]->ci.secondsOnServer = (short)( (currentMillis - clients[i]->momentOfConnectMillis) / 1000 );
  353.             pi.ci[i] = clients[i]->ci;
  354.         }else{
  355.             pi.clientIds[i] = -1;
  356.         }
  357.     }
  358.  
  359.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_PLAYERINFO, this->ipAddress, &pi, sizeof(pi));
  360.     if( !sendToAllRemoteClients(p) ){
  361.         error("(in Server::sendPackets()): Couldn't send playerinfo packet.\n\n");
  362.         SDLNet_FreePacket(p);
  363.         return;
  364.     }
  365.     SDLNet_FreePacket(p);
  366.  
  367. //        log("Playerinfo send.\n");
  368.     lastPlayerinfoMillis = currentMillis;
  369. }
  370.  
  371. void Server::sendPing(){
  372.     unsigned long currentMillis = SDL_GetTicks();
  373.  
  374.     pingPacket_t pp;
  375.     pp.protocolVersion = Network::info.var.protocolVersion;
  376.  
  377.  
  378.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_PING, this->ipAddress, &pp, sizeof(pp));
  379.     if( !sendToAllClients(p) ){
  380.         error("(in Server::sendPackets()): Couldn't send ping packet.\n\n");
  381.         SDLNet_FreePacket(p);
  382.         return;
  383.     }
  384.     SDLNet_FreePacket(p);
  385.     
  386.     for(int i=0;i<si.maxClients;i++){
  387.         if(clients[i] == NULL || clients[i] == localClient)
  388.             continue;
  389.  
  390.         // not responding -> set ping to server.pingInterval
  391.         if( currentMillis > clients[i]->lastPingMillis + (unsigned long)5000 ){
  392.             clients[i]->ci.ping = (unsigned long)9999;
  393.             if( ((currentMillis - clients[i]->lastPingMillis) / 1000) % 5 == 0 ){
  394.                 log("Connection to '%s' interrupted\n", clients[i]->ci.name);
  395.             }
  396.         }
  397.  
  398.         // not responding for too long -> disconnect
  399.         //printf("client %i t: %i\n", i, currentMillis - clients[i]->lastPingMillis);
  400.         if(currentMillis - clients[i]->lastPingMillis > (unsigned long)Network::info.var.server_maxClientIdleTime){
  401.             disconnectClient(clients[i], "server.maxClientIdleTime reached.");
  402.         }
  403.     }
  404.  
  405.     lastPingMillis = currentMillis;
  406.  
  407. }
  408.  
  409. void Server::sendClientHurt(char hurtClientId, char hurterClientId, unsigned char amount){
  410.     clientHurtPacket_t ch;
  411.  
  412.     if( clients[hurtClientId] == NULL ){
  413.         warn("(in Server::sendClientHurt()): hurtClientId is invalid.\n\n");
  414.         return;
  415.     }
  416.     ch.hurtClientId = hurtClientId;
  417.  
  418.     if( clients[hurterClientId] == NULL ){
  419.         warn("(in Server::sendClientHurt()): hurterClientId is invalid.\n\n");
  420.         // maybe just disconnected
  421.         ch.hurterClientId = -1;
  422.     }else{
  423.         ch.hurterClientId = hurterClientId;
  424.     }
  425.  
  426.     ch.amount = amount;
  427.  
  428.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_CLIENT_HURT, this->ipAddress, &ch, sizeof(ch));
  429.     if( !sendToAllRemoteClients(p) ){
  430.         error("(in Server::sendClientHurt()): Couldn't send packet.\n\n");
  431.         SDLNet_FreePacket(p);
  432.         return;
  433.     }
  434.     SDLNet_FreePacket(p);
  435. }
  436.  
  437.  
  438. void Server::sendClientKill(char killedClientId, char killerClientId, char weapon){
  439.     clientKillPacket_t ck;
  440.  
  441.     ck.killedClientId = killedClientId;
  442.     ck.killerClientId = killerClientId;
  443.     ck.weapon = weapon;
  444.  
  445.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_CLIENT_KILL, this->ipAddress, &ck, sizeof(ck));
  446.     if( !sendToAllRemoteClients(p) ){
  447.         error("(in Server::sendClientKill()): Couldn't send packet.\n\n");
  448.         SDLNet_FreePacket(p);
  449.         return;
  450.     }
  451.     SDLNet_FreePacket(p);
  452. }
  453.  
  454. void Server::sendChatMessage(const char* message){
  455.     chatMessagePacket_t cm;
  456.     cm.clientId = -1;
  457.     strncpy(cm.message, message, CON_MAX_STRING_LENGTH);
  458.     cm.mode = GAME_CHAT_MODE_SERVER;
  459.  
  460.  
  461.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_CHAT_MESSAGE, this->ipAddress, &cm, sizeof(cm));
  462.     if(p == NULL){
  463.         error("(in Server::sendChatMessage()): Couldn't alloc packet.\n\n");
  464.         return;
  465.     }
  466.  
  467.     if( !sendToAllClients(p) ){
  468.         error("(in Server::sendChatMessage()): Couldn't send packet.\n\n");
  469.         SDLNet_FreePacket(p);
  470.         return;
  471.     }
  472.  
  473. }
  474.  
  475. void Server::sendArenaChange(){
  476.     arenaChangePacket_t ac;
  477.     strcpy(ac.newArena, Game::info.var.arena);
  478.  
  479.  
  480.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_ARENA_CHANGE, this->ipAddress, &ac, sizeof(ac));
  481.     if(p == NULL){
  482.         error("(in Server::sendArenaChange()): Couldn't alloc packet.\n\n");
  483.         return;
  484.     }
  485.  
  486.     if( !sendToAllRemoteClients(p) ){
  487.         error("(in Server::sendArenaChange()): Couldn't send packet.\n\n");
  488.         SDLNet_FreePacket(p);
  489.         return;
  490.     }
  491. }
  492.  
  493. void Server::sendPackets(){
  494.     unsigned long currentMillis = SDL_GetTicks();
  495.  
  496.     // do ping stuff
  497.     if(currentMillis - lastPingMillis > (unsigned long)Network::info.var.server_pingInterval){
  498. //        log("Pinging...\n");
  499.         sendPing();
  500.     }
  501.  
  502.     // do playerinfo stuff
  503.     if(currentMillis - lastPlayerinfoMillis > (unsigned long)Network::info.var.server_playerinfoInterval){
  504. //        log("Sending playerinfo...\n");
  505.         sendPlayerinfo();
  506.     }
  507.  
  508.  
  509.  
  510.     // do gamestate stuff
  511.     if(currentMillis - lastGamestateMillis > (unsigned long)Network::info.var.server_gamestateInterval){
  512. //        log("Sending gamestate...\n");
  513.         sendGamestate();
  514.     }
  515.  
  516. }
  517.  
  518. void Server::receivePackets(){
  519.     UDPpacket** packets = SDLNet_AllocPacketV(NETWORK_MAX_PACKETS_PER_FRAME, NETWORK_MAX_PACKET_SIZE);
  520.     if(packets == NULL){
  521.         error("(in Server::receivePackets()): Unable to alloc packets.\n\n");
  522.         return;
  523.     }
  524.  
  525.     int numReceived = SDLNet_UDP_RecvV(socket, packets);
  526.     if(numReceived == -1){
  527.         error("(in Server::receivePackets()): SDLNet_UDP_RecvV failed: %s.\n\n", SDLNet_GetError());
  528.         return;
  529.     }
  530.  
  531.     for(int i=0;i<numReceived;i++){
  532.         if(packets[i]->data[0] != NETWORK_FWP_PACKET_ID){
  533.             warn("(in Server::receivePackets()): Received unknown packet.\n\n");
  534.             continue;
  535.         }
  536.         handlePacket(packets[i]);
  537.     }
  538.  
  539.     SDLNet_FreePacketV(packets);
  540. }
  541.  
  542. void Server::handlePacket(UDPpacket* packet){
  543. //    printf("Server::handlePacket(): received packet of type %i.\n", packet->data[1]);
  544.  
  545.     switch(packet->data[1]){
  546.         case PACKET_TYPE_PING: 
  547. //            log("Server::handlePacket(): Received ping packet.\n");
  548.             handlePing(packet);
  549.             break;
  550.  
  551.         case PACKET_TYPE_SERVERINFO_REQUEST: 
  552. //            log("Server::handlePacket(): Received serverinfo request.\n");
  553.             handleServerinfoRequest(packet);
  554.             break;
  555.  
  556.         case PACKET_TYPE_PLAYERINFO_REQUEST: 
  557. //            log("Server::handlePacket(): Received playerinfo request.\n");
  558. //            handlePlayerinfoRequest(packet);
  559.             break;
  560.  
  561.         case PACKET_TYPE_CONNECTION_REQUEST: 
  562.  
  563. //            log("Server::handlePacket(): Received connection request.\n");
  564.             handleConnectionRequest(packet);
  565.             break;
  566.  
  567.         case PACKET_TYPE_DISCONNECT: 
  568. //            log("Server::handlePacket(): Received disconnect packet.\n");
  569.             handleDisconnect(packet);
  570.             break;
  571.  
  572.         case PACKET_TYPE_CHAT_MESSAGE: 
  573. //            log("Server::handlePacket(): Received chatMessage packet.\n");
  574.             handleChatMessage(packet);
  575.             break;
  576.  
  577.         case PACKET_TYPE_VOICE_MESSAGE: 
  578. //            log("Server::handlePacket(): Received voiceMessage packet.\n");
  579.             handleVoiceMessage(packet);
  580.             break;
  581.  
  582.         case PACKET_TYPE_CLIENTSTATE: 
  583. //            log("Server::handlePacket(): Received clientstate packet.\n");
  584.             handleClientstate(packet);
  585.             break;
  586.  
  587.         case PACKET_TYPE_CLIENT_SPAWN: 
  588. //            log("Server::handlePacket(): Received clientSpawn packet.\n");
  589.             handleClientSpawn(packet);
  590.             break;
  591.  
  592.         case PACKET_TYPE_CLIENT_KILL: 
  593. //            log("Server::handlePacket(): Received clientKill packet.\n");
  594.             handleClientKill(packet);
  595.             break;
  596.  
  597.         case PACKET_TYPE_SHOT_SPAWN: 
  598. //            log("Server::handlePacket(): Received ShotSpawn packet.\n");
  599.             handleShotSpawn(packet);
  600.             break;
  601.  
  602.         default:
  603.             warn("Server::handlePacket(): Received packet of unknown type. Ignoring.\n");
  604.             break;
  605.     }
  606. }
  607.  
  608. void Server::emptyPacketQueue(){
  609.     int numLoops = 0;
  610.     int numReceived = 0;
  611.  
  612.     // receive packets
  613.     do{
  614.         UDPpacket** packets = SDLNet_AllocPacketV(NETWORK_MAX_PACKETS_PER_FRAME, NETWORK_MAX_PACKET_SIZE);
  615.         if(packets == NULL){
  616.             error("(in Server::receivePackets()): Unable to alloc packets.\n\n");
  617.             return;
  618.         }
  619.  
  620.         numReceived = SDLNet_UDP_RecvV(socket, packets);
  621.         if(numReceived == -1){
  622.             error("(in Server::emptyPacketQueue()): SDLNet_UDP_RecvV failed: %s.\n\n", SDLNet_GetError());
  623.             return;
  624.         }
  625.         SDLNet_FreePacketV(packets);
  626.  
  627.         numLoops++;
  628.     }while(numReceived > 0 && numLoops < 10);
  629.  
  630. }
  631.  
  632. void Server::handlePing(UDPpacket* packet){
  633.     pingPacket_t pp;
  634.     if( !PacketHandler::unwrapPacket(packet, &pp, sizeof(pp)) ){
  635.         warn("(in Server::handlePing()): Couldn't unwrap packet. Ignoring.\n\n");
  636.         return;
  637.     }
  638.  
  639.     if( clients[pp.clientId] == NULL ){
  640.         warn("(in Server::handlePing()): Received ping packet from unknown source. Ignoring.\n\n");
  641.         return;
  642.     }
  643.  
  644.     clients[pp.clientId]->lastPingMillis = SDL_GetTicks();
  645.     clients[pp.clientId]->ci.ping = (short)( clients[pp.clientId]->lastPingMillis - this->lastPingMillis );
  646. }
  647.  
  648. void Server::handleServerinfoRequest(UDPpacket* packet){
  649.     serverinfoRequestPacket_t sir;
  650.     serverinfoPacket_t si;
  651.  
  652.     if( !PacketHandler::unwrapPacket(packet, &sir, sizeof(sir)) ){
  653.         warn("(in Server::handleServerinfoRequest()): Couldn't unwrap packet. Ignoring.\n\n");
  654.         return;
  655.     }
  656.  
  657. //    printf("address: %d:%d\n", packet->address.host, packet->address.port);
  658.  
  659.     si = this->si;
  660.  
  661.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_SERVERINFO, packet->address, &si, sizeof(si));
  662.     if( !Network::sendAndFreePacket(socket, p) ){
  663.         error("(in Server::handleServerinfoRequest()): Couldn't send packet.\n\n");
  664.         return;
  665.     }
  666. //    printf("p->len: %i\n", p->len);
  667.     
  668. //    log("Serverinfo send.\n");
  669.  
  670. }
  671.  
  672. void Server::handleConnectionRequest(UDPpacket* packet){
  673.     connectionRequestPacket_t cr;
  674.  
  675.     if( !PacketHandler::unwrapPacket(packet, &cr, sizeof(cr)) ){
  676.         warn("(in Server::handleConnectionRequest()): Couldn't unwrap packet. Ignoring.\n\n");
  677.         return;
  678.     }
  679.  
  680.     if( getClientByPacket(packet) != NULL ){
  681.         warn("(in Server::handleConnectionRequest()): Client already connected. Ignoring request.\n\n");
  682.         return;
  683.     }
  684.  
  685.     if(!hasFreeSlots()){    // server is full
  686.         connectionRequestDeclinedPacket_t cd;
  687.         strcpy(cd.reason, "server is full");
  688.  
  689.         UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_CONNECTION_REQUEST_DECLINED, packet->address, &cd, sizeof(cd));
  690.         if( !Network::sendPacket(socket, p) ){
  691.             error("(in Server::handleConnectionRequest()): Couldn't send packet.\n\n");
  692.             SDLNet_FreePacket(p);
  693.             return;
  694.         }
  695.         SDLNet_FreePacket(p);
  696.  
  697.         log("Declined connection request from '%s' (%s).\n", cr.name, cd.reason);
  698.  
  699.     }else if(cr.protocolVersion != NETWORK_PROTOCOL_VERSION){    // wrong protocol version
  700.         connectionRequestDeclinedPacket_t cd;
  701.         strcpy(cd.reason, "wrong protocol version");
  702.  
  703.         UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_CONNECTION_REQUEST_DECLINED, packet->address, &cd, sizeof(cd));
  704.         if( !Network::sendPacket(socket, p) ){
  705.             error("(in Server::handleConnectionRequest()): Couldn't send packet.\n\n");
  706.             SDLNet_FreePacket(p);
  707.             return;
  708.         }
  709.         SDLNet_FreePacket(p);
  710.  
  711.         log("Declined connection request from '%s' (%s).\n", cr.name, cd.reason);
  712.  
  713.     }else if( Game::info.var.useArenaCycle 
  714.         && SDL_GetTicks() + 60000 > Game::arenaCycle.playingSinceMillis + Game::arenaCycle.arenaCycleElements[Game::arenaCycle.currentArena].durationMillis ){    // arena change is imminent (60s)
  715.         connectionRequestDeclinedPacket_t cd;
  716.         strcpy(cd.reason, "arena change is imminent");
  717.  
  718.         UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_CONNECTION_REQUEST_DECLINED, packet->address, &cd, sizeof(cd));
  719.         if( !Network::sendPacket(socket, p) ){
  720.             error("(in Server::handleConnectionRequest()): Couldn't send packet.\n\n");
  721.             SDLNet_FreePacket(p);
  722.             return;
  723.         }
  724.         SDLNet_FreePacket(p);
  725.  
  726.         log("Declined connection request from '%s' (%s).\n", cr.name, cd.reason);
  727.     }else{        // accept connection
  728.         connectionRequestAcceptedPacket_t ca;
  729.  
  730.         // make new client and fill ca part
  731.         Client* c = new Client();
  732.         c->ipAddress.host = packet->address.host;
  733.         c->ipAddress.port = packet->address.port;
  734.         checkClientName(cr.name, ca.newName);
  735.         c->setName(ca.newName);
  736.         c->clientId = addClient(c);
  737.         ca.clientId = c->clientId;
  738. //        c->team = addClientToTeam(c, GAME_TEAM_SPECTATORS);
  739.  
  740.         // fill pi
  741.         for(int i=0;i<si.maxClients;i++){
  742.             if(clients[i] != NULL){
  743.                 ca.pi.clientIds[i] = i;
  744.                 ca.pi.ci[i] = clients[i]->ci;
  745.             }else{
  746.                 ca.pi.clientIds[i] = -1;
  747.             }
  748.         }
  749.  
  750.         // fill si
  751.         ca.si = this->si;
  752.         UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_CONNECTION_REQUEST_ACCEPTED, packet->address, &ca, sizeof(ca));
  753.         if(!Network::sendPacket(socket, p)){
  754.             error("(in Server::handleConnectionRequest()): Couldn't send packet.\n\n");
  755.             SDLNet_FreePacket(p);
  756.             return;
  757.         }
  758.         SDLNet_FreePacket(p);
  759.  
  760.         log("Accepted connection request from %s.\n", c->ci.name);
  761.  
  762.  
  763.         // inform the other clients!!!
  764.         clientConnectedPacket_t cc;
  765.         cc.clientId = ca.clientId;
  766.         cc.ci = c->ci;
  767.  
  768.         UDPpacket* p2 = PacketHandler::wrapPacket(PACKET_TYPE_CLIENT_CONNECTED, packet->address, &cc, sizeof(cc));
  769.         if( !sendToAllOtherRemoteClients(c, p2) ){
  770.             error("(in Server::handleConnectionRequest()): Couldn't send packet.\n\n");
  771.             SDLNet_FreePacket(p2);
  772.             return;
  773.         }
  774.         SDLNet_FreePacket(p2);
  775.  
  776.         log("'%s' connected.\n", c->ci.name);
  777.     }
  778. }
  779.  
  780. void Server::handleDisconnect(UDPpacket* packet){
  781.     disconnectPacket_t d;
  782.     
  783.     if( !PacketHandler::unwrapPacket(packet, &d, sizeof(d)) ){
  784.         warn("(in Server::handleDisconnect()): Couldn't unwrap packet. Ignoring.\n\n");
  785.         return;
  786.     }
  787.  
  788.  
  789.     Client* c = getClientByPacket(packet);
  790.  
  791.     if(c == NULL || clients[d.clientId] != c){
  792.         warn("(in Server::handleDisconnect()): Received disconnect packet from unknown source. Ignoring.\n\n");
  793.         return;
  794.     }
  795.     
  796.     if( c->vehicle != NULL ){
  797.         Game::unspawnVehicle(c->vehicle);
  798.     }
  799.  
  800.     // inform the other clients
  801.     clientDisconnectedPacket_t cd;
  802.     cd.clientId = d.clientId;
  803.     strcpy(cd.reason, "Client disconnected");
  804.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_CLIENT_DISCONNECTED, packet->address, &cd, sizeof(cd));
  805.     if( !sendToAllOtherRemoteClients(c, p) ){
  806.         error("(in Server::handleDisconnect()): Couldn't send packet.\n\n");
  807.         SDLNet_FreePacket(p);
  808.         return;
  809.     }
  810.     SDLNet_FreePacket(p);
  811.  
  812.     log("'%s' disconnected.\n", c->ci.name);
  813.  
  814.     removeClient(c);
  815. }
  816.  
  817.  
  818. void Server::handleChatMessage(UDPpacket* packet){
  819.     chatMessagePacket_t cm;
  820.  
  821.     if( !PacketHandler::unwrapPacket(packet, &cm, sizeof(cm)) ){
  822.         warn("(in Server::handleChatMessage()): Couldn't unwrap packet. Ignoring.\n\n");
  823.         return;
  824.     }
  825.  
  826.     if( Network::server->clients[cm.clientId] == NULL ){
  827.         warn("(in Server::handleChatMessage()): Received chat message from unknown client. Ignoring.\n\n");
  828.         return;
  829.     }
  830.  
  831.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_CHAT_MESSAGE, packet->address, &cm, sizeof(cm));
  832.     for(int i=0;i<si.maxClients;i++){
  833.         if(clients[i] != NULL){
  834.             if( clients[i]->vehicle == NULL && clients[cm.clientId]->vehicle != NULL 
  835.                 || clients[i]->vehicle != NULL && clients[cm.clientId]->vehicle == NULL ){
  836.                 continue;
  837.             }
  838.             if( cm.mode == GAME_CHAT_MODE_TEAM ){
  839.                 if( clients[i]->ci.team != clients[cm.clientId]->ci.team )
  840.                     continue;
  841.             }
  842.             packet->address.host = clients[i]->ipAddress.host;
  843.             packet->address.port = clients[i]->ipAddress.port;
  844.             if( !SDLNet_UDP_Send(socket, -1, packet) ){
  845.                 warn("(in Server::handleChatMessage()): SDLNet_UDP_Send() failed: %s.\n\n", SDLNet_GetError());
  846.             }
  847.         }
  848.     }
  849.     SDLNet_FreePacket(p);
  850. //    log("Server: Send chatMessage.\n");
  851. }
  852.  
  853. void Server::handleVoiceMessage(UDPpacket* packet){
  854.     voiceMessagePacket_t vm;
  855.  
  856.     if( !PacketHandler::unwrapPacket(packet, &vm, sizeof(vm)) ){
  857.         warn("(in Server::handleVoiceMessage()): Couldn't unwrap packet. Ignoring.\n\n");
  858.         return;
  859.     }
  860.  
  861.     if( Network::server->clients[vm.clientId] == NULL ){
  862.         warn("(in Server::handleVoiceMessage()): Received voice message from unknown client. Ignoring.\n\n");
  863.         return;
  864.     }
  865.  
  866.     if( vm.messageId < 0 || vm.messageId >= GAME_NUM_VOICE_MESSAGES ){
  867.         warn("(in Server::handleVoiceMessage()): MessageId out of bounds.\n\n");
  868.         return;
  869.     }
  870.  
  871.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_VOICE_MESSAGE, packet->address, &vm, sizeof(vm));
  872.     for(int i=0;i<si.maxClients;i++){
  873.         if(clients[i] != NULL){
  874.             if( clients[i]->vehicle == NULL && clients[vm.clientId]->vehicle != NULL 
  875.                 || clients[i]->vehicle != NULL && clients[vm.clientId]->vehicle == NULL ){
  876.                 continue;
  877.             }
  878.             if( vm.mode == GAME_CHAT_MODE_TEAM ){
  879.                 if( clients[i]->ci.team != clients[vm.clientId]->ci.team )
  880.                     continue;
  881.             }
  882.             packet->address.host = clients[i]->ipAddress.host;
  883.             packet->address.port = clients[i]->ipAddress.port;
  884.             if( !SDLNet_UDP_Send(socket, -1, packet) ){
  885.                 warn("(in Server::handleVoiceMessage()): SDLNet_UDP_Send() failed: %s.\n\n", SDLNet_GetError());
  886.             }
  887.         }
  888.     }
  889.     SDLNet_FreePacket(p);
  890.  
  891. }
  892.  
  893.  
  894. void Server::handleClientstate(UDPpacket* packet){
  895. //    log("Received clientstate.\n");
  896.     clientstatePacket_t cs;
  897.  
  898.     if( !PacketHandler::unwrapPacket(packet, &cs, sizeof(cs)) ){
  899.         warn("(in Server::handleClientstate()): Couldn't unwrap packet. Ignoring.\n\n");
  900.         return;
  901.     }
  902.  
  903.     Client* c = getClientByPacket(packet);
  904.     if( c == NULL ){
  905.         warn("(in Server::handleClientstate()): Received clientstate from unknown client. Ignoring.\n\n");
  906.         return;
  907.     }
  908.  
  909.     if( c->vehicle != NULL ){
  910.         vectorCopy3d(cs.pos, c->cs.pos);
  911.         vectorCopy3d(cs.vel, c->cs.vel);
  912.         vectorCopy3d(cs.dir, c->cs.dir);
  913.         vectorCopy3d(cs.up, c->cs.up);
  914.         c->cs.energy = cs.energy;
  915.  
  916.         vectorCopy3d(cs.pos, c->vehicle->pos);
  917.         vectorCopy3d(cs.vel, c->vehicle->vel_inp);
  918.         vectorCopy3d(cs.dir, c->vehicle->dir);
  919.         vectorCopy3d(cs.up, c->vehicle->up);
  920.         c->vehicle->energy = cs.energy;
  921.     }else{
  922.         c->cs = cs;
  923.         c->cs.armor = 0;
  924.         c->cs.energy = 0;
  925.     }
  926. }
  927.  
  928.  
  929. void Server::handleClientSpawn(UDPpacket* packet){
  930. //    log("Received client spawn.\n");
  931.     clientSpawnPacket_t cs;
  932.  
  933.     if( !PacketHandler::unwrapPacket(packet, &cs, sizeof(cs)) ){
  934.         warn("(in Server::handleClientSpawn()): Couldn't unwrap packet. Ignoring.\n\n");
  935.         return;
  936.     }
  937.  
  938.     Client* c = getClientByPacket(packet);
  939.     if( c == NULL ){
  940.         warn("(in Server::handleClientSpawn()): Received spawn request from unknown client. Ignoring.\n\n");
  941.         return;
  942.     }
  943.     if( cs.clientId < 0 || cs.clientId >= si.maxClients || c != clients[cs.clientId] ){
  944.         warn("(in Server::handleClientSpawn()): Received spawn request with invalid clientId. Ignoring.\n\n");
  945.         return;
  946.     }
  947.  
  948.  
  949.     // check values
  950.     int newTeam = 0;
  951.     if( Game::info.var.mode == GAME_MODE_DEATHMATCH /*|| Game::info.var.mode == GAME_MODE_SOLE_SURVIVOR*/ ){
  952.         newTeam = cs.ci.team == 0 ? 0 : 1;    // allow only spectators and players in deathmatch/ss games
  953.     }else{
  954.         if( cs.ci.team == GAME_TEAM_PLAYERS ){ // this means auto-join
  955.             newTeam = frand() < 0.5f ? GAME_TEAM_RED : GAME_TEAM_BLUE;
  956.         }else{
  957.             newTeam = cs.ci.team;
  958.         }
  959.     }
  960.     if( c->ci.team != newTeam || newTeam == GAME_TEAM_SPECTATORS ){    // log change team + reset score etc.
  961.         log("%s joined %s.\n", cs.ci.name, Game::getTeamName(newTeam) );
  962.         c->ci.score = 0;
  963.         c->ci.kills = 0;
  964.         c->ci.deaths = 0;
  965.     }
  966.  
  967.     c->ci.team = newTeam;
  968.     c->ci.vehicle = cs.ci.vehicle;
  969.     c->ci.weapon1 = cs.ci.weapon1;
  970.     c->ci.weapon2 = cs.ci.weapon2;
  971.     c->ci.weapon3 = cs.ci.weapon3;
  972.     c->ci.weapon4 = cs.ci.weapon4;
  973.     
  974.     vectorInit3d(0.0f, 0.0f, 0.0f, c->cs.pos);
  975.     Game::findSpawnpointForClient(c);
  976.  
  977.     if( c == localClient ){
  978.         // UPDATE GAME CVARS!!!!
  979.         Game::info.var.player_team = c->ci.team;
  980.         Game::info.cvar.game_player_team->setVal(c->ci.team);    // THINKABOUTME: to avoid respawns caused by changing teams
  981.         Game::info.var.player_vehicle = c->ci.vehicle;
  982.         Game::info.var.player_weapon1 = c->ci.weapon1;
  983.         Game::info.var.player_weapon2 = c->ci.weapon2;
  984.         Game::info.var.player_weapon3 = c->ci.weapon3;
  985.         Game::info.var.player_weapon4 = c->ci.weapon4;
  986.     }
  987.  
  988.     if( c->vehicle != NULL ){
  989.         Game::unspawnVehicle(c->vehicle);
  990.     }
  991.     Game::spawnVehicle(c);
  992.  
  993.     if( c->ci.team != GAME_TEAM_SPECTATORS ){    // update cs and vehicle armor / energy
  994.         c->vehicle->armor = c->cs.armor = c->vehicle->maxArmor;
  995.         c->vehicle->energy = c->cs.energy = c->vehicle->maxEnergy;
  996. //        log("%s has spawned for %s with a %s.\n", c->ci.name, Game::getTeamName(c->ci.team), Game::getVehicleName(c->ci.vehicle) );
  997.     }else{
  998.         c->cs.armor = 0;
  999.         c->cs.energy = 0;
  1000.     }
  1001.  
  1002.     // copy to packet
  1003.     cs.ci = c->ci;
  1004.     cs.cs = c->cs;
  1005.  
  1006.     // send the packet to all remote clients
  1007.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_CLIENT_SPAWN, this->ipAddress, &cs, sizeof(cs));
  1008.     if( !sendToAllRemoteClients(p) ){
  1009.         error("(in Server::handleClientSpawn()): Couldn't send packet.\n\n");
  1010.         SDLNet_FreePacket(p);
  1011.         return;
  1012.     }
  1013.     SDLNet_FreePacket(p);
  1014.  
  1015. }
  1016.  
  1017. void Server::handleClientKill(UDPpacket* packet){
  1018.     clientKillPacket_t ck;
  1019.  
  1020.     if( !PacketHandler::unwrapPacket(packet, &ck, sizeof(ck)) ){
  1021.         warn("(in Server::handleClientKill()): Couldn't unwrap packet. Ignoring.\n\n");
  1022.         return;
  1023.     }
  1024.  
  1025.     Client* killedClient = clients[ck.killedClientId];
  1026.     Client* killerClient = clients[ck.killerClientId];
  1027.     if( killedClient == NULL ){
  1028.         warn("(in Server::handleClientKill()): Received client kill packet with invalid killedClientId. Ignoring.\n\n");
  1029.         return;
  1030.     }
  1031.     if( killerClient == NULL ){    // May have disconnected
  1032.         warn("(in Server::handleClientKill()): Received client kill packet with invalid killerClientId.\n\n");
  1033. //        return;
  1034.     }
  1035.  
  1036.     if( ck.weapon == -1 ){    //
  1037.         warn("(in Server::handleClientKill()): Received AdminKill-Request from remote Client. Ignoring\n\n");
  1038.         return;
  1039.     }
  1040.  
  1041.     // tell the others
  1042.     sendClientKill(ck.killedClientId, ck.killerClientId, ck.weapon);
  1043.  
  1044.     Game::killClient(killedClient, killerClient, ck.weapon);
  1045.  
  1046. }
  1047.  
  1048. void Server::handleShotSpawn(UDPpacket* packet){
  1049.     shotSpawnPacket_t ss;
  1050.  
  1051.     if( !PacketHandler::unwrapPacket(packet, &ss, sizeof(ss)) ){
  1052.         warn("(in Server::handleShotSpawn()): Couldn't unwrap packet. Ignoring.\n\n");
  1053.         return;
  1054.     }
  1055.  
  1056.     if( clients[ss.clientId] == NULL ){
  1057.         warn("(in Server::handleShotSpawn()): Received ShotSpawnPacket from unknown client. Ignoring.\n\n");
  1058.         return;
  1059.     }
  1060.  
  1061.     if( clients[ss.clientId]->vehicle == NULL ){
  1062.         warn("(in Server::handleShotSpawn()): Received ShotSpawnPacket from dead client. Ignoring.\n\n");
  1063.         return;
  1064.     }
  1065.  
  1066.     Game::spawnShot(&ss);
  1067.  
  1068.     UDPpacket* p = PacketHandler::wrapPacket(PACKET_TYPE_SHOT_SPAWN, packet->address, &ss, sizeof(ss));
  1069.     if( !sendToAllRemoteClients(p) ){
  1070.         warn("(in Server::handleShotSpawn()): Couldn't send packet.\n\n");
  1071.         SDLNet_FreePacket(p);
  1072.         return;
  1073.     }
  1074.  
  1075. }
  1076.