Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Changeset 9656 in orxonox.OLD for trunk/src


Ignore:
Timestamp:
Aug 4, 2006, 11:01:28 PM (18 years ago)
Author:
bensch
Message:

orxonox/trunk: merged the proxy bache back with no conflicts

Location:
trunk/src
Files:
97 edited
6 copied

Legend:

Unmodified
Added
Removed
  • trunk/src/defs/class_id.h

    r9406 r9656  
    234234  CL_GROUND_TURRET              =    0x000003e5,
    235235  CL_SPACE_TURRET               =    0x000003e6,
    236   CL_GUIDED_MISSILE             =    0x000003e7,
    237   CL_HYPERBLAST                 =    0x000003e8,
    238   CL_BOOMERANG_PROJECTILE       =    0x00000309,
     236  CL_NETWORK_TURRET             =    0x000003e7,
     237  CL_GUIDED_MISSILE             =    0x000003e8,
     238  CL_HYPERBLAST                 =    0x000003e9,
     239  CL_BOOMERANG_PROJECTILE       =    0x0000030a,
    239240
    240241  // NPC's
     
    424425  CL_SIMPLE_SYNC                =    0x00000d0a,
    425426  CL_NETWORK_MONITOR            =    0x00000d0b,
     427  CL_PROXY_CONTROL              =    0x00000d0c,
    426428
    427429
  • trunk/src/lib/BuildLibs.am

    r8368 r9656  
    33                $(LIB_PREFIX)/util/libORXlibutil.a \
    44                $(LIB_PREFIX)/shell/libORXshell.a \
     5                $(LIB_PREFIX)/event/libORXevent.a \
    56                $(LIB_PREFIX)/gui/qt/libORXqtgui.a \
    67                $(LIB_PREFIX)/gui/gl/libORXglgui.a \
     
    1112                $(LIB_PREFIX)/graphics/importer/libtc.a \
    1213                $(LIB_PREFIX)/sound/libORXsound.a \
    13                 $(LIB_PREFIX)/event/libORXevent.a \
    1414                $(LIB_PREFIX)/particles/libORXparticles.a \
    1515                $(LIB_PREFIX)/collision_detection/libORXcd.a \
     
    2222                $(LIB_PREFIX)/parser/ini_parser/libIniParser.a \
    2323                $(LIB_PREFIX)/physics/libORXphysics.a \
     24                $(LIB_PREFIX)/gui/gl/libORXglgui.a \
    2425                $(LIB_PREFIX)/shell/libORXshell.a \
    2526                $(LIB_PREFIX)/math/libORXmath.a \
  • trunk/src/lib/coord/p_node.cc

    r9406 r9656  
    5454    parent->addChild(this);
    5555
    56   this->relCoordinate_handle = this->registerVarId( new SynchronizeableVector( &relCoordinate, &relCoordinate_write, "coordinate" ) );
    57   this->relDirection_handle = this->registerVarId( new SynchronizeableQuaternion( &relDirection, &relDirection_write, "direction" ) );
     56  this->relCoordinate_handle = this->registerVarId( new SynchronizeableVector( &relCoordinate, &relCoordinate_write, "coordinate", PERMISSION_SERVER ) );
     57  this->relDirection_handle = this->registerVarId( new SynchronizeableQuaternion( &relDirection, &relDirection_write, "direction", PERMISSION_SERVER ) );
    5858}
    5959
     
    487487void PNode::addChild (PNode* child)
    488488{
     489  if (unlikely(child->parent == this))
     490    return;
    489491  if( likely(child->parent != NULL))
    490492    child->parent->eraseChild(child);
     
    749751{
    750752  const PNode* parent = this;
     753  if (this == NULL)
     754    return true;
    751755  while ( (parent = parent->getParent()) != NULL)
    752756    if (unlikely(parent == checkParent))
  • trunk/src/lib/event/event_handler.cc

    r9406 r9656  
    2525#include "compiler.h"
    2626#include "debug.h"
    27 #include "class_list.h"
    2827
    2928#include <algorithm>
  • trunk/src/lib/gui/gl/Makefile.am

    r9406 r9656  
    1313                \
    1414                glgui_handler.cc \
     15                glgui_widget.cc \
    1516                glgui_mainwidget.cc \
    16                 glgui_widget.cc \
    1717                glgui_button.cc \
    1818                glgui_pushbutton.cc \
     
    2222                glgui_bar.cc \
    2323                glgui_box.cc \
     24                glgui_fixedposition_box.cc \
    2425                glgui_frame.cc \
    2526                glgui_text.cc \
     
    4041                glgui_defs.h \
    4142                glgui_handler.h \
     43                glgui_widget.h \
    4244                glgui_mainwidget.h \
    43                 glgui_widget.h \
    4445                glgui_button.h \
    4546                glgui_pushbutton.h \
     
    4950                glgui_bar.h \
    5051                glgui_box.h \
     52                glgui_fixedposition_box.h \
    5153                glgui_frame.h \
    5254                glgui_text.h \
  • trunk/src/lib/gui/gl/glgui.h

    r9015 r9656  
    1414#include "glgui_bar.h"
    1515#include "glgui_box.h"
     16#include "glgui_fixedposition_box.h"
    1617#include "glgui_button.h"
    1718#include "glgui_checkbutton.h"
  • trunk/src/lib/gui/gl/glgui_box.cc

    r9110 r9656  
    1818#include "glgui_box.h"
    1919#include <cassert>
     20#include "debug.h"
    2021
    2122namespace OrxGui
     
    3637  */
    3738  GLGuiBox::~GLGuiBox()
    38   {}
     39  {
     40    // unpack all the widgets.
     41    while(!this->_children.empty())
     42    {
     43      /// not deleting children here.
     44      this->_children.front()->setParentWidget(NULL);
     45      this->_children.pop_front();
     46    }
     47  }
    3948
    4049  /**
     
    4958  {
    5059    assert (widget != NULL);
    51 
    52     this->children.push_back(widget);
     60    this->_children.push_back(widget);
     61
     62    this->packing(widget);
     63  }
     64
     65
     66  void GLGuiBox::pack(GLGuiWidget* widget, std::list<GLGuiWidget*>::iterator pos)
     67  {
     68    this->_children.insert(pos, widget);
     69    this->packing(widget);
     70  }
     71
     72  void GLGuiBox::pack(GLGuiWidget* widget, unsigned int position)
     73  {
     74    if (this->_children.empty())
     75      this->pack(widget);
     76
     77    unsigned int pos = 0;
     78    std::list<GLGuiWidget*>::iterator it = this->_children.begin();
     79
     80    for (; pos < position; ++pos)
     81    {
     82      if (this->_children.end() == ++it)
     83      {
     84        PRINTF(2)("Reached end of packing list, without getting to the designated position %d (i am at %d)\n", position, pos);
     85        this->pack(widget);
     86      }
     87    }
     88    this->_children.insert(it, widget);
     89    this->packing(widget);
     90  }
     91
     92  void GLGuiBox::pack(GLGuiWidget* widget, const GLGuiWidget* widgetPointer)
     93  {
     94    assert (widget != NULL && widgetPointer != NULL);
     95
     96    std::list<GLGuiWidget*>::iterator it = this->_children.begin();
     97    for (; it != this->_children.end(); ++it)
     98    {
     99      if (widgetPointer == *it)
     100      {
     101        this->_children.insert(it, widget);
     102        this->packing(widget);
     103        return;
     104      }
     105    }
     106    PRINTF(2)("WidgetPointer %p not found, inserting at the end\n", widgetPointer);
     107    this->pack(widget);
     108  }
     109
     110  void GLGuiBox::packFront(GLGuiWidget* widget)
     111  {
     112    this->_children.push_front(widget);
     113    this->packing(widget);
     114  }
     115
     116  void GLGuiBox::packBack(GLGuiWidget* widget)
     117  {
     118    this->pack(widget);
     119  }
     120
     121  void GLGuiBox::packing(GLGuiWidget* widget)
     122  {
    53123    widget->setParentWidget(this);
    54 
    55124    this->resize();
    56125  }
    57126
    58 
    59127  void GLGuiBox::unpack(GLGuiWidget* widget)
    60128  {
    61129    assert(widget != NULL);
    62130
    63     std::vector<GLGuiWidget*>::iterator delWidget = std::find(this->children.begin(), this->children.end(), widget);
    64     if (delWidget != this->children.end())
     131    std::list<GLGuiWidget*>::iterator delWidget = std::find(this->_children.begin(), this->_children.end(), widget);
     132    if (delWidget != this->_children.end())
    65133    {
    66134      (*delWidget)->setParentWidget(NULL);
    67       this->children.erase(delWidget);
     135      this->_children.erase(delWidget);
    68136    }
    69137    this->resize();
     
    72140  void GLGuiBox::clear()
    73141  {
    74     this->children.clear();
     142    this->_children.clear();
    75143    this->resize();
    76144  }
     
    78146  void GLGuiBox::showAll()
    79147  {
    80     std::vector<GLGuiWidget*>::iterator itC = this->children.begin();
    81     while (itC != this->children.end())
     148    std::list<GLGuiWidget*>::iterator itC = this->_children.begin();
     149    while (itC != this->_children.end())
    82150    {
    83151      if ((*itC)->isA(CL_GLGUI_CONTAINER))
     
    93161  void GLGuiBox::hideAll()
    94162  {
    95     std::vector<GLGuiWidget*>::iterator itC = this->children.begin();
    96     while (itC != this->children.end())
     163    std::list<GLGuiWidget*>::iterator itC = this->_children.begin();
     164    while (itC != this->_children.end())
    97165    {
    98166      if ((*itC)->isA(CL_GLGUI_CONTAINER))
     
    112180      float height = borderTop();
    113181      float width = 0.0f;
    114       std::vector<GLGuiWidget*>::iterator widget;
     182      std::list<GLGuiWidget*>::iterator widget;
    115183
    116184      // find out how big the Widgets are.
    117       for (widget = this->children.begin(); widget != this->children.end(); ++widget)
     185      for (widget = this->_children.begin(); widget != this->_children.end(); ++widget)
    118186      {
    119187        (*widget)->setRelCoor2D(borderLeft(), height);
     
    131199      float height = borderTop();
    132200      float width = borderLeft();
    133       std::vector<GLGuiWidget*>::iterator widget;
     201      std::list<GLGuiWidget*>::iterator widget;
    134202
    135203      // find out how big the Widgets are.
    136       for (widget = this->children.begin(); widget != this->children.end(); ++widget)
     204      for (widget = this->_children.begin(); widget != this->_children.end(); ++widget)
    137205      {
    138206        (*widget)->setRelCoor2D(width, borderTop());
     
    149217
    150218    // resize everything.
    151     //for (widget = this->children.begin(); widget != this->children.end(); ++widget)
     219    //for (widget = this->_children.begin(); widget != this->_children.end(); ++widget)
    152220    //{}
    153221  }
  • trunk/src/lib/gui/gl/glgui_box.h

    r8145 r9656  
    11/*!
    2  * @file glgui_.h
     2 * @file glgui_box.h
    33 * The gl_box widget of th openglGUI
    44 *
     
    3030
    3131    virtual void pack(GLGuiWidget* widget);
     32    void pack(GLGuiWidget* widget, unsigned int position);
     33    void pack(GLGuiWidget* widget, const GLGuiWidget* widgetPointer);
     34    void packFront(GLGuiWidget* widget);
     35    void packBack(GLGuiWidget* widget);
    3236    virtual void unpack(GLGuiWidget* widget);
     37
    3338    virtual void clear();
    3439
     
    4348  private:
    4449    void init();
     50    void packing(GLGuiWidget* widget); // the action executing when packing a widget.
     51    void pack(GLGuiWidget* widget, std::list<GLGuiWidget*>::iterator pos);
     52
     53  private:
     54
    4555
    4656    Orientation                _orientation;
    47     std::vector<GLGuiWidget*>  children;
     57    std::list<GLGuiWidget*>    _children;
    4858  };
    4959}
  • trunk/src/lib/gui/gl/glgui_container.cc

    r8619 r9656  
    4848
    4949
     50  void GLGuiContainer::removeChildWidget(GLGuiWidget* widget)
     51  {
     52    this->unpack(widget);
     53  }
     54
     55
    5056  /**
    5157   * draws the GLGuiContainer
  • trunk/src/lib/gui/gl/glgui_container.h

    r8145 r9656  
    3838    virtual void draw();
    3939
     40  protected:
     41    virtual void removeChildWidget(GLGuiWidget* widget);
     42
    4043  private:
    4144    void init();
  • trunk/src/lib/gui/gl/glgui_defs.h

    r8619 r9656  
    2323
    2424  //! Names of Orientations
    25   const std::string OrientationString[] = {
    26     "Horizontal",
    27     "Vertical"
    28   };
     25  const std::string OrientationString[] =
     26    {
     27      "Horizontal",
     28      "Vertical"
     29    };
     30
     31  //! An enumeration for the Positions of some Elements (FixedPositionBox as an example).
     32  typedef enum {
     33    Left,               //!< Left
     34    Right,              //!< Right
     35    Top,                //!< Top
     36    Bottom,             //!< Bottom
     37    TopLeft,            //!< TopLeft
     38    TopRight,           //!< TopRight
     39    BottomLeft,         //!< BottomLeft
     40    BottomRight,        //!< BottomRight
     41    Center,             //!< Centered
     42  } Position;
     43
     44  //! Names of Positions
     45  const std::string PositionString[] =
     46    {
     47      "Left",
     48      "Right",
     49      "Top",
     50      "Bottom",
     51      "TopLeft",
     52      "TopRight",
     53      "BottomLeft",
     54      "BottomRight",
     55      "Center"
     56    };
     57
    2958
    3059  //! An enumerator that defines the different states Widgets may be in.
     
    3968#define GLGUI_DEFAULT_STYLE OrxGui::Normal
    4069
    41 //! names of the States.
     70  //! names of the States.
    4271  const std::string StateString[] =
    4372    {
     
    4877    };
    4978
    50     //! Where a Certain feature will be positioned at.
    51     typedef enum {
    52       FeatureLeft,          //!< On the Left side.
    53       FeatureRight,         //!< On the Right side.
    54       FeatureTop,           //!< On Top of the rest of the Widget.
    55       FeatureBottom,        //!< At the Bottom of the rest of the Widget.
    56     } FeaturePosition;
     79  //! Where a Certain feature will be positioned at.
     80  typedef enum {
     81    FeatureLeft,          //!< On the Left side.
     82    FeatureRight,         //!< On the Right side.
     83    FeatureTop,           //!< On Top of the rest of the Widget.
     84    FeatureBottom,        //!< At the Bottom of the rest of the Widget.
     85  } FeaturePosition;
    5786
    58     //! Names of Feature-Positions
    59     const std::string FeaturePositionString[] =
     87  //! Names of Feature-Positions
     88  const std::string FeaturePositionString[] =
    6089    {
    6190      "Left",
  • trunk/src/lib/gui/gl/glgui_handler.cc

    r9240 r9656  
    2828#include "debug.h"
    2929
    30 #include <cassert>
    31 
    3230
    3331/// TAKE THIS OUT OF HERE.
     
    4644    this->setName("GLGuiHandler");
    4745
     46    this->_resolution = Vector2D(GraphicsEngine::getInstance()->getResolutionX(), GraphicsEngine::getInstance()->getResolutionY());
    4847
    4948    EventHandler::getInstance()->withUNICODE(ES_MENU, true );
     
    5251    for (unsigned int i = 0; i < EV_NUMBER; i++)
    5352    {
    54       this->subscribeEvent(ES_ALL, i);
     53      this->subscribeEvent(ES_GAME, i);
     54      this->subscribeEvent(ES_GAME_MENU, i);
     55      this->subscribeEvent(ES_MENU, i);
    5556    }
    5657  }
     
    8889      this->_cursor = NULL;
    8990    }
     91  }
     92
     93  const Vector2D& GLGuiHandler::resolution()
     94  {
     95    if (this->_resolution == Vector2D::nullVector())
     96      this->_resolution = Vector2D(GraphicsEngine::getInstance()->getResolutionX(), GraphicsEngine::getInstance()->getResolutionY());
     97    return _resolution;
    9098  }
    9199
     
    244252        if (this->_cursor != NULL)
    245253          this->_cursor->setMaxBorders(Vector2D(event.resize.w, event.resize.h));
    246         break;
     254        this->_resolution = Vector2D(event.resize.w, event.resize.h);
     255        break;
     256
    247257      case SDLK_TAB:
    248258        if (event.bPressed)
  • trunk/src/lib/gui/gl/glgui_handler.h

    r9240 r9656  
    1212namespace OrxGui
    1313{
    14 
     14 // FORWARD DECLARATION
    1515  class GLGuiCursor;
    1616
    17   // FORWARD DECLARATION
    1817
    1918  //! A singleton class for the GLGui-Handler
     
    2221
    2322  public:
    24     virtual ~GLGuiHandler(void);
    2523    /** @returns a Pointer to the only object of this Class */
    2624    inline static GLGuiHandler* getInstance(void) { if (!GLGuiHandler::singletonRef) GLGuiHandler::singletonRef = new GLGuiHandler();  return GLGuiHandler::singletonRef; };
     25    /** @brief deletes the instance if it exists */
     26    inline static void deleteInstance() { if (GLGuiHandler::singletonRef) delete GLGuiHandler::singletonRef; };
    2727
    2828    void activateCursor();
     
    3333    const Vector2D& cursorPositionAbs() const;
    3434    Vector2D cursorPositionRel(const GLGuiWidget* const widget) const;
     35
     36    const Vector2D& resolution();
    3537
    3638    void selectNext();
     
    4850  private:
    4951    GLGuiHandler(void);
     52    virtual ~GLGuiHandler(void);
    5053    static GLGuiHandler* singletonRef;
    5154
     
    5356    bool                 isActive;
    5457    GLGuiCursor*         _cursor;
     58    Vector2D             _resolution;
    5559
    5660  };
  • trunk/src/lib/gui/gl/glgui_text.cc

    r9406 r9656  
    101101  {
    102102    this->_text.clear();
    103     this->changedText();
     103    this->resize();
    104104  }
     105
    105106
    106107  /**
     
    114115    this->setFrontColor(_changedTextColor, true);
    115116    this->textChanged.emit(this->_text.text());
     117  }
     118
     119  void GLGuiText::setTextSize(float size)
     120  {
     121    this->_text.setSize(size);
     122    this->changedText();
     123  }
     124
     125  void GLGuiText::setFont(const Font& font)
     126  {
     127    GLGuiWidget::setFont(font);
     128    this->_text.setFont(font);
    116129  }
    117130
  • trunk/src/lib/gui/gl/glgui_text.h

    r9406 r9656  
    3131    void clear();
    3232
     33    void setTextSize(float size);
     34    virtual void setFont(const Font& font);
    3335    void setChangedTextColor(const Color& color);
    3436
  • trunk/src/lib/gui/gl/glgui_widget.cc

    r9406 r9656  
    7979    if (this == GLGuiWidget::selected())
    8080      this->unselect();
     81
     82    if (this->_parent != NULL)
     83      this->_parent->removeChildWidget(this);
    8184  }
    8285
     
    8487  GLGuiWidget* GLGuiWidget::_mouseFocused = NULL;
    8588  GLGuiWidget* GLGuiWidget::_inputGrabber = NULL;
    86 
     89  Font* GLGuiWidget::_defaultFont = NULL;
    8790
    8891
     
    100103    this->_state = OrxGui::Normal;
    101104
    102 
    103     this->_font = Font(ResourceManager::getInstance()->getDataDir() + "/fonts/final_frontier.ttf", 20);
     105    if(GLGuiWidget::_defaultFont == NULL)
     106      GLGuiWidget::_defaultFont = new Font(ResourceManager::getInstance()->getDataDir() + "/fonts/final_frontier.ttf", 20);
     107
     108    this->_font = *GLGuiWidget::_defaultFont;
    104109    this->resetStyle();
    105110
     
    776781  void GLGuiWidget::setFont(const std::string& fontName, unsigned int renderSize)
    777782  {
    778     this->_font = Font(fontName, renderSize);
     783    this->setFont(Font(fontName, renderSize));
    779784  }
    780785
  • trunk/src/lib/gui/gl/glgui_widget.h

    r9406 r9656  
    206206    void setFeaturePositionS(const std::string& featurePosition);
    207207
    208     void setFont(const Font& font);
    209     void setFont(const std::string& fontName, unsigned int renderSize);
     208    virtual void setFont(const Font& font);
     209    void setFont(const std::string& fontName, unsigned int renderSize = FONT_DEFAULT_RENDER_SIZE);
    210210
    211211    void setAnimatedStateChanges(bool animated);
     
    270270    virtual void destroying();
    271271
     272    // unparent the widget and from this widget seen as parent
     273    virtual void removeChildWidget(GLGuiWidget* widget) {};
     274
    272275
    273276    virtual void debug(unsigned int level) const;
     
    323326    Font                           _font;                 //!< The Font used in the current Widget.
    324327
     328    static Font*                   _defaultFont;          //!< The default Font.
    325329
    326330    /// ANIMATION STUFF:
  • trunk/src/lib/math/quaternion.cc

    r9110 r9656  
    336336  // check the diagonal
    337337  float tr = mat[0][0] + mat[1][1] + mat[2][2];
    338   if( tr > 0.0f) {
     338  if( tr > 0.0f)
     339  {
    339340    float s = (float)sqrtf(tr + 1.0f);
    340341    this->w = s * 0.5f;
     
    372373}
    373374
     375Quaternion Quaternion::lookAt(Vector from, Vector to, Vector up)
     376{
     377  Vector n = to - from;
     378  n.normalize();
     379  Vector v = n.cross(up);
     380  v.normalize();
     381  Vector u = v.cross(n);
     382
     383  float matrix[3][3];
     384  matrix[0][0] = v.x;
     385  matrix[0][1] = v.y;
     386  matrix[0][2] = v.z;
     387  matrix[1][0] = u.x;
     388  matrix[1][1] = u.y;
     389  matrix[1][2] = u.z;
     390  matrix[2][0] = -n.x;
     391  matrix[2][1] = -n.y;
     392  matrix[2][2] = -n.z;
     393
     394  Quaternion quat;
     395  quat.from3x3(matrix);
     396  return quat;
     397}
     398
     399
    374400/**
    375401 * @brief outputs some nice formated debug information about this quaternion
  • trunk/src/lib/math/quaternion.h

    r9110 r9656  
    3333class Quaternion
    3434{
    35  public:
    36   /** creates a Default quaternion (multiplicational identity Quaternion)*/
    37   inline Quaternion () { w = 1; v = Vector(0,0,0); }
    38   /** Copy constructor @param q the Quaternion to copy. */
    39   inline Quaternion (const Quaternion& q) { w = q.w; v = q.v; };
    40   /** creates a Quaternion looking into the direction v @param v: the direction @param f: the value */
    41   inline Quaternion (const Vector& v, float f) { this->w = f; this->v = v; }
    42   /** turns a rotation along an axis into a Quaternion @param angle: the amount of radians to rotate @param axis: the axis to rotate around */
    43   inline Quaternion (float angle, const Vector& axis) { w = cos(angle/2.0); v = axis * sin(angle/2.0); }
    44   Quaternion (const Vector& dir, const Vector& up);
    45   Quaternion (float roll, float pitch, float yaw);
     35  public:
     36    /** creates a Default quaternion (multiplicational identity Quaternion)*/
     37    inline Quaternion () { w = 1; v = Vector(0,0,0); }
     38    /** Copy constructor @param q the Quaternion to copy. */
     39    inline Quaternion (const Quaternion& q) { w = q.w; v = q.v; };
     40    /** creates a Quaternion looking into the direction v @param v: the direction @param f: the value */
     41    inline Quaternion (const Vector& v, float f) { this->w = f; this->v = v; }
     42    /** turns a rotation along an axis into a Quaternion @param angle: the amount of radians to rotate @param axis: the axis to rotate around */
     43    inline Quaternion (float angle, const Vector& axis) { w = cos(angle/2.0); v = axis * sin(angle/2.0); }
     44    Quaternion (const Vector& dir, const Vector& up);
     45    Quaternion (float roll, float pitch, float yaw);
    4646
    47   void from3x3(float m[3][3]);
    48   void from4x4(float m[4][4]);
     47    void from3x3(float m[3][3]);
     48    void from4x4(float m[4][4]);
    4949
    5050
    51   /** @param q: the Quaternion to compare with this one. @returns true if the Quaternions are the same, false otherwise */
     51    /** @param q: the Quaternion to compare with this one. @returns true if the Quaternions are the same, false otherwise */
    5252  inline bool operator== (const Quaternion& q) const { return (unlikely(this->v==q.v&&this->w==q.w))?true:false; };
    53   /** @param q: the Quaternion to compare with this one. @returns true if the Quaternions are the same, false otherwise */
     53    /** @param q: the Quaternion to compare with this one. @returns true if the Quaternions are the same, false otherwise */
    5454  inline bool operator!= (const Quaternion& q) const { return (unlikely(this->v!=q.v||this->w!=q.w))?true:false; };
    55   /** @param f: a real value @return a Quaternion containing the quotient */
    56   inline Quaternion operator/ (const float& f) const { return (unlikely(f==0.0)) ? Quaternion() : Quaternion(this->v/f, this->w/f); };
    57   /** @param f: the value to divide by @returns the quaternion devided by f (this /= f) */
    58   inline const Quaternion& operator/= (const float& f) {*this = *this / f; return *this;}
    59   /** @param f: a real value @return a Quaternion containing the product */
    60   inline Quaternion operator* (const float& f) const { return Quaternion(this->v*f, this->w*f); };
    61   /** @param f: the value to multiply by @returns the quaternion multiplied by f (this *= f) */
    62   inline const Quaternion& operator*= (const float& f) {*this = *this * f; return *this;}
    63   /** @param q: another Quaternion to rotate this by @return a quaternion that represents the first one rotated by the second one (WARUNING: this operation is not commutative! e.g. (A*B) != (B*A)) */
    64   Quaternion operator* (const Quaternion& q) const { return Quaternion(Vector(this->w*q.v.x + this->v.x*q.w + this->v.y*q.v.z - this->v.z*q.v.y,
    65                                                                          this->w*q.v.y + this->v.y*q.w + this->v.z*q.v.x - this->v.x*q.v.z,
    66                                                                          this->w*q.v.z + this->v.z*q.w + this->v.x*q.v.y - this->v.y*q.v.x),
    67                                                                          this->w*q.w - this->v.x*q.v.x - this->v.y*q.v.y - this->v.z*q.v.z); };
    68   /** @param q: the Quaternion to multiply by @returns the quaternion multiplied by q (this *= q) */
    69   inline const Quaternion& operator*= (const Quaternion& q) {*this = *this * q; return *this; };
    70   /** @param q the Quaternion by which to devide @returns the division from this by q (this / q) */
    71   inline Quaternion operator/ (const Quaternion& q) const { return *this * q.inverse(); };
    72   /** @param q the Quaternion by which to devide @returns the division from this by q (this /= q) */
    73   inline const Quaternion& operator/= (const Quaternion& q) { *this = *this * q.inverse(); return *this; };
    74   /** @param q the Quaternion to add to this @returns the quaternion added with q (this + q) */
    75   inline Quaternion operator+ (const Quaternion& q) const { return Quaternion(q.v + v, q.w + w); };
    76   /** @param q the Quaternion to add to this @returns the quaternion added with q (this += q) */
    77   inline const Quaternion& operator+= (const Quaternion& q) { this->v += q.v; this->w += q.w; return *this; };
    78   /** @param q the Quaternion to substrace from this @returns the quaternion substracted by q (this - q) */
    79   inline Quaternion operator- (const Quaternion& q) const { return Quaternion(q.v - v, q.w - w); }
    80   /** @param q the Quaternion to substrace from this @returns the quaternion substracted by q (this -= q) */
    81   inline const Quaternion& operator-= (const Quaternion& q) { this->v -= q.v; this->w -= q.w; return *this; };
    82   /** copy constructor @param q: the Quaternion to set this to. @returns the Quaternion q (or this) */
    83   inline Quaternion operator= (const Quaternion& q) {this->v = q.v; this->w = q.w; return *this;}
    84   /** conjugates this Quaternion @returns the conjugate */
    85   inline Quaternion conjugate () const { return Quaternion(Vector(-v.x, -v.y, -v.z), this->w); };
    86   /** @returns the norm of The Quaternion */
    87   inline float norm () const { return sqrt(w*w + v.x*v.x + v.y*v.y + v.z*v.z); };
    88   /** @returns the inverted Quaterntion of this */
    89   inline Quaternion inverse () const { return conjugate() / (w*w + v.x*v.x + v.y*v.y + v.z*v.z); };
    90   /** @returns the dot Product of a Quaternion */
    91   inline float dot (const Quaternion& q) const { return v.x*q.v.x + v.y*q.v.y + v.z*q.v.z + w*q.w; };
    92   /** @retuns the Distance between two Quaternions */
    93   inline float distance(const Quaternion& q) const { return 2*acos(fabsf(this->dot(q))); };
    94   /** @param v: the Vector  @return a new Vector representing v rotated by the Quaternion */
    95   inline Vector apply (const Vector& v) const { return (*this * Quaternion(v, 0) * conjugate()).v; };
    96   void matrix (float m[4][4]) const;
    97   /** @returns the normalized Quaternion (|this|) */
    98   inline Quaternion getNormalized() const { float n = this->norm(); return Quaternion(this->v/n, this->w/n); };
    99   /** normalizes the current Quaternion */
    100   inline void normalize() { float n = this->norm(); this->v /= n; this->w/=n; };
     55    /** @param f: a real value @return a Quaternion containing the quotient */
     56    inline Quaternion operator/ (const float& f) const { return (unlikely(f==0.0)) ? Quaternion() : Quaternion(this->v/f, this->w/f); };
     57    /** @param f: the value to divide by @returns the quaternion devided by f (this /= f) */
     58    inline const Quaternion& operator/= (const float& f) {*this = *this / f; return *this;}
     59    /** @param f: a real value @return a Quaternion containing the product */
     60    inline Quaternion operator* (const float& f) const { return Quaternion(this->v*f, this->w*f); };
     61    /** @param f: the value to multiply by @returns the quaternion multiplied by f (this *= f) */
     62    inline const Quaternion& operator*= (const float& f) {*this = *this * f; return *this;}
     63    /** @param q: another Quaternion to rotate this by @return a quaternion that represents the first one rotated by the second one (WARUNING: this operation is not commutative! e.g. (A*B) != (B*A)) */
     64    Quaternion operator* (const Quaternion& q) const
     65    {
     66      return Quaternion(Vector(this->w*q.v.x + this->v.x*q.w + this->v.y*q.v.z - this->v.z*q.v.y,
     67                               this->w*q.v.y + this->v.y*q.w + this->v.z*q.v.x - this->v.x*q.v.z,
     68                               this->w*q.v.z + this->v.z*q.w + this->v.x*q.v.y - this->v.y*q.v.x),
     69                        this->w*q.w - this->v.x*q.v.x - this->v.y*q.v.y - this->v.z*q.v.z);
     70    };
     71    /** @param q: the Quaternion to multiply by @returns the quaternion multiplied by q (this *= q) */
     72    inline const Quaternion& operator*= (const Quaternion& q) {*this = *this * q; return *this; };
     73    /** @param q the Quaternion by which to devide @returns the division from this by q (this / q) */
     74    inline Quaternion operator/ (const Quaternion& q) const { return *this * q.inverse(); };
     75    /** @param q the Quaternion by which to devide @returns the division from this by q (this /= q) */
     76    inline const Quaternion& operator/= (const Quaternion& q) { *this = *this * q.inverse(); return *this; };
     77    /** @param q the Quaternion to add to this @returns the quaternion added with q (this + q) */
     78    inline Quaternion operator+ (const Quaternion& q) const { return Quaternion(q.v + v, q.w + w); };
     79    /** @param q the Quaternion to add to this @returns the quaternion added with q (this += q) */
     80    inline const Quaternion& operator+= (const Quaternion& q) { this->v += q.v; this->w += q.w; return *this; };
     81    /** @param q the Quaternion to substrace from this @returns the quaternion substracted by q (this - q) */
     82    inline Quaternion operator- (const Quaternion& q) const { return Quaternion(q.v - v, q.w - w); }
     83    /** @param q the Quaternion to substrace from this @returns the quaternion substracted by q (this -= q) */
     84    inline const Quaternion& operator-= (const Quaternion& q) { this->v -= q.v; this->w -= q.w; return *this; };
     85    /** copy constructor @param q: the Quaternion to set this to. @returns the Quaternion q (or this) */
     86    inline Quaternion operator= (const Quaternion& q) {this->v = q.v; this->w = q.w; return *this;}
     87    /** conjugates this Quaternion @returns the conjugate */
     88    inline Quaternion conjugate () const { return Quaternion(Vector(-v.x, -v.y, -v.z), this->w); };
     89    /** @returns the norm of The Quaternion */
     90    inline float norm () const { return sqrt(w*w + v.x*v.x + v.y*v.y + v.z*v.z); };
     91    /** @returns the inverted Quaterntion of this */
     92    inline Quaternion inverse () const { return conjugate() / (w*w + v.x*v.x + v.y*v.y + v.z*v.z); };
     93    /** @returns the dot Product of a Quaternion */
     94    inline float dot (const Quaternion& q) const { return v.x*q.v.x + v.y*q.v.y + v.z*q.v.z + w*q.w; };
     95    /** @retuns the Distance between two Quaternions */
     96    inline float distance(const Quaternion& q) const { return 2*acos(fabsf(this->dot(q))); };
     97    /** @param v: the Vector  @return a new Vector representing v rotated by the Quaternion */
     98    inline Vector apply (const Vector& v) const { return (*this * Quaternion(v, 0) * conjugate()).v; };
     99    void matrix (float m[4][4]) const;
     100    /** @returns the normalized Quaternion (|this|) */
     101    inline Quaternion getNormalized() const { float n = this->norm(); return Quaternion(this->v/n, this->w/n); };
     102    /** normalizes the current Quaternion */
     103    inline void normalize() { float n = this->norm(); this->v /= n; this->w/=n; };
    101104
    102   float getHeading() const;
    103   Quaternion getHeadingQuat() const;
    104   float getAttitude() const;
    105   Quaternion getAttitudeQuat() const;
    106   float getBank() const;
    107   Quaternion getBankQuat() const;
    108   /** @returns the rotational axis of this Quaternion */
    109   inline Vector getSpacialAxis() const { return this->v / sin(acos(w));/*sqrt(v.x*v.x + v.y*v.y + v.z+v.z);*/ };
    110   /** @returns the rotational angle of this Quaternion around getSpacialAxis()  !! IN DEGREE !! */
    111   inline float getSpacialAxisAngle() const { return 360.0 / M_PI * acos( this->w ); };
     105    float getHeading() const;
     106    Quaternion getHeadingQuat() const;
     107    float getAttitude() const;
     108    Quaternion getAttitudeQuat() const;
     109    float getBank() const;
     110    Quaternion getBankQuat() const;
     111    /** @returns the rotational axis of this Quaternion */
     112    inline Vector getSpacialAxis() const { return this->v / sin(acos(w));/*sqrt(v.x*v.x + v.y*v.y + v.z+v.z);*/ };
     113    /** @returns the rotational angle of this Quaternion around getSpacialAxis()  !! IN DEGREE !! */
     114    inline float getSpacialAxisAngle() const { return 360.0 / M_PI * acos( this->w ); };
    112115
    113116
    114   inline void slerpTo(const Quaternion& toQuat, float t);
    115   static Quaternion quatSlerp(const Quaternion& from, const Quaternion& to, float t);
    116 
    117   void debug() const;
    118   void debug2() const;
     117    inline void slerpTo(const Quaternion& toQuat, float t);
     118    static Quaternion quatSlerp(const Quaternion& from, const Quaternion& to, float t);
    119119
    120120
    121  public:
    122   Vector    v;        //!< Imaginary Vector
    123   float     w;        //!< Real part of the number
     121    static Quaternion lookAt(Vector from, Vector to, Vector up);
     122
     123    void debug() const;
     124    void debug2() const;
     125
     126
     127  public:
     128    Vector    v;        //!< Imaginary Vector
     129    float     w;        //!< Real part of the number
    124130};
    125131
  • trunk/src/lib/network/Makefile.am

    r9494 r9656  
    2727                      \
    2828                      proxy/network_settings.cc \
     29                      proxy/proxy_control.cc \
    2930                      \
    3031                      monitor/connection_monitor.cc \
     
    7677                udp_broadcast.h \
    7778                \
    78                 proxy/network_settings.cc \
     79                proxy/network_settings.h \
     80                proxy/proxy_control.h \
    7981                \
    8082                monitor/connection_monitor.h \
  • trunk/src/lib/network/README.NETWORK

    r9494 r9656  
    11
     2
     3
     4
     5WORD OF WARNING:
     6================
     7 - Allways keep the network_settings.conf file from the data repos up-to-date!! Its very important, that the user numbers are synchronized!
    28
    39
    410WORKING_STACK:
    511==============
    6  - it works to connecto to a master server which is connected to a proxy itself
    7 
     12 - removed compiler warnings in some modules
     13 - totaly rework of the permission system
     14 - introduced a new PERMISSION layer: PERMISSION_SERVER which gives the nearest server the authority to handle
    815
    916
    1017UNSOLVED:
    1118=========
    12  - what if the proxy server gets a new client and wants to add it to the game? There are some problems waiting in the network game manager
    13  - actualy the whole message sending system won't work in this network topic. proxys have to relay messages to clients
    14  - the clients cant get its ip in the handleHandshakes without throuwing sigseg
     19 - the clients cant get its ip in the handleHandshakes without throwing sigseg
     20 - MessageManager: proxy/server forward the messages always. Perhaps there is a case, where messages get forwarded forever if there is a loop in the network. think about it again.
     21 - Permissions: Proxy Servers shouldn't be able to create new eneitites on the server
     22 - the nick name must be handled new
    1523
    1624
     
    4856
    4957
     58The ids are created by the master/proxy servers. Each server receives an address space of 1000 nodes where it is able to assign nodes to. This address space could be extended quite easely, since we got plenty of numbers in 4bytes (integer)
     59
     60The handshake sync has always the uniqueId == userId. This is why there are some reserved uniqueIds
     61
    5062
    5163uniqueId:
    5264=========
    5365uniqueId is an id (unique :D) for each synchronizeable to be identified in a network. the number space for uniqueIds goes from 0 to maxplayers - 1
     66
     67The handshake sync has always the uniqueId == userId. This is why there are some reserved uniqueIds
    5468
    5569
     
    6276PERMISSION_ALL                 : all clients can write this variable
    6377
     78Only the master server should have the permission to create new WorldEntities and to add them to the game
    6479
    6580
     
    7287
    7388
     89MessageManager:
     90===============
     91The message manager has special handling if its a master/proxy: the messages will simply be forwarded to the other server
     92
     93
     94Proxy Control:
     95==============
     96The ProxyControl class manages the state of the network by exchanging state messages.
  • trunk/src/lib/network/handshake.cc

    r9494 r9656  
    7171  remoteState.error = 0;
    7272  remoteState.errorString = "";
    73   remoteState.hostId = -1;
     73  remoteState.hostId = NET_ID_UNASSIGNED;
    7474  remoteState.networkManagerId = -1;
    7575  remoteState.messageManagerId = -1;
  • trunk/src/lib/network/message_manager.cc

    r9494 r9656  
    1111   ### File Specific:
    1212   main-programmer: Christoph Renner
    13    co-programmer: ...
     13   co-programmer: Patrick Boenzli (patrick@orxonox.ethz.ch)
     14
     15     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
     16     July 2006: some code rearangement and integration of the proxy server mechanism (boenzlip@ee.ethz.ch)
     17     July 2006: message forwarding algorithms
    1418*/
    1519
     
    4448MessageManager::~MessageManager ()
    4549{
    46   for ( MessageQueue::iterator it = messageQueue.begin(); it != messageQueue.end(); it++ )
     50  for ( MessageQueue::iterator it = outgoingMessageQueue.begin(); it != outgoingMessageQueue.end(); it++ )
    4751  {
    4852    for ( std::list<NetworkMessage>::iterator it2 = it->second.messages.begin(); it2 != it->second.messages.end(); it2++ )
     
    5963  }
    6064
    61   messageQueue.clear();
     65  outgoingMessageQueue.clear();
    6266
    6367  this->messageHandlerMap.clear();
     
    8589  int n;
    8690
    87   n = Converter::intToByteArray( messageQueue[userId].toAck.size(), data + i, maxLength );
     91  n = Converter::intToByteArray( outgoingMessageQueue[userId].toAck.size(), data + i, maxLength );
    8892  i += n;
    8993  assert( n == INTSIZE );
    9094
    91   for ( std::list<int>::iterator it = messageQueue[userId].toAck.begin(); it != messageQueue[userId].toAck.end(); it++)
     95  for ( std::list<int>::iterator it = outgoingMessageQueue[userId].toAck.begin(); it != outgoingMessageQueue[userId].toAck.end(); it++)
    9296  {
    9397    n = Converter::intToByteArray( *it, data + i, maxLength );
     
    96100  }
    97101
    98   messageQueue[userId].toAck.clear();
    99 
    100   n = Converter::intToByteArray( messageQueue[userId].messages.size(), data + i, maxLength );
     102  outgoingMessageQueue[userId].toAck.clear();
     103
     104  n = Converter::intToByteArray( outgoingMessageQueue[userId].messages.size(), data + i, maxLength );
    101105  i += n;
    102106  assert( n == INTSIZE );
    103107
    104   for ( std::list<NetworkMessage>::iterator it = messageQueue[userId].messages.begin(); it != messageQueue[userId].messages.end(); it++ )
    105   {
     108  // write the message down, a message has this structure:
     109  //   | data_length | serial_number | message_type | source_id | dest_id | ...data... |
     110  //      4byte        4byte            4byte         4byte      4byte     data_length
     111  for ( std::list<NetworkMessage>::iterator it = outgoingMessageQueue[userId].messages.begin(); it != outgoingMessageQueue[userId].messages.end(); it++ )
     112  {
     113    // send data length
    106114    n = Converter::intToByteArray( it->length, data + i, maxLength );
    107115    i += n;
    108116    assert( n == INTSIZE );
    109117
     118    // send serial number
    110119    n = Converter::intToByteArray( it->number, data + i, maxLength );
    111120    i += n;
    112121    assert( n == INTSIZE );
    113122
    114     n = Converter::intToByteArray( it->messageId, data + i, maxLength );
    115     i += n;
    116     assert( n == INTSIZE );
    117 
     123    // send message type
     124    n = Converter::intToByteArray( it->messageType, data + i, maxLength );
     125    i += n;
     126    assert( n == INTSIZE );
     127
     128    // send sender id
     129    n = Converter::intToByteArray( it->senderId, data + i, maxLength );
     130    i += n;
     131    assert( n == INTSIZE );
     132
     133    // send destination id
     134    n = Converter::intToByteArray( it->destinationId, data + i, maxLength );
     135    i += n;
     136    assert( n == INTSIZE );
     137
     138    // send receiver type
     139    n = Converter::intToByteArray( it->recieverType, data + i, maxLength );
     140    i += n;
     141    assert( n == INTSIZE );
     142
     143    // and copy the data
    118144    assert( i + it->length <= maxLength );
    119145    memcpy( data + i, it->data, it->length );
     
    141167  int nAcks;
    142168
     169
    143170  assert( i + INTSIZE <= length );
    144171  n = Converter::byteArrayToInt( data + i, &nAcks );
     
    167194  i += n;
    168195
    169   int messageLength, messageId;
    170 
     196  int messageLength, messageType;
     197  int senderId, destinationId, recieverType;
     198
     199  // now go through all newly received messages and assemble them
    171200  for ( int j = 0; j < nMessages; j++ )
    172201  {
     202    // read the length
    173203    assert( i + INTSIZE <= length );
    174204    n = Converter::byteArrayToInt( data + i, &messageLength );
     
    176206    i += n;
    177207
     208    // read the serial number
    178209    assert( i + INTSIZE <= length );
    179210    n = Converter::byteArrayToInt( data + i, &number );
     
    181212    i += n;
    182213
    183     assert( i + INTSIZE <= length );
    184     n = Converter::byteArrayToInt( data + i, &messageId );
     214    // read the message type
     215    assert( i + INTSIZE <= length );
     216    n = Converter::byteArrayToInt( data + i, &messageType );
     217    assert( n == INTSIZE );
     218    i += n;
     219
     220    // read the sender id
     221    assert( i + INTSIZE <= length );
     222    n = Converter::byteArrayToInt( data + i, &senderId );
     223    assert( n == INTSIZE );
     224    i += n;
     225
     226    //read the destination id
     227    assert( i + INTSIZE <= length );
     228    n = Converter::byteArrayToInt( data + i, &destinationId);
     229    assert( n == INTSIZE );
     230    i += n;
     231
     232    // read the receiver type
     233    assert( i + INTSIZE <= length );
     234    n = Converter::byteArrayToInt( data + i, &recieverType);
    185235    assert( n == INTSIZE );
    186236    i += n;
    187237
    188238    if ( number > 0 )
    189       messageQueue[userId].toAck.push_back( number );
    190 
     239      outgoingMessageQueue[userId].toAck.push_back( number );
     240
     241//     PRINTF(0)("got message with type: %i\n", messageType);
    191242    assert( i + messageLength <= length );
    192     assert( messageHandlerMap.find( (MessageId)messageId ) != messageHandlerMap.end() );
    193     if ( std::find( messageQueue[userId].recievedMessages.begin(), messageQueue[userId].recievedMessages.end(), number )== messageQueue[userId].recievedMessages.end() )
     243    // make sure there is a message handler for this message type
     244    assert( messageHandlerMap.find( (MessageType)messageType ) != messageHandlerMap.end());
     245
     246
     247    if ( std::find( outgoingMessageQueue[userId].recievedMessages.begin(), outgoingMessageQueue[userId].recievedMessages.end(), number ) ==
     248         outgoingMessageQueue[userId].recievedMessages.end() )
    194249    {
    195       if ( !(*(messageHandlerMap[(MessageId)messageId].cb))( (MessageId)messageId, data + i, messageLength, messageHandlerMap[(MessageId)messageId].someData, userId ) )
     250
     251      // find out if this message is addressed for this client too
     252      if( recieverType == RT_ALL_BUT_ME  && SharedNetworkData::getInstance()->getHostID() != senderId ||
     253          recieverType == RT_ALL_ME ||
     254          recieverType == RT_NOT_USER && SharedNetworkData::getInstance()->getHostID() != destinationId ||
     255          recieverType == RT_USER  && SharedNetworkData::getInstance()->getHostID() == destinationId ||
     256          recieverType == RT_SERVER && SharedNetworkData::getInstance()->isMasterServer() ||
     257          recieverType == RT_SERVER && SharedNetworkData::getInstance()->isProxyServerActive())
    196258      {
    197         NetworkMessage msg;
    198 
    199         msg.data = new byte[messageLength];
    200         memcpy( msg.data, data + i, messageLength );
    201         msg.length = messageLength;
    202         msg.messageId = (MessageId)messageId;
    203         msg.number = userId;
    204 
    205         incomingMessageBuffer.push_back( msg );
     259
     260        PRINTF(0)("<<< MessageManager: got msg with type: %i, from sender %i, to rec: %i\n", messageType, senderId, destinationId);
     261      // call the handler function and handle errors
     262        if ( !(*(messageHandlerMap[(MessageType)messageType].cb))( (MessageType)messageType, data + i, messageLength,
     263                 messageHandlerMap[(MessageType)messageType].someData, senderId, destinationId ) )
     264        {
     265        // if the message is not handled correctly, bush it back to the incoming packets therefore trying it later
     266          NetworkMessage msg;
     267
     268          msg.data = new byte[messageLength];
     269          memcpy( msg.data, data + i, messageLength );
     270          msg.length = messageLength;
     271          msg.messageType = (MessageType)messageType;
     272          msg.number = userId;
     273          msg.senderId = senderId;
     274          msg.recieverType = (RecieverType)recieverType;
     275          msg.destinationId = destinationId;
     276
     277          incomingMessageQueue.push_back( msg );
     278        }
    206279      }
    207       messageQueue[userId].recievedMessages.push_back( number );
     280
     281
     282      // check if the message needs to be forwarded
     283      if( recieverType == RT_ALL_BUT_ME ||
     284          recieverType == RT_ALL_ME ||
     285          recieverType == RT_NOT_USER ||
     286          recieverType == RT_USER  && SharedNetworkData::getInstance()->getHostID() != destinationId ||
     287          recieverType == RT_SERVER && SharedNetworkData::getInstance()->isProxyServerActive() )
     288      {
     289        // forwarding the messages but only if its a proxy
     290        if( SharedNetworkData::getInstance()->isProxyServerActive())
     291        {
     292          PRINTF(0)("===========>> Forwarding Message msg with type: %i, from sender %i, to rec: %i\n", messageType, senderId, destinationId);
     293          NetworkMessage msg;
     294
     295          msg.data = new byte[messageLength];
     296          memcpy( msg.data, data + i, messageLength );
     297          msg.length = messageLength;
     298          msg.messageType = (MessageType)messageType;
     299          msg.number = userId;
     300          msg.senderId = senderId;
     301          msg.destinationId = destinationId;
     302          msg.recieverType = (RecieverType)recieverType;
     303
     304          this->sendMessage(msg.messageType, msg.data, msg.length, msg.recieverType, msg.senderId = senderId, msg.destinationId, MP_HIGHBANDWIDTH);
     305        }
     306      }
     307
     308      // save the serial number for ack signaling
     309      outgoingMessageQueue[userId].recievedMessages.push_back( number );
    208310    }
     311
    209312    i += messageLength;
    210313  }
    211314
    212315
    213   //TODO maybe handle incomingMessage in tick function. else local messages will not be handled if no clients are connected
    214   for ( std::list<NetworkMessage>::iterator it = incomingMessageBuffer.begin(); it != incomingMessageBuffer.end();  )
    215   {
    216     if ( (*(messageHandlerMap[it->messageId].cb))( it->messageId, it->data, it->length, messageHandlerMap[it->messageId].someData, it->number ) )
     316  //walk throu message queue and remove acked messages
     317  for ( std::list<NetworkMessage>::iterator it = outgoingMessageQueue[userId].messages.begin(); it != outgoingMessageQueue[userId].messages.end();  )
     318  {
     319    if ( std::find( acks.begin(), acks.end(), it->number) != acks.end() )
     320    {
     321      std::list<NetworkMessage>::iterator delIt = it;
     322      it++;
     323      outgoingMessageQueue[userId].messages.erase( delIt );
     324      continue;
     325    }
     326    it++;
     327  }
     328
     329  //TODO find bether way. maybe with timestamp
     330  if ( outgoingMessageQueue[userId].recievedMessages.size() > 1000 )
     331  {
     332    for ( int j = 0; j < (int)outgoingMessageQueue[userId].recievedMessages.size() - 1000; j++ )
     333      outgoingMessageQueue[userId].recievedMessages.erase( outgoingMessageQueue[userId].recievedMessages.begin() );
     334  }
     335
     336  return i;
     337}
     338
     339
     340
     341
     342/**
     343 * processes the message manager data, specialy check for localy generated messages
     344 */
     345void MessageManager::processData()
     346{
     347  // now call the message handlers with the new message
     348  for ( std::list<NetworkMessage>::iterator it = incomingMessageQueue.begin(); it != incomingMessageQueue.end();  )
     349  {
     350    PRINTF(0)("<<< MessageManager: got local msg with type: %i, from sender %i, to rec: %i\n", (*it).messageType, (*it).senderId, (*it).destinationId);
     351
     352    if ( (*(messageHandlerMap[it->messageType].cb))( it->messageType, it->data, it->length, messageHandlerMap[it->messageType].someData,
     353                                                     /*it->number, */it->senderId, it->destinationId ) )
    217354    {
    218355      std::list<NetworkMessage>::iterator delIt = it;
     
    220357        delete it->data;
    221358      it++;
    222       incomingMessageBuffer.erase( delIt );
     359      incomingMessageQueue.erase( delIt );
    223360      continue;
    224361    }
     
    226363  }
    227364
    228   //walk throu message queue and remove acked messages
    229   for ( std::list<NetworkMessage>::iterator it = messageQueue[userId].messages.begin(); it != messageQueue[userId].messages.end();  )
    230   {
    231     if ( std::find( acks.begin(), acks.end(), it->number) != acks.end() )
    232     {
    233       std::list<NetworkMessage>::iterator delIt = it;
    234       it++;
    235       messageQueue[userId].messages.erase( delIt );
    236       continue;
    237     }
    238     it++;
    239   }
    240 
    241   //TODO find bether way. maybe with timestamp
    242   if ( messageQueue[userId].recievedMessages.size() > 1000 )
    243   {
    244     for ( int j = 0; j < messageQueue[userId].recievedMessages.size() - 1000; j++ )
    245       messageQueue[userId].recievedMessages.erase( messageQueue[userId].recievedMessages.begin() );
    246   }
    247 
    248   return i;
    249 }
     365}
     366
     367
     368
    250369
    251370/**
     
    255374void MessageManager::cleanUpUser( int userId )
    256375{
    257   if ( messageQueue.find( userId ) == messageQueue.end() )
     376  if ( outgoingMessageQueue.find( userId ) == outgoingMessageQueue.end() )
    258377    return;
    259378
    260   for ( std::list<NetworkMessage>::iterator it = messageQueue[userId].messages.begin(); it != messageQueue[userId].messages.end(); it++ )
     379  for ( std::list<NetworkMessage>::iterator it = outgoingMessageQueue[userId].messages.begin(); it != outgoingMessageQueue[userId].messages.end(); it++ )
    261380  {
    262381    if ( it->data )
     
    265384  }
    266385
    267   messageQueue[userId].toAck.clear();
    268 
    269   messageQueue.erase( userId );
    270 }
    271 
    272 /**
    273  * registers function to handle messages with id messageId. someData is passed to callbackfuntion
    274  * @param messageId message id to handle
     386  outgoingMessageQueue[userId].toAck.clear();
     387
     388  outgoingMessageQueue.erase( userId );
     389}
     390
     391/**
     392 * registers function to handle messages with id messageType. someData is passed to callbackfuntion
     393 * @param messageType message id to handle
    275394 * @param cb function pointer to callback function
    276395 * @param someData this pointer is passed to callback function without modification
    277396 * @return true on success
    278397 */
    279 bool MessageManager::registerMessageHandler( MessageId messageId, MessageCallback cb, void * someData )
     398bool MessageManager::registerMessageHandler( MessageType messageType, MessageCallback cb, void * someData )
    280399{
    281400  MessageHandler messageHandler;
    282401
    283402  messageHandler.cb = cb;
    284   messageHandler.messageId = messageId;
     403  messageHandler.messageType = messageType;
    285404  messageHandler.someData = someData;
    286405
    287   messageHandlerMap[messageId] = messageHandler;
     406  messageHandlerMap[messageType] = messageHandler;
    288407
    289408  return true;
     
    297416{
    298417  // just do something so map creates a new entry
    299   messageQueue[userId].toAck.clear();
    300   //assert( messageQueue[userId].messages.size() == 0 );
    301 }
     418  outgoingMessageQueue[userId].toAck.clear();
     419  //assert( outgoingMessageQueue[userId].messages.size() == 0 );
     420}
     421
     422
    302423
    303424/**
     
    308429 *               RT_NOT_USER send to all but reciever
    309430 *
    310  * @param messageId message id
     431 * @param messageType message id
    311432 * @param data pointer to data
    312433 * @param dataLength length of data
    313  * @param recieverType
    314  * @param reciever
    315  */
    316 void MessageManager::sendMessage( MessageId messageId, byte * data, int dataLength, RecieverType recieverType, int reciever, MessagePriority messagePriority )
    317 {
    318   for ( MessageQueue::iterator it = messageQueue.begin(); it != messageQueue.end(); it++ )
    319   {
     434 * @param recieverType type of the receiver
     435 * @param reciever the userId of the receiver if needed (depends on the ReceiverType)
     436 */
     437void MessageManager::sendMessage( MessageType messageType, byte * data, int dataLength, RecieverType recieverType, int reciever, MessagePriority messagePriority )
     438{
     439  this->sendMessage(messageType, data, dataLength, recieverType, SharedNetworkData::getInstance()->getHostID(), reciever, messagePriority);
     440}
     441
     442
     443/**
     444 * send a message to one or more clients as a special client
     445 * recieverType:
     446 *               RT_ALL send to all users. reciever is ignored
     447 *               RT_USER send only to reciever
     448 *               RT_NOT_USER send to all but reciever
     449 *
     450 * @param messageType message id
     451 * @param data pointer to data
     452 * @param dataLength length of data
     453 * @param recieverType type of the receiver
     454 * @param sender the userId of the sender if there is need for shadowing it (eg. for msg forwarding)
     455 * @param reciever the userId of the receiver if needed (depends on the ReceiverType)
     456 */
     457    void MessageManager::sendMessage( MessageType messageType, byte * data, int dataLength, RecieverType recieverType, int sender, int reciever, MessagePriority messagePriority )
     458{
     459  PRINTF(0)(" >>> MessageManager: sending msg with type: %i, recieverType: %i, reciever %i\n", messageType, recieverType, reciever);
     460
     461  // go through all outgoing message queues and add the message if its appropriate
     462  for ( MessageQueue::iterator it = this->outgoingMessageQueue.begin(); it != this->outgoingMessageQueue.end(); it++ )
     463  {
     464
    320465    if (
    321          recieverType == RT_ALL_ME ||
    322          recieverType == RT_ALL_BUT_ME ||
    323          recieverType == RT_USER && it->first == reciever ||
    324          recieverType == RT_NOT_USER && it->first != reciever ||
    325          recieverType == RT_SERVER && getNetworkStream()->isUserMasterServer( it->first ) ||
    326          recieverType == RT_SERVER && getNetworkStream()->isUserProxyServerActive( it->first )
    327        )
     466         recieverType == RT_ALL_ME      ||
     467         recieverType == RT_ALL_BUT_ME  ||
     468         recieverType == RT_USER        && it->first == reciever ||
     469         recieverType == RT_USER        && reciever == NET_ID_MASTER_SERVER && !getNetworkStream()->isUserMasterServer( it->first ) ||  //(*)
     470         recieverType == RT_NOT_USER    && it->first != reciever ||
     471         recieverType == RT_SERVER      && getNetworkStream()->isUserMasterServer( it->first ) ||
     472         recieverType == RT_SERVER      && getNetworkStream()->isUserProxyServerActive( it->first )
     473       )// (*) special case: forward
    328474    {
    329475      NetworkMessage msg;
     
    332478      memcpy( msg.data, data, dataLength );
    333479      msg.length = dataLength;
    334       msg.messageId = messageId;
    335       msg.number = newNumber++;
     480      msg.messageType = messageType;
     481      msg.number = this->newNumber++;
     482      msg.senderId = sender;
     483      msg.destinationId = reciever;
     484      msg.recieverType = recieverType;
    336485      msg.priority = messagePriority;
    337486
    338487      it->second.messages.push_back( msg );
    339488    }
    340   }
    341 
    342   if ( recieverType == RT_ALL_ME )
     489
     490
     491  }
     492
     493
     494  // if the message is also for myself, handle it here
     495  if ( recieverType == RT_ALL_ME ||
     496       recieverType == RT_USER   && reciever == SharedNetworkData::getInstance()->getHostID()
     497     )
    343498  {
    344499    NetworkMessage msg;
     
    347502    memcpy( msg.data, data, dataLength );
    348503    msg.length = dataLength;
    349     msg.messageId = messageId;
     504    msg.messageType = messageType;
    350505    msg.number = SharedNetworkData::getInstance()->getHostID();
     506    msg.senderId = sender;
     507    msg.destinationId = reciever;
     508    msg.recieverType = recieverType;
    351509    msg.priority = messagePriority;
    352510
    353     incomingMessageBuffer.push_back( msg );
    354   }
    355 }
    356 
    357 
     511    this->incomingMessageQueue.push_back( msg );
     512  }
     513}
     514
     515
  • trunk/src/lib/network/message_manager.h

    r9494 r9656  
    2020      int length
    2121      int number
    22       int MessageId
     22      int MessageType
    2323      byte * data
    2424    )[1..nmsg]
     
    2626
    2727
    28 enum MessageId
     28//!< different message ids
     29enum MessageType
    2930{
    30   TESTMESSAGEID = 1,
    31   MSGID_DELETESYNCHRONIZEABLE,
    32   MSGID_PREFEREDTEAM,
    33   MSGID_CHANGENICKNAME,
    34   MSGID_CHATMESSAGE,
    35   MSGID_RESPAWN
     31  TESTMESSAGEID                  = 1,         //!< for testing purposes
     32  MSGID_DELETESYNCHRONIZEABLE,                //!< message for sync deletion
     33  MSGID_PREFEREDTEAM,                         //!< change prefered team
     34  MSGID_CHANGENICKNAME,                       //!< change nicknames
     35  MSGID_CHATMESSAGE,                          //!< chat message
     36  MSGID_RESPAWN,                              //!< respawn message
     37
     38  MSGID_PROXY_NEWCLIENT,                       //!< informs the master server about a new client
     39  MSGID_PROXY_LEAVECLIENT,                     //!< informs the master and other proxy servers about a leaving client
     40  MSGID_PROXY_COMMAND,                         //!< command handler: delivers commands from and to proxies/clients
    3641};
    3742
    38 typedef bool (*MessageCallback)( MessageId messageId, byte * data, int dataLength, void * someData, int userId );
    3943
    40 enum RecieverType
     44typedef bool (*MessageCallback)( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId );
     45
     46typedef enum RecieverType
    4147{
    4248  RT_ALL_BUT_ME = 1,   //!< message is sent to all users but myself
     
    5763struct NetworkMessage
    5864{
    59   MessageId        messageId;
    60   byte *           data;
    61   int              length;
    62   int              number;
    63   MessagePriority  priority;
     65  MessageType      messageType;                         //!< type of the message
     66  byte *           data;                                //!< data
     67  int              length;                              //!< length of the data
     68  int              number;                              //!< serial number
     69  int              senderId;                            //!< userId of the sender
     70  int              destinationId;                       //!< userId of the destination
     71  RecieverType     recieverType;                        //!< type of the receiver
     72  MessagePriority  priority;                            //!< priority of the messages
    6473};
    6574
     
    7382typedef std::map<int,MessageUserQueue> MessageQueue;
    7483
     84
     85
    7586struct MessageHandler
    7687{
    77   MessageCallback cb;
    78   MessageId       messageId;
    79   void *          someData;
     88  MessageCallback   cb;
     89  MessageType       messageType;
     90  void *            someData;
    8091};
    8192
    82 typedef std::map<MessageId,MessageHandler> MessageHandlerMap;
     93typedef std::map<MessageType,MessageHandler> MessageHandlerMap;
    8394
    8495//! A class for sending messages over network
    8596class MessageManager : public Synchronizeable {
    86  protected:
    87    MessageManager();
     97
     98
    8899 public:
    89100   inline static MessageManager * getInstance(){ if (!singletonRef) singletonRef = new MessageManager();  return singletonRef; }
     
    91102   virtual ~MessageManager();
    92103
    93    bool registerMessageHandler( MessageId messageId, MessageCallback cb, void * someData );
     104   bool registerMessageHandler( MessageType messageType, MessageCallback cb, void * someData );
    94105
    95    void sendMessage( MessageId messageId, byte * data, int dataLength, RecieverType recieverType, int reciever, MessagePriority messagePriority );
     106   void sendMessage( MessageType messageType, byte * data, int dataLength, RecieverType recieverType, int reciever, MessagePriority messagePriority );
     107   void sendMessage( MessageType messageType, byte * data, int dataLength, RecieverType recieverType, int sender, int reciever, MessagePriority messagePriority );
    96108
     109   void initUser( int userId );
     110
     111   void processData();
     112
     113
     114  protected:
     115    MessageManager();
     116
     117
     118  private:
    97119   virtual int getStateDiff( int userId, byte* data, int maxLength, int stateId, int fromStateId, int priorityTH );
    98120   virtual int setStateDiff( int userId, byte* data, int length, int stateId, int fromStateId );
     
    101123   virtual void handleRecvState( int userId, int stateId, int fromStateId ){}
    102124
    103    void initUser( int userId );
    104 
    105125
    106126 private:
    107    static MessageManager *   singletonRef;
    108    MessageQueue              messageQueue;           //!< stores messages to send
     127   static MessageManager *   singletonRef;           //!< the singleton reference
     128
     129   std::list<NetworkMessage> incomingMessageQueue;   //!< the incoming message buffer
     130   MessageQueue              outgoingMessageQueue;   //!< stores messages to send
    109131   MessageHandlerMap         messageHandlerMap;      //!< contains handlers for messages
    110132
    111133   int                       newNumber;              //!< used to create unique message numbers
    112    std::list<NetworkMessage> incomingMessageBuffer;
     134
    113135
    114136};
    115137
    116 #endif /* _PROTO_CLASS_H */
     138#endif /* _MESSAGE_MANAGER_H */
  • trunk/src/lib/network/monitor/network_monitor.cc

    r9494 r9656  
    1010
    1111### File Specific:
    12    main-programmer: Patrick Boenzli
     12   main-programmer: Patrick Boenzli (patrick@orxonox.ethz.ch)
    1313*/
    1414
     
    4949  this->networkStream = networkStream;
    5050  this->playerNumber = 0;
     51  this->connectionNumber = 0;
    5152  // create the localnode, init it and add it to the nodes list
    5253  this->localNode = new NetworkNode( this->networkStream->getPeerInfo());
     
    6667      PeerInfo* peer = new PeerInfo();
    6768      peer->ip = (*it);
    68       peer->nodeType = NET_PROXY_SERVER_ACTIVE;
     69      peer->nodeType = NET_PROXY_SERVER_PASSIVE;
    6970      peer->userId = -1;
    7071
    71       NetworkNode* node = new NetworkNode(peer);
    72       this->addNode( node);
    7372      this->addActiveProxyServer( this->localNode, peer);
    7473    }
     
    141140    return;
    142141
     142  PRINTF(0)("^^^^^^^^^^^^^^^^^^^^^^^^^^ adding node: %i with type: %s\n\n", pInfo->userId, pInfo->getNodeTypeString().c_str());
     143
    143144  if( pInfo->isClient())
    144     this->localNode->addClient(pInfo);
     145  {
     146    this->localNode->addClient(new NetworkNode(pInfo));
     147  }
    145148  else if( pInfo->isProxyServerActive())
    146149  {
    147     this->localNode->addActiveProxyServer(pInfo);
    148     // create a new node, since a proxy can connect clients again
    149     NetworkNode* node = new NetworkNode(pInfo);
    150     this->nodeList.push_back(node);
     150    this->localNode->addActiveProxyServer(new NetworkNode(pInfo));
     151  }
     152  else if( pInfo->isProxyServerActivePassive())
     153  {
     154    this->localNode->addPassiveProxyServer(new NetworkNode(pInfo));
    151155  }
    152156  else if( pInfo->isMasterServer())
    153157  {
    154     this->localNode->addMasterServer(pInfo);
    155   }
     158    this->localNode->addMasterServer(new NetworkNode(pInfo));
     159  }
     160  else
     161    assert(false);
    156162}
    157163
     
    168174
    169175  if( pInfo->isClient())
    170     node->addClient(pInfo);
     176    node->addClient(new NetworkNode(pInfo));
    171177  else if( pInfo->isProxyServerActive())
    172     node->addActiveProxyServer(pInfo);
     178    node->addActiveProxyServer(new NetworkNode(pInfo));
    173179  else if( pInfo->isMasterServer())
    174     node->addMasterServer(pInfo);
     180    node->addMasterServer(new NetworkNode(pInfo));
     181}
     182
     183
     184
     185/**
     186 * removes a node from the network monitor
     187 * @param pInfo the node to remove
     188 */
     189void NetworkMonitor::removeNode(PeerInfo* pInfo)
     190{
     191  this->removeNode(this->localNode, pInfo);
     192}
     193
     194
     195/**
     196 * removes the network node
     197 * @param node the network node where the PeerInfo node is connected to
     198 * @param pInfo the PeerInfo to remove
     199 */
     200void NetworkMonitor::removeNode(NetworkNode* node, PeerInfo* pInfo)
     201{
     202  if( node == NULL || pInfo == NULL)
     203    return;
     204
     205  if( pInfo->isClient())
     206    node->removeClient(pInfo->userId);
     207  else if( pInfo->isProxyServerActive())
     208    node->removeActiveProxyServer(pInfo->userId);
     209  else if( pInfo->isMasterServer())
     210    node->removeMasterServer(pInfo->userId);
    175211}
    176212
     
    197233
    198234/**
     235 * @param userId of the searched node
     236 * @returns the PeerInfo of the userId peer
     237 */
     238PeerInfo* NetworkMonitor::getPeerByUserId( int userId)
     239{
     240  NetworkNode* node = this->getNodeByUserId(userId);
     241  if( node != NULL)
     242    return node->getPeerInfo();
     243
     244  return NULL;
     245}
     246
     247/**
     248 * searches for a given NetworkNode
     249 * @param userId of the searched node
     250 * @returns the PeerInfo of the userId peer
     251 */
     252NetworkNode* NetworkMonitor::getNodeByUserId( int userId)
     253{
     254  std::list<NetworkNode*>::iterator it = this->nodeList.begin();
     255  NetworkNode* node = NULL;
     256  for(; it != this->nodeList.end(); it++)
     257  {
     258    node = (*it)->getNodeByUserId(userId);
     259    if( node != NULL)
     260      return node;
     261  }
     262
     263  return NULL;
     264}
     265
     266
     267/**
    199268 * this displays the network monitor gui
    200269 */
     
    203272  if (this->box == NULL)
    204273  {
    205     this->box = new OrxGui::GLGuiBox(OrxGui::Vertical);
    206     {
    207       NetworkStatsWidget* netStats = new NetworkStatsWidget(this);
    208       this->box->pack(netStats);
    209 
    210     }
    211 
     274    this->box = new NetworkStatsWidget(this);
    212275    this->box->showAll();
    213     this->box->setAbsCoor2D(300, 40);
    214276  }
    215277  else
     
    251313  for(; it != this->nodeList.end(); it++)
    252314  {
    253     (*it)->debug(0);
     315    (*it)->debug(1);
    254316  }
    255317
  • trunk/src/lib/network/monitor/network_monitor.h

    r9494 r9656  
    4242
    4343    /** adds to @param node a network node @param pInfo a new client */
    44     inline void addClient(NetworkNode* node, PeerInfo* pInfo) { node->addClient(pInfo); }
     44    inline void addClient(NetworkNode* node, PeerInfo* pInfo) { node->addClient(new NetworkNode(pInfo)); }
    4545    /** adds to @param node a network node @param pInfo a new proxy server */
    46     inline void addActiveProxyServer(NetworkNode* node, PeerInfo* pInfo) { node->addActiveProxyServer(pInfo); }
     46    inline void addActiveProxyServer(NetworkNode* node, PeerInfo* pInfo) { node->addActiveProxyServer(new NetworkNode(pInfo)); }
    4747    /** adds to @param node a network node @param pInfo a new proxy server */
    48     inline void addPassiveProxyServer(NetworkNode* node, PeerInfo* pInfo) { node->addPassiveProxyServer(pInfo); }
     48    inline void addPassiveProxyServer(NetworkNode* node, PeerInfo* pInfo) { node->addPassiveProxyServer(new NetworkNode(pInfo)); }
    4949    /** adds to @param node a network node @param pInfo a new master server*/
    50     inline void addMasterServer(NetworkNode* node, PeerInfo* pInfo) { node->addMasterServer(pInfo); }
     50    inline void addMasterServer(NetworkNode* node, PeerInfo* pInfo) { node->addMasterServer(new NetworkNode(pInfo)); }
    5151
    52     inline void removeClient(NetworkNode* node, PeerInfo* pInfo) { node->removeClient(pInfo); }
    53     inline void removeActiveProxyServer(NetworkNode* node, PeerInfo* pInfo) { node->removeActiveProxyServer(pInfo); }
    54     inline void removePassiveProxyServer(NetworkNode* node, PeerInfo* pInfo) { node->removePassiveProxyServer(pInfo); }
    55     inline void removeMasterServer(NetworkNode* node, PeerInfo* pInfo) { node->removeMasterServer(pInfo); }
     52    void removeNode(PeerInfo* pInfo);
     53    void removeNode(NetworkNode* node, PeerInfo* pInfo);
     54
     55    inline void removeClient(NetworkNode* node, int userId) { node->removeClient(userId); }
     56    inline void removeActiveProxyServer(NetworkNode* node, int userId) { node->removeActiveProxyServer(userId); }
     57    inline void removePassiveProxyServer(NetworkNode* node, int userId) { node->removePassiveProxyServer(userId); }
     58    inline void removeMasterServer(NetworkNode* node, int userId) { node->removeMasterServer(userId); }
    5659
    5760    PeerInfo* getFirstChoiceProxy() const;
     
    6164
    6265    /** @returns the active proxy server list of the localnode */
    63     inline std::list<PeerInfo*> getActiveProxyServer() const { return this->localNode->getActiveProxyServer(); }
     66    inline std::list<NetworkNode*> getActiveProxyServers() const { return this->localNode->getActiveProxyServers(); }
    6467
    6568    /* slots admin and info interface */
     
    7679
    7780    inline const std::list<NetworkNode*>& getNodeList() const { return this->nodeList; };
     81    PeerInfo* getPeerByUserId( int userId);
     82    NetworkNode* getNodeByUserId( int userId);
     83
     84    /* forced reconnection interface */
     85    inline void setForcedReconnection(IP address) { this->bForcedRecon = true; this->forcedReconnection = address;}
     86    inline bool isForcedReconnection() const { return this->bForcedRecon; }
     87    inline IP getForcedReconnectionIP() { this->bForcedRecon = false; return this->forcedReconnection; }
     88
    7889
    7990    void toggleGUI();
     
    92103    int                          playerNumber;                 //!< total number of players in the game
    93104    int                          connectionNumber;             //!< total number of connections at this localhost
     105
     106    IP                           forcedReconnection;           //!< ip of a forced reconnection
     107    bool                         bForcedRecon;                 //!< true if there is a forced recon
    94108};
    95109
  • trunk/src/lib/network/monitor/network_node.cc

    r9494 r9656  
    1818#include "debug.h"
    1919
    20 
    2120/**
    2221 * constructor
     
    3938 * adds a client
    4039 */
    41 void NetworkNode::addClient(PeerInfo* node)
     40void NetworkNode::addClient(NetworkNode* node)
    4241{
    4342  this->clientList.push_back(node);
     
    4948 * adds a proxy server
    5049 */
    51 void NetworkNode::addActiveProxyServer(PeerInfo* node)
     50void NetworkNode::addActiveProxyServer(NetworkNode* node)
    5251{
    5352  this->activeProxyServerList.push_back(node);
     
    5857 * adds a proxy server
    5958 */
    60 void NetworkNode::addPassiveProxyServer(PeerInfo* node)
     59void NetworkNode::addPassiveProxyServer(NetworkNode* node)
    6160{
    6261  this->passiveProxyServerList.push_back(node);
     
    6665 * adds a master server
    6766 */
    68 void NetworkNode::addMasterServer(PeerInfo* node)
     67void NetworkNode::addMasterServer(NetworkNode* node)
    6968{
    7069  this->masterServerList.push_back(node);
     
    7574 * removes a client
    7675 */
    77 void NetworkNode::removeClient(PeerInfo* node)
    78 {
    79   std::list<PeerInfo*>::iterator it = this->clientList.begin();
     76void NetworkNode::removeClient(NetworkNode* node)
     77{
     78  std::list<NetworkNode*>::iterator it = this->clientList.begin();
    8079  for(; it != this->clientList.end(); it++)
    8180  {
     
    9493 * removes a proxy server
    9594 */
    96 void NetworkNode::removeActiveProxyServer(PeerInfo* node)
    97 {
    98   std::list<PeerInfo*>::iterator it = this->activeProxyServerList.begin();
     95void NetworkNode::removeActiveProxyServer(NetworkNode* node)
     96{
     97  std::list<NetworkNode*>::iterator it = this->activeProxyServerList.begin();
    9998  for(; it != this->activeProxyServerList.end(); it++)
    10099  {
     
    113112 * removes a proxy server
    114113 */
    115 void NetworkNode::removePassiveProxyServer(PeerInfo* node)
    116 {
    117   std::list<PeerInfo*>::iterator it = this->passiveProxyServerList.begin();
     114void NetworkNode::removePassiveProxyServer(NetworkNode* node)
     115{
     116  std::list<NetworkNode*>::iterator it = this->passiveProxyServerList.begin();
    118117  for(; it != this->passiveProxyServerList.end(); it++)
    119118  {
     
    131130 * removes a master server
    132131 */
    133 void NetworkNode::removeMasterServer(PeerInfo* node)
    134 {
    135   std::list<PeerInfo*>::iterator it = this->masterServerList.begin();
     132void NetworkNode::removeMasterServer(NetworkNode* node)
     133{
     134  std::list<NetworkNode*>::iterator it = this->masterServerList.begin();
    136135  for(; it != this->masterServerList.end(); it++)
    137136  {
     
    145144
    146145  PRINTF(2)("Could not remove client from the list, very strange...");
     146}
     147
     148
     149
     150
     151/**
     152 * removes a client
     153 */
     154void NetworkNode::removeClient(int userId)
     155{
     156  std::list<NetworkNode*>::iterator it = this->clientList.begin();
     157  for(; it != this->clientList.end(); it++)
     158  {
     159    if( (*it)->getPeerInfo()->userId == userId)
     160    {
     161      this->clientList.erase(it);
     162      this->playerNumber--;
     163      return;
     164    }
     165  }
     166
     167  PRINTF(2)("Could not remove client from the list, very strange...");
     168}
     169
     170/**
     171 * removes a proxy server
     172 */
     173void NetworkNode::removeActiveProxyServer(int userId)
     174{
     175  std::list<NetworkNode*>::iterator it = this->activeProxyServerList.begin();
     176  for(; it != this->activeProxyServerList.end(); it++)
     177  {
     178    if( (*it)->getPeerInfo()->userId == userId)
     179    {
     180      this->activeProxyServerList.erase(it);
     181      this->playerNumber--;
     182      return;
     183    }
     184  }
     185
     186  PRINTF(2)("Could not remove proxy server from the list, very strange...");
     187}
     188
     189/**
     190 * removes a proxy server
     191 */
     192void NetworkNode::removePassiveProxyServer(int userId)
     193{
     194  std::list<NetworkNode*>::iterator it = this->passiveProxyServerList.begin();
     195  for(; it != this->passiveProxyServerList.end(); it++)
     196  {
     197    if( (*it)->getPeerInfo()->userId == userId)
     198    {
     199      this->passiveProxyServerList.erase(it);
     200      return;
     201    }
     202  }
     203
     204  PRINTF(2)("Could not remove proxy server from the list, very strange...");
     205}
     206
     207/**
     208 * removes a master server
     209 */
     210void NetworkNode::removeMasterServer(int userId)
     211{
     212  std::list<NetworkNode*>::iterator it = this->masterServerList.begin();
     213  for(; it != this->masterServerList.end(); it++)
     214  {
     215    if( (*it)->getPeerInfo()->userId == userId)
     216    {
     217      this->masterServerList.erase(it);
     218      this->playerNumber--;
     219      return;
     220    }
     221  }
     222
     223  PRINTF(2)("Could not remove client from the list, very strange...");
     224}
     225
     226
     227
     228
     229
     230/**
     231 *  gets the peer info by user id
     232 * @param userId  the user id of the node to look up
     233 * @return the peer info of this node NULL if nothing found
     234 */
     235PeerInfo* NetworkNode::getPeerByUserId( int userId)
     236{
     237  // look through the master server lists
     238  std::list<NetworkNode*>::const_iterator it = this->masterServerList.begin();
     239  for( ;it != this->masterServerList.end(); it++)
     240  {
     241    if( (*it)->getPeerInfo()->userId == userId)
     242      return (*it)->getPeerInfo();
     243  }
     244
     245  // look through the active proxy server list
     246  it = this->activeProxyServerList.begin();
     247  for( ; it != this->activeProxyServerList.end(); it++)
     248  {
     249    if( (*it)->getPeerInfo()->userId == userId)
     250      return (*it)->getPeerInfo();
     251  }
     252
     253  // look through the passive server list
     254  it = this->passiveProxyServerList.begin();
     255  for( ; it != this->passiveProxyServerList.end(); it++)
     256  {
     257    if( (*it)->getPeerInfo()->userId == userId)
     258      return (*it)->getPeerInfo();
     259  }
     260
     261  // look through the client list
     262  it = this->clientList.begin();
     263  for( ; it != this->clientList.end(); it++)
     264  {
     265    if( (*it)->getPeerInfo()->userId == userId)
     266      return (*it)->getPeerInfo();
     267  }
     268
     269  return NULL;
    147270}
    148271
     
    154277PeerInfo* NetworkNode::getClient(int index) const
    155278{
    156   if( this->clientList.size() < index)
     279  if( (int)this->clientList.size() < index)
    157280    return NULL;
    158281
    159   std::list<PeerInfo*>::const_iterator it = this->clientList.begin();
     282  std::list<NetworkNode*>::const_iterator it = this->clientList.begin();
    160283  for(int i = 0; it != this->clientList.end(); it++, i++)
    161284  {
    162285  if( i == index)
    163     return (*it);
     286    return (*it)->getPeerInfo();
    164287  }
    165288
     
    174297PeerInfo* NetworkNode::getActiveProxyServer(int index) const
    175298{
    176   if( this->activeProxyServerList.size() < index)
     299  if( (int)this->activeProxyServerList.size() < index)
    177300    return NULL;
    178301
    179   std::list<PeerInfo*>::const_iterator it = this->activeProxyServerList.begin();
     302  std::list<NetworkNode*>::const_iterator it = this->activeProxyServerList.begin();
    180303  for(int i = 0; it != this->activeProxyServerList.end(); it++, i++)
    181304  {
    182305    if( i == index)
    183       return (*it);
     306      return (*it)->getPeerInfo();
    184307  }
    185308
     
    194317PeerInfo* NetworkNode::getPassiveProxyServer(int index) const
    195318{
    196   if( this->passiveProxyServerList.size() < index)
     319  if( (int)this->passiveProxyServerList.size() < index)
    197320    return NULL;
    198321
    199   std::list<PeerInfo*>::const_iterator it = this->passiveProxyServerList.begin();
     322  std::list<NetworkNode*>::const_iterator it = this->passiveProxyServerList.begin();
    200323  for(int i = 0; it != this->passiveProxyServerList.end(); it++, i++)
    201324  {
    202325    if( i == index)
    203       return (*it);
     326      return (*it)->getPeerInfo();
    204327  }
    205328
     
    214337PeerInfo* NetworkNode::getMasterServer(int index) const
    215338{
    216   if( this->masterServerList.size() < index)
     339  if( (int)this->masterServerList.size() < index)
    217340    return NULL;
    218341
    219   std::list<PeerInfo*>::const_iterator it = this->masterServerList.begin();
     342  std::list<NetworkNode*>::const_iterator it = this->masterServerList.begin();
    220343  for(int i = 0; it != this->masterServerList.end(); it++, i++)
    221344  {
    222345    if( i == index)
    223       return (*it);
     346      return (*it)->getPeerInfo();
     347  }
     348
     349  return NULL;
     350}
     351
     352
     353
     354/**
     355 * searches for a given NetworkNode
     356 * @param userId of the searched node
     357 * @returns the PeerInfo of the userId peer
     358 */
     359NetworkNode* NetworkNode::getNodeByUserId( int userId)
     360{
     361  if( this->peerInfo->userId == userId)
     362    return this;
     363
     364
     365  NetworkNode* node = NULL;
     366  std::list<NetworkNode*>::const_iterator it = this->masterServerList.begin();
     367
     368  for(; it != this->masterServerList.end(); it++)
     369  {
     370    node = (*it)->getNodeByUserId(userId);
     371    if( node != NULL)
     372      return node;
     373  }
     374
     375  it = this->activeProxyServerList.begin();
     376  for(; it != this->activeProxyServerList.end(); it++)
     377  {
     378    node = (*it)->getNodeByUserId(userId);
     379    if( node != NULL)
     380      return node;
     381  }
     382
     383  it = this->passiveProxyServerList.begin();
     384  for(; it != this->passiveProxyServerList.end(); it++)
     385  {
     386    node = (*it)->getNodeByUserId(userId);
     387    if( node != NULL)
     388      return node;
     389  }
     390
     391  it = this->clientList.begin();
     392  for(; it != this->clientList.end(); it++)
     393  {
     394    node = (*it)->getNodeByUserId(userId);
     395    if( node != NULL)
     396      return node;
    224397  }
    225398
     
    234407void NetworkNode::debug(int depth) const
    235408{
    236   PRINT(0)(" = %s\n", this->peerInfo->getNodeTypeString().c_str());
    237 
    238   PRINT(0)("    master servers: %i\n", this->masterServerList.size());
    239   std::list<PeerInfo*>::const_iterator it = this->masterServerList.begin();
    240   for(; it != this->masterServerList.end(); it++)
    241   {
    242     IP* ip = &(*it)->ip;
    243     PRINT(0)("     - ms, id: %i (%s)\n", (*it)->userId, ip->ipString().c_str());
    244   }
    245 
    246   PRINT(0)("    proxy servers active: %i\n", this->activeProxyServerList.size());
    247   it = this->activeProxyServerList.begin();
    248   for(; it != this->activeProxyServerList.end(); it++)
    249   {
    250     IP* ip = &(*it)->ip;
    251     PRINT(0)("     - ps-a, id: %i (%s)\n", (*it)->userId, ip->ipString().c_str());
    252   }
    253 
    254   PRINT(0)("    proxy servers passive: %i\n", this->passiveProxyServerList.size());
    255   it = this->passiveProxyServerList.begin();
    256   for(; it != this->passiveProxyServerList.end(); it++)
    257   {
    258     IP* ip = &(*it)->ip;
    259     PRINT(0)("     - ps-p, id: %i (%s)\n", (*it)->userId, ip->ipString().c_str());
    260   }
    261 
    262   PRINT(0)("    clients: %i\n", this->clientList.size());
    263   it = this->clientList.begin();
    264   for(; it != this->clientList.end(); it++)
    265   {
    266     IP* ip = &(*it)->ip;
    267     PRINT(0)("     - client, id: %i (%s)\n", (*it)->userId, ip->ipString().c_str());
    268   }
    269 }
    270 
     409  char indent[depth +1];
     410  for( int i = 0; i < depth; i++) {     indent[i] = ' ';  }
     411  indent[depth] = '\0';
     412
     413  PRINT(0)("%s + %s, with id %i and ip: %s\n", indent, this->peerInfo->getNodeTypeString().c_str(), this->peerInfo->userId, this->peerInfo->ip.ipString().c_str());
     414
     415
     416
     417  std::list<NetworkNode*>::const_iterator it;
     418  if( !this->masterServerList.empty())
     419  {
     420    it = this->masterServerList.begin();
     421
     422    for(; it != this->masterServerList.end(); it++)
     423    {
     424      (*it)->debug(depth+1);
     425    }
     426  }
     427
     428  if( !this->activeProxyServerList.empty())
     429  {
     430    it = this->activeProxyServerList.begin();
     431
     432    for(; it != this->activeProxyServerList.end(); it++)
     433    {
     434      (*it)->debug(depth+1);
     435    }
     436  }
     437
     438
     439  if( !this->passiveProxyServerList.empty())
     440  {
     441    it = this->passiveProxyServerList.begin();
     442
     443    for(; it != this->passiveProxyServerList.end(); it++)
     444    {
     445      (*it)->debug(depth+1);
     446    }
     447  }
     448
     449  if( !this->clientList.empty())
     450  {
     451    it = this->clientList.begin();
     452
     453    for(; it != this->clientList.end(); it++)
     454    {
     455      (*it)->debug(depth+1);
     456    }
     457  }
     458}
     459
  • trunk/src/lib/network/monitor/network_node.h

    r9494 r9656  
    1313#include <list>
    1414
    15 
    1615//!< a class representing a node in the network (this can be a MASTER_SERVER, PROXY_SERVER or a CLIENT
    1716class NetworkNode
     
    2221
    2322
    24     void addClient(PeerInfo* node);
    25     void addActiveProxyServer(PeerInfo* node);
    26     void addPassiveProxyServer(PeerInfo* node);
    27     void addMasterServer(PeerInfo* node);
     23    void addClient(NetworkNode* node);
     24    void addActiveProxyServer(NetworkNode* node);
     25    void addPassiveProxyServer(NetworkNode* node);
     26    void addMasterServer(NetworkNode* node);
    2827
    29     void removeClient(PeerInfo* node);
    30     void removeActiveProxyServer(PeerInfo* node);
    31     void removePassiveProxyServer(PeerInfo* node);
    32     void removeMasterServer(PeerInfo* node);
     28    void removeClient(NetworkNode* node);
     29    void removeActiveProxyServer(NetworkNode* node);
     30    void removePassiveProxyServer(NetworkNode* node);
     31    void removeMasterServer(NetworkNode* node);
     32
     33    void removeClient(int userId);
     34    void removeActiveProxyServer(int userId);
     35    void removePassiveProxyServer(int userId);
     36    void removeMasterServer(int userId);
     37
    3338
    3439    PeerInfo* getClient(int index) const;
     
    3843
    3944    /** @returns the master server list */
    40     inline std::list<PeerInfo*> getMasterServer() const { return this->masterServerList; }
     45    inline std::list<NetworkNode*> getMasterServers() const { return this->masterServerList; }
    4146    /** @returns the active proxy server list */
    42     inline std::list<PeerInfo*> getActiveProxyServer() const { return this->activeProxyServerList; }
     47    inline std::list<NetworkNode*> getActiveProxyServers() const { return this->activeProxyServerList; }
    4348    /** @returns the passive proxy server list */
    44     inline std::list<PeerInfo*> getPassiveProxyServer() const { return this->passiveProxyServerList; }
     49    inline std::list<NetworkNode*> getPassiveProxyServers() const { return this->passiveProxyServerList; }
    4550    /** @returns the client list */
    46     inline std::list<PeerInfo*> getClient() const { return this->clientList; }
     51    inline std::list<NetworkNode*> getClients() const { return this->clientList; }
    4752
     53    PeerInfo* getPeerByUserId( int userId);
    4854
    4955    /** @returns the number of players */
     
    5359    /** @returns the peer info of this node */
    5460    inline PeerInfo* getPeerInfo() const { return this->peerInfo; }
     61
     62    NetworkNode* getNodeByUserId( int userId);
    5563
    5664    void debug(int depth) const;
     
    6371
    6472    /* network nodes directly connected to this node */
    65     std::list<PeerInfo*>         clientList;                   //!< list of all clients in the network
    66     std::list<PeerInfo*>         activeProxyServerList;        //!< list of all proxy servers in the network
    67     std::list<PeerInfo*>         passiveProxyServerList;       //!< list of all proxy servers in the network
    68     std::list<PeerInfo*>         masterServerList;             //!< list of all master servers in the network (should be 1!! :D)
     73    std::list<NetworkNode*>         clientList;                   //!< list of all clients in the network
     74    std::list<NetworkNode*>         activeProxyServerList;        //!< list of all proxy servers in the network
     75    std::list<NetworkNode*>         passiveProxyServerList;       //!< list of all proxy servers in the network
     76    std::list<NetworkNode*>         masterServerList;             //!< list of all master servers in the network (should be 1!! :D)
    6977
    7078};
  • trunk/src/lib/network/monitor/network_stats_widget.cc

    r9494 r9656  
    1818#include "network_stats_widget.h"
    1919#include "network_monitor.h"
     20#include "peer_info.h"
    2021
    2122#include "multi_type.h"
     
    2324#include "shell_command.h"
    2425
    25 // SHELL_COMMAND(gui, NetworkMonitor, toggleGUI)
    26 //  ->setAlias("ProxyGui");
     26#include "loading/resource_manager.h"
     27
     28// this fcuk does not work!
     29// SHELL_COMMAND(gui, NetworkStatsWidget, toggleGUI)
     30// ->setAlias("ProxyGui");
    2731
    2832
     
    3034    : GLGuiBox(OrxGui::Horizontal)
    3135{
     36  this->init();
     37
    3238  this->setName(name);
    3339  this->setIP(ip);
    3440
     41}
     42
     43HostWidget::HostWidget(const PeerInfo* peerInfo)
     44    : GLGuiBox(OrxGui::Horizontal)
     45{
     46  this->init();
     47  if (peerInfo == NULL)
     48  {
     49    this->setName("INVALID");
     50    return;
     51  }
     52  this->setName(peerInfo->getNodeTypeString() + "ID: " + MultiType(peerInfo->userId).getString());
     53  this->setIP(peerInfo->ip);
     54}
     55
     56void HostWidget::init()
     57{
     58  if(_font == NULL)
     59    _font = new Font(ResourceManager::getInstance()->getDataDir() + "/fonts/arial.ttf", 20);
     60
     61  //this->_name.setFont(*_font);
     62  this->_name.setTextSize(15);
     63  //this->_ip.setFont(*_font);
     64  this->_ip.setTextSize(15);
     65
    3566  this->pack(&this->_name);
    3667  this->pack(&this->_ip);
     
    4980}
    5081
     82Font* HostWidget::_font = NULL;
     83
     84
    5185
    5286
     
    5488
    5589
    56 ProxyWidget::ProxyWidget(const std::string& proxyName, const IP& ip)
     90NodeWidget::NodeWidget(const std::string& proxyName, const IP& ip)
    5791    : _proxyWidget(proxyName, ip)
    5892{
    59   this->_clientNameWidth = 100.0f;
     93  this->_nodeNameWidth = 100.0f;
    6094  this->pack(&_proxyWidget);
    6195}
    6296
    63 void ProxyWidget::addClient(const std::string& name, const IP& ip)
     97NodeWidget::NodeWidget(const NetworkNode* node)
     98    : _proxyWidget(node->getPeerInfo())// "node", node->getPeerInfo()->ip)
     99{
     100  this->_nodeNameWidth = 100.0f;
     101  this->pack(&_proxyWidget);
     102
     103  std::list<NetworkNode*> list = node->getMasterServers();
     104  std::list<NetworkNode*>::const_iterator it;
     105
     106  for(it = list.begin(); it != list.end(); it++)
     107    this->addNode(*it);
     108
     109  list = node->getActiveProxyServers();
     110  for(it = list.begin(); it != list.end(); it++)
     111    this->addNode(*it);
     112
     113  list = node->getPassiveProxyServers();
     114  for(it = list.begin(); it != list.end(); it++)
     115    this->addNode(*it);
     116
     117  list = node->getClients();
     118  for(it = list.begin(); it != list.end(); it++)
     119    this->addNode(*it);
     120}
     121
     122
     123void NodeWidget::addNode(const NetworkNode* node)
     124{
     125  this->_nodes.push_back(new NodeWidget(node));
     126  this->pack(this->_nodes.back());
     127  this->_nodes.back()->show();
     128}
     129
     130
     131void NodeWidget::addNode(const std::string& name, const IP& ip)
    64132{
    65133  HostWidget* newClient = new HostWidget(name, ip);
    66   newClient->setNameWidth(this->_clientNameWidth);
     134  newClient->setNameWidth(this->_nodeNameWidth);
    67135
    68136  this->pack(newClient);
     
    72140}
    73141
    74 bool ProxyWidget::removeClient(const IP& ip)
    75 {
    76   std::vector<HostWidget*>::iterator rmIt;
    77   for(rmIt = this->_clients.begin(); rmIt != this->_clients.end(); ++rmIt)
    78   {
    79     if (*(*rmIt) == ip)
    80     {
    81       delete (*rmIt);
    82       this->_clients.erase(rmIt);
    83       return true;
    84     }
    85   }
    86   return false;
    87 }
    88 
    89 bool ProxyWidget::removeClient(const std::string& name)
    90 {
    91   std::vector<HostWidget*>::iterator rmIt;
    92   for(rmIt = this->_clients.begin(); rmIt != this->_clients.end(); ++rmIt)
    93   {
    94     if (*(*rmIt) == name)
    95     {
    96       delete (*rmIt);
    97       this->_clients.erase(rmIt);
    98       return true;
    99     }
    100   }
    101   return false;
    102 
    103 }
    104 
    105 bool ProxyWidget::removeClient(const std::string& name, const IP& ip)
    106 {
    107   std::vector<HostWidget*>::iterator rmIt;
    108   for(rmIt = this->_clients.begin(); rmIt != this->_clients.end(); ++rmIt)
    109   {
    110     if (*(*rmIt) == ip && *(*rmIt) == name)
    111     {
    112       delete (*rmIt);
    113       this->_clients.erase(rmIt);
    114       return true;
    115     }
    116   }
    117   return false;
    118 }
    119 
    120 
    121 void ProxyWidget::setClientNameWidths(float width)
    122 {
    123   this->_clientNameWidth = width;
    124   for (unsigned int i = 0; i < this->_clients.size(); ++i)
    125     this->_clients[i]->setNameWidth(width);
    126 }
    127 
    128 void ProxyWidget::hiding()
     142bool NodeWidget::removeNode(const IP& ip)
     143{
     144//   std::vector<HostWidget*>::iterator rmIt;
     145//   for(rmIt = this->_nodes.begin(); rmIt != this->_nodes.end(); ++rmIt)
     146//   {
     147//     if (*(*rmIt) == ip)
     148//     {
     149//       delete (*rmIt);
     150//       this->_nodes.erase(rmIt);
     151//       return true;
     152//     }
     153//   }
     154//   return false;
     155}
     156
     157bool NodeWidget::removeNode(const std::string& name)
     158{
     159//   std::vector<HostWidget*>::iterator rmIt;
     160//   for(rmIt = this->_nodes.begin(); rmIt != this->_nodes.end(); ++rmIt)
     161//   {
     162//     if (*(*rmIt) == name)
     163//     {
     164//       delete (*rmIt);
     165//       this->_nodes.erase(rmIt);
     166//       return true;
     167//     }
     168//   }
     169//   return false;
     170
     171}
     172
     173bool NodeWidget::removeNode(const std::string& name, const IP& ip)
     174{
     175//   std::vector<HostWidget*>::iterator rmIt;
     176//   for(rmIt = this->_nodes.begin(); rmIt != this->_nodes.end(); ++rmIt)
     177//   {
     178//     if (*(*rmIt) == ip && *(*rmIt) == name)
     179//     {
     180//       delete (*rmIt);
     181//       this->_nodes.erase(rmIt);
     182//       return true;
     183//     }
     184//   }
     185//   return false;
     186}
     187
     188
     189void NodeWidget::setNodeNameWidths(float width)
     190{
     191/*  this->_nodeNameWidth = width;
     192  for (unsigned int i = 0; i < this->_nodes.size(); ++i)
     193    this->_nodes[i]->setNameWidth(width);*/
     194}
     195
     196void NodeWidget::hiding()
    129197{
    130198  this->_proxyWidget.hide();
    131   for (unsigned int i = 0; i < this->_clients.size(); ++i)
    132     this->_clients[i]->hide();
    133 }
    134 
    135 void ProxyWidget::showing()
     199  for (unsigned int i = 0; i < this->_nodes.size(); ++i)
     200    this->_nodes[i]->hide();
     201}
     202
     203void NodeWidget::showing()
    136204{
    137205  this->_proxyWidget.show();
    138   for (unsigned int i = 0; i < this->_clients.size(); ++i)
    139     this->_clients[i]->show();
     206  for (unsigned int i = 0; i < this->_nodes.size(); ++i)
     207    this->_nodes[i]->show();
    140208}
    141209
     
    147215 */
    148216NetworkStatsWidget::NetworkStatsWidget(const NetworkMonitor* monitor)
    149     : GLGuiBox(OrxGui::Vertical), _thisHost("myName", IP(127, 0, 0 , 1))
     217    : OrxGui::GLGuiFixedpositionBox(OrxGui::Center, OrxGui::Vertical), _thisHost("myName", IP(127, 0, 0 , 1))
    150218{
    151219  this->_monitor = monitor;
     220  this->_passedTime = 0.0f;
    152221
    153222  /*
     
    169238  this->_bar.setChangedValueColor(Color::black);
    170239  */
     240  this->_thisHostIs.setText(std::string("I am ") + _monitor->getLocalNode()->getPeerInfo()->getNodeTypeString());
     241
     242  this->pack(&this->_thisHostIs);
     243
    171244  this->pack(&this->_thisHost);
     245
     246  this->pack(&this->_serverBox);
    172247
    173248  this->pack(&this->_upstreamText);
    174249  this->pack(&this->_downstreamText);
    175250
    176   this->pack(&this->_serverIP);
     251
     252  this->rebuild();
    177253}
    178254
     
    183259NetworkStatsWidget::~NetworkStatsWidget ()
    184260{}
     261
     262
     263void NetworkStatsWidget::addNode(const NetworkNode* node)
     264{
     265  this->_proxies.push_back(new NodeWidget(node));
     266  this->_serverBox.pack(this->_proxies.back());
     267  this->_proxies.back()->show();
     268}
     269
     270
     271
     272
     273NetworkStatsWidget* NetworkStatsWidget::_statsWidget = NULL;
     274
     275#include "class_list.h"
     276
     277void NetworkStatsWidget::toggleGUI()
     278{
     279  BaseObject* bo = NULL;
     280  const std::list<BaseObject*>* ls = ClassList::getList(CL_NETWORK_MONITOR);
     281  if (ls != NULL && !ls->empty())
     282    bo = ls->front();
     283
     284  if (bo != NULL && NetworkStatsWidget::_statsWidget == NULL)
     285  {
     286    NetworkStatsWidget::_statsWidget = new NetworkStatsWidget(dynamic_cast<NetworkMonitor*> (bo));
     287    NetworkStatsWidget::_statsWidget->showAll();
     288  }
     289  else
     290  {
     291    delete NetworkStatsWidget::_statsWidget;
     292    NetworkStatsWidget::_statsWidget = NULL;
     293  }
     294}
    185295
    186296
     
    204314
    205315
     316void NetworkStatsWidget::addProxy(const std::string& name, const IP& proxy)
     317{}
     318
     319void NetworkStatsWidget::clearProxies()
     320{}
     321
     322
     323void NetworkStatsWidget::rebuild()
     324{
     325  while (!this->_proxies.empty())
     326  {
     327    delete this->_proxies.back();
     328    this->_proxies.pop_back();
     329  }
     330
     331  const NetworkNode* node = this->_monitor->getLocalNode();
     332  if (node == NULL)
     333  {
     334    printf("NO NODE\n");
     335    return;
     336  }
     337
     338  this->addNode(node);
     339}
     340
     341
     342
    206343void NetworkStatsWidget::tick(float dt)
    207344{
     345
     346  if ((_passedTime+= dt) > 1.0f)
     347  {
     348    this->_passedTime = 0.0f;
     349    this->rebuild();
     350  }
     351
    208352  assert (this->_monitor->getLocalNode() != NULL);
    209353  assert(this->_monitor->getLocalNode()->getPeerInfo() != NULL);
     
    220364void NetworkStatsWidget::resize()
    221365{
    222   GLGuiBox::resize();
     366  GLGuiFixedpositionBox::resize();
    223367}
    224368
  • trunk/src/lib/network/monitor/network_stats_widget.h

    r9494 r9656  
    22 * @file network_stats_widget.h
    33 * @brief Definition of an EnergyWidget, that displays a bar and a Text
    4 */
     4 */
    55
    66#ifndef _NETWORK_STATS_WIDGET_H
    77#define _NETWORK_STATS_WIDGET_H
    88
    9 #include "glgui_box.h"
     9#include "glgui_fixedposition_box.h"
    1010#include "glgui_bar.h"
    1111#include "glgui_text.h"
     12#include "glgui_pushbutton.h"
    1213
    1314#include "network/ip.h"
    1415
    1516class NetworkMonitor;
    16 
     17class NetworkNode;
     18class PeerInfo;
    1719
    1820class HostWidget : public OrxGui::GLGuiBox
     
    2022  public:
    2123    HostWidget(const std::string& name, const IP& ip);
    22     ~HostWidget() {};
     24    HostWidget(const PeerInfo* peerInfo);
    2325
    2426    void setName(const std::string& name) { this->_name.setText(name); };
    25     void setIP(const IP& ip) { this->_ip.setText(ip.ipString()); this->_storedIP = ip; };
     27    void setIP(const IP& ip) { this->_ip.setText(std::string("at ") + ip.ipString()); this->_storedIP = ip; };
    2628
    2729    void setNameWidth(float width) { this->_name.setLineWidth(width); };
     
    3537
    3638  private:
     39    void init();
     40  private:
    3741    OrxGui::GLGuiText _name;           //!< The Name of the Proxy server to be displayed.
    3842    OrxGui::GLGuiText _ip;             //!< The IP of the proxy server.
    3943    IP                _storedIP;       //!< The ip to compare.
     44
     45    static Font*      _font;
    4046};
    4147
    4248
    43 class ProxyWidget : public OrxGui::GLGuiBox
     49class NodeWidget : public OrxGui::GLGuiBox
    4450{
    4551  public:
    46     ProxyWidget(const std::string& proxyName, const IP& ip);
     52    NodeWidget(const std::string& proxyName, const IP& ip);
     53    NodeWidget(const NetworkNode* node);
    4754
    48     void addClient(const std::string& name, const IP& ip);
     55    void addNode(const NetworkNode* node);
     56    void addNode(const std::string& name, const IP& ip);
    4957
    50     bool removeClient(const IP& ip);
    51     bool removeClient(const std::string& name);
    52     bool removeClient(const std::string& name, const IP& ip);
     58    bool removeNode(const IP& ip);
     59    bool removeNode(const std::string& name);
     60    bool removeNode(const std::string& name, const IP& ip);
    5361
    54     void setClientNameWidths(float width);
     62    void setNodeNameWidths(float width);
    5563
    5664
     
    6371    HostWidget                _proxyWidget;
    6472
    65     std::vector<HostWidget*>  _clients;
    66     float                     _clientNameWidth;
     73    std::vector<NodeWidget*>  _nodes;
     74    float                     _nodeNameWidth;
    6775};
    6876
     
    7179
    7280//! A class to display network Statistics.
    73 class NetworkStatsWidget : public OrxGui::GLGuiBox
     81class NetworkStatsWidget : public OrxGui::GLGuiFixedpositionBox
    7482{
    7583  public:
     84    static void toggleGUI();
     85
    7686    NetworkStatsWidget(const NetworkMonitor* monitor);
    7787    virtual ~NetworkStatsWidget();
     
    8494
    8595    void addProxy(const std::string& name, const IP& proxy);
     96    void addNode(const NetworkNode* node);
    8697
     98    void clearProxies();
     99
     100    void rebuild();
    87101
    88102    //void rebuildConnectedHosts(std::vector<hosts> hosts);
     
    101115    const NetworkMonitor*  _monitor;
    102116
     117    OrxGui::GLGuiText      _thisHostIs;
    103118    HostWidget             _thisHost;
    104119
     
    106121    OrxGui::GLGuiText      _downstreamText;
    107122
    108     std::vector<HostWidget*>_connectedProxies;
     123    OrxGui::GLGuiBox       _serverBox;
    109124
    110     OrxGui::GLGuiText       _serverIP;
     125    std::vector<NodeWidget*> _proxies;
    111126
    112127
     128    static NetworkStatsWidget*    _statsWidget;
     129
     130
     131    float                   _passedTime;
    113132    //OrxGui::GLGuiText       _valueText;
    114133    //OrxGui::GLGuiBar        _bar;
  • trunk/src/lib/network/nettypes.h

    r9494 r9656  
    1010  PERMISSION_MASTER_SERVER = 1,
    1111  PERMISSION_PROXY_SERVER  = 2,
    12   PERMISSION_OWNER         = 4,
    13   PERMISSION_ALL           = 8
     12  PERMISSION_SERVER        = 4,
     13  PERMISSION_OWNER         = 8,
     14  PERMISSION_ALL           = 16
    1415};
    1516
  • trunk/src/lib/network/network_game_manager.cc

    r9494 r9656  
    6868
    6969  this->gameState = 0;
    70   registerVar( new SynchronizeableInt( &gameState, &gameState, "gameState" ) );
     70  registerVar( new SynchronizeableInt( &gameState, &gameState, "gameState", PERMISSION_MASTER_SERVER ) );
    7171}
    7272
     
    9191bool NetworkGameManager::signalNewPlayer( int userId )
    9292{
    93   assert( SharedNetworkData::getInstance()->isMasterServer() ||  SharedNetworkData::getInstance()->isProxyServerActive());
     93  assert( SharedNetworkData::getInstance()->isMasterServer());
    9494  assert( State::getGameRules() );
    9595  assert( State::getGameRules()->isA( CL_NETWORK_GAME_RULES ) );
     
    9797  NetworkGameRules & rules = *(dynamic_cast<NetworkGameRules*>(State::getGameRules()));
    9898
    99   int team = rules.getTeamForNewUser();
    100   ClassID playableClassId = rules.getPlayableClassId( userId, team );
    101   std::string playableModel = rules.getPlayableModelFileName( userId, team, playableClassId );
    102   std::string playableTexture = rules.getPlayableModelFileName( userId, team, playableClassId );
    103   float       playableScale = rules.getPlayableScale( userId, team, playableClassId );
     99  int          team = rules.getTeamForNewUser();
     100  ClassID      playableClassId = rules.getPlayableClassId( userId, team );
     101  std::string  playableModel = rules.getPlayableModelFileName( userId, team, playableClassId );
     102  std::string  playableTexture = rules.getPlayableModelFileName( userId, team, playableClassId );
     103  float        playableScale = rules.getPlayableScale( userId, team, playableClassId );
    104104
    105105  BaseObject * bo = Factory::fabricate( playableClassId );
     
    111111
    112112  playable.loadMD2Texture( playableTexture );
    113 
     113  playable.setTeam(team);
    114114  playable.loadModel( playableModel, 100.0f );
    115115  playable.setOwner( userId );
     
    159159/**
    160160 * handler for remove synchronizeable messages
    161  * @param messageId
     161 * @param messageType
    162162 * @param data
    163163 * @param dataLength
     
    166166 * @return true on successfull handling else handler will be called again
    167167 */
    168 bool NetworkGameManager::delSynchronizeableHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId )
     168bool NetworkGameManager::delSynchronizeableHandler( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId )
    169169{
    170170
     
    172172
    173173  if ( SharedNetworkData::getInstance()->isMasterServer() ||
    174        SharedNetworkData::getInstance()->isProxyServerActive() && SharedNetworkData::getInstance()->isUserClient(userId))
    175   {
    176     PRINTF(0)("Recieved DeleteSynchronizeable message from client %d!\n", userId);
     174       SharedNetworkData::getInstance()->isProxyServerActive() && SharedNetworkData::getInstance()->isUserClient(senderId))
     175  {
     176    PRINTF(0)("Recieved DeleteSynchronizeable message from client %d!\n", senderId);
    177177    return true;
    178178  }
     
    183183  if ( len != dataLength )
    184184  {
    185     PRINTF(2)("Recieved DeleteSynchronizeable message with incorrect size (%d) from client %d!\n", dataLength, userId);
     185    PRINTF(2)("Recieved DeleteSynchronizeable message with incorrect size (%d) from client %d!\n", dataLength, senderId);
    186186    return true;
    187187  }
     
    217217  assert( Converter::intToByteArray( uniqueId, buf, INTSIZE ) == INTSIZE );
    218218
    219   MessageManager::getInstance()->sendMessage( MSGID_DELETESYNCHRONIZEABLE, buf, INTSIZE, RT_ALL_BUT_ME, 0, MP_HIGHBANDWIDTH );
     219  MessageManager::getInstance()->sendMessage( MSGID_DELETESYNCHRONIZEABLE, buf, INTSIZE, RT_ALL_BUT_ME, NET_UNASSIGNED, MP_HIGHBANDWIDTH );
    220220}
    221221
     
    224224/**
    225225 * handler for MSGID_PREFEREDTEAM message
    226  * @param messageId
     226 * @param messageType
    227227 * @param data
    228228 * @param dataLength
     
    231231 * @return
    232232 */
    233 bool NetworkGameManager::preferedTeamHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId )
    234 {
    235   assert( SharedNetworkData::getInstance()->isMasterServer() ||  SharedNetworkData::getInstance()->isProxyServerActive());
     233bool NetworkGameManager::preferedTeamHandler( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId )
     234{
     235  assert( SharedNetworkData::getInstance()->isMasterServer() );
    236236
    237237  int teamId = 0;
     
    240240  if ( len != dataLength )
    241241  {
    242     PRINTF(2)("Recieved DeleteSynchronizeable message with incorrect size (%d) from client %d!\n", dataLength, userId);
     242    PRINTF(2)("Recieved DeleteSynchronizeable message with incorrect size (%d) from client %d!\n", dataLength, senderId);
    243243    return true;
    244244  }
    245245
    246   NetworkGameManager::getInstance()->setPreferedTeam( userId, teamId );
    247 
    248   return true;
    249 }
    250 
     246  PRINTF(0)("Client %i wishes to play in team %i\n", senderId, teamId);
     247  NetworkGameManager::getInstance()->setPreferedTeam( senderId, teamId );
     248
     249  return true;
     250}
     251
     252
     253/**
     254 * this actualy sets the new prefered team id
     255 * @param userId: the user that changes team
     256 * @param teamId: the new team id for the user
     257 */
    251258void NetworkGameManager::setPreferedTeam( int userId, int teamId )
    252259{
     
    259266}
    260267
     268
    261269/**
    262270 * set prefered team for this host
     
    265273void NetworkGameManager::prefereTeam( int teamId )
    266274{
    267   if ( SharedNetworkData::getInstance()->isMasterServer() /*|| SharedNetworkData::getInstance()->isProxyServerActive()*/)
    268     setPreferedTeam( SharedNetworkData::getInstance()->getHostID(), teamId );
     275  if ( SharedNetworkData::getInstance()->isMasterServer() )
     276    this->setPreferedTeam( SharedNetworkData::getInstance()->getHostID(), teamId );
    269277  else
    270278  {
     
    273281    assert( Converter::intToByteArray( teamId, buf, INTSIZE) == INTSIZE );
    274282
    275     MessageManager::getInstance()->sendMessage( MSGID_PREFEREDTEAM, buf, INTSIZE, RT_USER, 0, MP_HIGHBANDWIDTH );
     283    // send this message to the master server
     284    MessageManager::getInstance()->sendMessage( MSGID_PREFEREDTEAM, buf, INTSIZE, RT_USER, NET_ID_MASTER_SERVER, MP_HIGHBANDWIDTH );
    276285  }
    277286}
     
    306315
    307316
    308 bool NetworkGameManager::chatMessageHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId )
    309 {
    310   PRINTF(0)("NetworkGameManager::chatMessageHandler %d %d\n", userId, SharedNetworkData::getInstance()->getHostID() );
    311   if ( (SharedNetworkData::getInstance()->isMasterServer() /*|| SharedNetworkData::getInstance()->isProxyServerActive()*/) && userId !=  SharedNetworkData::getInstance()->getHostID() )
    312   {
    313     MessageManager::getInstance()->sendMessage( messageId, data, dataLength, RT_ALL_BUT_ME, 0, MP_HIGHBANDWIDTH );
     317bool NetworkGameManager::chatMessageHandler( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId )
     318{
     319  PRINTF(0)("NetworkGameManager::chatMessageHandler %d %d\n", senderId, SharedNetworkData::getInstance()->getHostID() );
     320  if ( (SharedNetworkData::getInstance()->isMasterServer() /*|| SharedNetworkData::getInstance()->isProxyServerActive()*/) && senderId !=  SharedNetworkData::getInstance()->getHostID() )
     321  {
     322    MessageManager::getInstance()->sendMessage( messageType, data, dataLength, RT_ALL_BUT_ME, NET_UNASSIGNED, MP_HIGHBANDWIDTH );
    314323  }
    315324
     
    321330  if ( dataLength < 3*INTSIZE )
    322331  {
    323     PRINTF(2)("got too small chatmessage from client %d\n", userId);
     332    PRINTF(2)("got too small chatmessage from client %d\n", senderId);
    324333
    325334    return true;
    326335  }
    327336
    328   int messageType = 0;
    329   Converter::byteArrayToInt( data, &messageType );
     337  int chatType = 0;
     338  Converter::byteArrayToInt( data, &chatType);
    330339  int senderUserId = 0;
    331340  Converter::byteArrayToInt( data+INTSIZE, &senderUserId );
     
    333342  Converter::byteArrayToString( data+2*INTSIZE, message, dataLength-2*INTSIZE );
    334343
    335   rules.handleChatMessage( senderUserId, message, messageType );
     344  rules.handleChatMessage( senderUserId, message, chatType);
    336345
    337346  return true;
     
    352361
    353362  if ( SharedNetworkData::getInstance()->isMasterServer() /*|| SharedNetworkData::getInstance()->isProxyServerActive()*/)
    354     MessageManager::getInstance()->sendMessage( MSGID_CHATMESSAGE, buf, message.length()+3*INTSIZE, RT_ALL_ME, 0, MP_HIGHBANDWIDTH );
     363    MessageManager::getInstance()->sendMessage( MSGID_CHATMESSAGE, buf, message.length()+3*INTSIZE, RT_ALL_ME, NET_UNASSIGNED, MP_HIGHBANDWIDTH );
    355364  else
    356     MessageManager::getInstance()->sendMessage( MSGID_CHATMESSAGE, buf, message.length()+3*INTSIZE, RT_ALL_BUT_ME, 0, MP_HIGHBANDWIDTH );
     365    MessageManager::getInstance()->sendMessage( MSGID_CHATMESSAGE, buf, message.length()+3*INTSIZE, RT_ALL_BUT_ME, NET_UNASSIGNED, MP_HIGHBANDWIDTH );
    357366
    358367
  • trunk/src/lib/network/network_game_manager.h

    r9406 r9656  
    1919class PNode;
    2020
    21 typedef enum NetworkGameManagerProtocol {
    22   NET_CREATE_ENTITY = 0,
    23   NET_REMOVE_ENTITY,
    24   NET_CREATE_ENTITY_LIST,
    25   NET_REMOVE_ENTITY_LIST,
    26   NET_REQUEST_CREATE,
    27   NET_REQUEST_REMOVE,
    28   NET_YOU_ARE_ENTITY,
    29   NET_REQUEST_ENTITY_LIST,
    3021
    31   NET_NUMBER
    32 };
    3322
    3423struct clientBuffer
     
    7059    NetworkGameManager();
    7160
    72     static bool delSynchronizeableHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId );
    73     static bool preferedTeamHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId );
    74     static bool chatMessageHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId );
     61    static bool delSynchronizeableHandler( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId );
     62    static bool preferedTeamHandler( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId );
     63    static bool chatMessageHandler( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId );
    7564
    7665    void setPreferedTeam( int userId, int teamId );
  • trunk/src/lib/network/network_manager.cc

    r9494 r9656  
    3131#include "network_log.h"
    3232#include "network_game_manager.h"
     33#include "proxy/proxy_control.h"
    3334
    3435
     
    3738
    3839SHELL_COMMAND(debug, NetworkManager, debug);
     40SHELL_COMMAND(redirTest, NetworkManager, setRedirectionTest);
     41
    3942
    4043
     
    111114  // create the network stream
    112115  this->networkStream = new NetworkStream(NET_MASTER_SERVER);
    113   this->networkStream->createServer( port, port + 1);
     116  this->networkStream->createServer( port, port + 1, port + 2);
    114117
    115118  // start the network game manager
    116119  this->networkStream->createNetworkGameManager();
     120
     121  // init the proxy control center
     122  ProxyControl::getInstance();
    117123
    118124  PRINTF(0)("Created Network Master Server\n");
     
    138144
    139145  // then start the server
    140   this->networkStream->createServer( port, port +1);
    141 
     146  this->networkStream->createServer( port, port + 1, port + 2);
    142147
    143148  // and to the other proxy servers also, this would be very nice if its works
    144 
    145 
    146   // start the network game manager
    147   //this->networkStream->createNetworkGameManager();
    148 
     149  /* put it here....*/
     150
     151  // init the proxy control center
     152  ProxyControl::getInstance();
    149153
    150154  PRINTF(0)("Created Network Proxy Server\n");
     
    168172  this->networkStream->connectToMasterServer( name, port);
    169173
     174
    170175  // and start the handshake
    171176  this->networkStream->startHandshake();
     177  // create the proxy control
     178  ProxyControl::getInstance();
    172179
    173180  PRINTF(0)("Created Network Client\n");
    174181  return 1;
     182}
     183
     184
     185/**
     186 * reconnects this client to another server
     187 * @param address new server address
     188 */
     189void NetworkManager::reconnectToServer(IP address)
     190{
     191  PRINTF(0)("Rec. reconnection command\n");
     192  this->networkStream->reconnectToServer(address);
    175193}
    176194
     
    216234  PRINT(0)("===========================================\n");
    217235}
     236
     237
     238void NetworkManager::setRedirectionTest()
     239{
     240  this->networkStream->setRedirectionTest();
     241}
     242
  • trunk/src/lib/network/network_manager.h

    r9494 r9656  
    3939    int createProxyServer( unsigned int port);
    4040
     41    void reconnectToServer(IP address);
     42
    4143    void connectSynchronizeable(Synchronizeable& sync);
    4244    void synchronize(float dtS);
    4345
    4446    void debug();
     47
     48    void setRedirectionTest();
     49
    4550
    4651
  • trunk/src/lib/network/network_stream.cc

    r9494 r9656  
    1111### File Specific:
    1212   main-programmer: Christoph Renner rennerc@ee.ethz.ch
    13    co-programmer:   Patrick Boenzli  boenzlip@orxonox.ethz.ch
     13   co-programmer:   Patrick Boenzli  patrick@orxonox.ethz.ch
    1414
    1515     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
    16      July 2006: some code rearangement and integration of the proxy server mechanism (boenzlip@ee.ethz.ch)
     16     July 2006: some code rearangement and integration of the proxy server mechanism (patrick@orxonox.ethz.ch)
    1717*/
    1818
     
    2020#define DEBUG_MODULE_NETWORK
    2121
     22#include "proxy/proxy_control.h"
    2223
    2324#include "base_object.h"
     
    8081      // init the shared network data
    8182      SharedNetworkData::getInstance()->setHostID(NET_ID_MASTER_SERVER);
     83      this->pInfo->userId = NET_ID_MASTER_SERVER;
     84      this->pInfo->nodeType = NET_MASTER_SERVER;
     85
    8286      break;
    8387    case NET_PROXY_SERVER_ACTIVE:
    8488      // init the shared network data
    8589      SharedNetworkData::getInstance()->setHostID(NET_ID_PROXY_SERVER_01);
     90      this->pInfo->nodeType = NET_PROXY_SERVER_ACTIVE;
     91
    8692      break;
    8793    case NET_PROXY_SERVER_PASSIVE:
    8894      // init the shared network data
    8995      SharedNetworkData::getInstance()->setHostID(NET_ID_PROXY_SERVER_01);
     96      this->pInfo->nodeType = NET_PROXY_SERVER_PASSIVE;
     97
    9098      break;
    9199    case NET_CLIENT:
    92100      SharedNetworkData::getInstance()->setHostID(NET_ID_UNASSIGNED);
     101      this->pInfo->nodeType = NET_CLIENT;
    93102      break;
    94103  }
     
    97106
    98107  // get the local ip address
    99   IPaddress ip;
    100   SDLNet_ResolveHost( &ip, NULL, 0);
     108  IP ip("localhost", 0);
    101109  this->pInfo->ip = ip;
    102110}
     
    112120  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
    113121  this->clientSocket = NULL;
     122  this->clientSoftSocket = NULL;
    114123  this->proxySocket = NULL;
    115124  this->networkGameManager = NULL;
     
    117126
    118127  this->pInfo = new PeerInfo();
    119   this->pInfo->userId = 0;
     128  this->pInfo->userId = NET_UID_UNASSIGNED;
    120129  this->pInfo->lastAckedState = 0;
    121130  this->pInfo->lastRecvedState = 0;
     131  this->pInfo->bLocal = true;
    122132
    123133  this->bRedirect = false;
    124134
    125135  this->currentState = 0;
     136  this->redirectionUID = NET_ID_MASTER_SERVER;
    126137
    127138  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
     
    142153  if ( this->clientSocket )
    143154  {
    144     clientSocket->close();
    145     delete clientSocket;
    146     clientSocket = NULL;
     155    this->clientSocket->close();
     156    delete this->clientSocket;
     157    this->clientSocket = NULL;
     158  }
     159  if ( this->clientSoftSocket )
     160  {
     161    this->clientSoftSocket->close();
     162    delete this->clientSoftSocket;
     163    this->clientSoftSocket = NULL;
    147164  }
    148165  if ( this->proxySocket)
     
    199216  this->peers[node].connectionMonitor = new ConnectionMonitor( NET_ID_MASTER_SERVER );
    200217  this->peers[node].ip = this->peers[node].socket->getRemoteAddress();
     218  this->peers[node].bLocal = true;
    201219}
    202220
     
    218236  this->peers[proxyId].connectionMonitor = new ConnectionMonitor( proxyId );
    219237  this->peers[proxyId].ip = this->peers[proxyId].socket->getRemoteAddress();
     238  this->peers[proxyId].bLocal = true;
    220239}
    221240
     
    225244 * @param port: interface port for all clients
    226245 */
    227 void NetworkStream::createServer(int clientPort, int proxyPort)
     246void NetworkStream::createServer(int clientPort, int proxyPort, int clientSoftPort)
    228247{
    229248  PRINTF(0)(" Creating new Server: listening for clients on port %i and for proxies on port %i", clientPort, proxyPort);
    230249  this->clientSocket= new UdpServerSocket(clientPort);
     250  this->clientSoftSocket= new UdpServerSocket(clientSoftPort);
    231251  this->proxySocket = new UdpServerSocket(proxyPort);
    232252}
     
    255275  Handshake* hs = new Handshake(this->pInfo->nodeType);
    256276  // fake the unique id
    257   hs->setUniqueID( NET_UID_HANDSHAKE );
    258   assert( peers[userId].handshake == NULL );
    259   peers[userId].handshake = hs;
     277  hs->setUniqueID( userId);
     278  assert( this->peers[userId].handshake == NULL );
     279  this->peers[userId].handshake = hs;
     280  this->peers[userId].bLocal = true;
    260281
    261282  // set the preferred nick name
     
    301322  // create the network monitor after all the init work and before there is any connection handlings
    302323  if( this->networkMonitor == NULL)
     324  {
    303325    this->networkMonitor = new NetworkMonitor(this);
     326    SharedNetworkData::getInstance()->setNetworkMonitor( this->networkMonitor);
     327  }
    304328
    305329
     
    318342    if ( this->clientSocket )
    319343      this->clientSocket->update();
     344    if ( this->clientSoftSocket)
     345      this->clientSoftSocket->update();
    320346    if( this->proxySocket)
    321347      this->proxySocket->update();
     
    328354    if ( this->clientSocket )
    329355      this->clientSocket->update();
     356    if ( this->clientSoftSocket)
     357      this->clientSoftSocket->update();
    330358    if( this->proxySocket)
    331359      this->proxySocket->update();
     
    348376    if( this->bRedirect)
    349377    {
    350       this->handleReconnect( NET_ID_MASTER_SERVER);
     378      this->handleReconnect( this->redirectionUID);
    351379    }
    352380  }
     
    362390  this->handleDownstream( tick );
    363391  this->handleUpstream( tick );
     392
     393  // process the local data of the message manager
     394  MessageManager::getInstance()->processData();
     395
     396  if( this->bSoftRedirect)
     397    this->softReconnectToServer(0, IP("localhost", 10001));
    364398}
    365399
     
    385419    if ( tempNetworkSocket )
    386420    {
    387       // determine the network node id
    388       if ( freeSocketSlots.size() > 0 )
     421      // get a userId
     422//       if ( freeSocketSlots.size() > 0 )
     423//       {
     424//         // this should never be called
     425//         userId = freeSocketSlots.back();
     426//         freeSocketSlots.pop_back();
     427//       }
     428//       else
    389429      {
    390         userId = freeSocketSlots.back();
    391         freeSocketSlots.pop_back();
    392       }
    393       else
    394       {
    395         userId = 1;
     430        // each server (proxy and master) have an address space for new network nodes of 1000 nodes
     431        // the first NET_ID_PROXY_MAX are always reserved for proxy servers
     432        userId = SharedNetworkData::getInstance()->getHostID() * 1000 + NET_ID_PROXY_MAX + 1;
    396433
    397434        for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
    398435          if ( it->first >= userId )
    399436            userId = it->first + 1;
     437
     438        // make sure that this server only uses an address space of 1000
     439        assert( userId < (SharedNetworkData::getInstance()->getHostID() + 1) * 1000);
    400440      }
    401441      // this creates a new entry in the peers list
     
    410450  }
    411451
     452  if( this->clientSoftSocket != NULL)
     453  {
     454    tempNetworkSocket = this->clientSoftSocket->getNewSocket();
     455
     456    // we got new NET_CLIENT connecting
     457    if ( tempNetworkSocket )
     458    {
     459
     460      // this creates a new entry in the peers list
     461      peers[userId].socket = tempNetworkSocket;
     462      peers[userId].nodeType = NET_CLIENT;
     463
     464      // handle the newly connected client
     465      this->handleSoftConnect(userId);
     466
     467      PRINTF(0)("New Client softly connected: %d :D\n", userId);
     468    }
     469  }
     470
    412471
    413472  if( this->proxySocket != NULL)
     
    419478    {
    420479      // determine the network node id
    421       if ( freeSocketSlots.size() > 0 )
    422       {
    423         userId = freeSocketSlots.back();
    424         freeSocketSlots.pop_back();
    425       }
    426       else
     480//       if ( freeSocketSlots.size() > 0 )
     481//       {
     482//         userId = freeSocketSlots.back();
     483//         freeSocketSlots.pop_back();
     484//       }
     485//       else
    427486      {
    428487        userId = 1;
    429488
    430         for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
    431           if ( it->first >= userId )
    432             userId = it->first + 1;
     489        // find an empty slot within the range
     490        for( int i = 0; i < NET_ID_PROXY_MAX; i++)
     491        {
     492          if( this->peers.find( i) == this->peers.end())
     493          {
     494            userId = i;
     495            break;
     496          }
     497        }
     498
     499//         for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
     500//           if ( it->first >= userId )
     501//             userId = it->first + 1;
    433502      }
    434503
     
    443512    }
    444513  }
     514
    445515
    446516
     
    461531      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
    462532
     533
    463534      this->handleDisconnect( it->second.userId);
     535
     536      if( SharedNetworkData::getInstance()->isProxyServerActive())
     537        ProxyControl::getInstance()->signalLeaveClient(it->second.userId);
    464538
    465539      it++;
     
    469543    it++;
    470544  }
    471 
    472 
    473545}
    474546
     
    481553{
    482554  // create new handshake and init its variables
    483   peers[userId].handshake = new Handshake(this->pInfo->nodeType, userId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
    484   peers[userId].handshake->setUniqueID(userId);
    485 
    486   peers[userId].connectionMonitor = new ConnectionMonitor( userId );
    487   peers[userId].userId = userId;
     555  this->peers[userId].handshake = new Handshake(this->pInfo->nodeType, userId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
     556  this->peers[userId].handshake->setUniqueID(userId);
     557
     558  this->peers[userId].connectionMonitor = new ConnectionMonitor( userId );
     559  this->peers[userId].userId = userId;
     560  this->peers[userId].bLocal = true;
    488561
    489562  PRINTF(0)("num sync: %d\n", synchronizeables.size());
     
    494567  if( pi != NULL)
    495568  {
    496     peers[userId].handshake->setProxy1Address( pi->ip);
     569    this->peers[userId].handshake->setProxy1Address( pi->ip);
    497570  }
    498571  pi = this->networkMonitor->getSecondChoiceProxy();
    499572  if( pi != NULL)
    500     peers[userId].handshake->setProxy2Address( pi->ip);
     573    this->peers[userId].handshake->setProxy2Address( pi->ip);
    501574
    502575  // check if the connecting client should reconnect to a proxy server
    503576  if( SharedNetworkData::getInstance()->isMasterServer())
    504     peers[userId].handshake->setRedirect(/*this->networkMonitor->isReconnectNextClient()*/false);
     577  {
     578    if( this->networkMonitor->isReconnectNextClient())
     579    {
     580      this->peers[userId].handshake->setRedirect(true);
     581      PRINTF(0)("forwarding client to proxy server because this server is saturated\n");
     582    }
     583  }
    505584
    506585  // the connecting node of course is a client
    507   peers[userId].ip = peers[userId].socket->getRemoteAddress();
    508 }
     586  this->peers[userId].ip = this->peers[userId].socket->getRemoteAddress();
     587}
     588
     589
     590/**
     591 * this handles new soft connections
     592 * @param userId: the id of the new user node
     593 *
     594 * soft connections are connections from clients that are already in the network and don't need a new handshake etc.
     595 * the state of all entitites owned by userId are not deleted and stay
     596 * soft connections can not be redirected therefore they are negotiated between the to parties
     597 */
     598void NetworkStream::handleSoftConnect( int userId)
     599{
     600  // create new handshake and init its variables
     601  this->peers[userId].handshake = NULL;
     602  this->peers[userId].handshake->setUniqueID(userId);
     603
     604  this->peers[userId].connectionMonitor = new ConnectionMonitor( userId );
     605  this->peers[userId].userId = userId;
     606  this->peers[userId].bLocal = true;
     607
     608  PRINTF(0)("num sync: %d\n", synchronizeables.size());
     609
     610  // the connecting node of course is a client
     611  this->peers[userId].ip = this->peers[userId].socket->getRemoteAddress();
     612}
     613
    509614
    510615
     
    524629    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
    525630  }
     631
     632  PRINT(0)(" Current number of connections is: %i\n", this->peers.size());
     633  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
     634  {
     635    PRINT(0)("  peers[%i] with uniqueId %i and address: %s\n", it->first, it->second.userId, it->second.ip.ipString().c_str());
     636  }
     637  PRINT(0)("\n\n");
     638
    526639
    527640  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
     
    576689            // - client       <==> master server
    577690            // - proxy server <==> master server
    578             if(  SharedNetworkData::getInstance()->isClient() || SharedNetworkData::getInstance()->isProxyServerActive() && it->second.isMasterServer())
     691            if(  SharedNetworkData::getInstance()->isClient() ||
     692                 SharedNetworkData::getInstance()->isProxyServerActive() &&
     693                 SharedNetworkData::getInstance()->isUserMasterServer(it->second.userId))
    579694            {
    580               PRINTF(0)("Handshake: i am in client role\n");
     695              PRINTF(4)("Handshake: i am in client role\n");
    581696
    582697              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
    583698              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
    584699
    585 #warning the ip address is not set here because it results in a segfault when connecting to a proxy server => trace this later
    586700//               it->second.ip = it->second.socket->getRemoteAddress();
    587701
    588               // it->second.nodeType = it->second.handshake->getRemoteNodeType();
     702              it->second.nodeType = it->second.handshake->getRemoteNodeType();
    589703              // it->second.ip = it->second.socket->getRemoteAddress();
    590704              // add the new server to the nodes list (it can be a NET_MASTER_SERVER or NET_PROXY_SERVER)
     
    633747              else if ( SharedNetworkData::getInstance()->isProxyServerActive() && it->second.isClient() )
    634748              {
    635                 PRINTF(0)("Handshake: i am in server role\n");
     749                PRINTF(4)("Handshake: Proxy in server role: connecting %i\n", it->second.userId);
    636750
    637751                it->second.ip = it->second.socket->getRemoteAddress();
     
    639753                this->networkMonitor->addNode(&it->second);
    640754
    641                 this->handleNewClient( it->second.userId );
     755                // work with the ProxyControl to init the new client
     756                ProxyControl::getInstance()->signalNewClient( it->second.userId);
    642757
    643758                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
     
    667782/**
    668783 * this functions handles a reconnect event received from the a NET_MASTER_SERVER or NET_PROXY_SERVER
     784 * @param userId
    669785 */
    670786void NetworkStream::handleReconnect(int userId)
    671787{
    672788  this->bRedirect = false;
     789#warning this peer will be created if it does not yet exist: dangerous
    673790  PeerInfo* pInfo = &this->peers[userId];
     791
     792  IP proxyIP;
     793  if( this->networkMonitor->isForcedReconnection())
     794    proxyIP = this->networkMonitor->getForcedReconnectionIP();
     795  else
     796    proxyIP = pInfo->handshake->getProxy1Address();
    674797
    675798  PRINTF(0)("===============================================\n");
    676799  PRINTF(0)("Client is redirected to the other proxy servers\n");
    677800  PRINTF(0)("  user id: %i\n", userId);
    678   PRINTF(0)("  connecting to: %s\n", this->networkMonitor->getFirstChoiceProxy()->ip.ipString().c_str());
     801  PRINTF(0)("  connecting to: %s\n", proxyIP.ipString().c_str());
    679802  PRINTF(0)("===============================================\n");
    680803
     
    683806  pInfo->lastRecvedState = 0;
    684807
    685   // temp save the ip address here
    686   IP proxyIP = pInfo->handshake->getProxy1Address();
    687 
    688808  // disconnect from the current server and reconnect to proxy server
    689809  this->handleDisconnect( userId);
    690810  this->connectToProxyServer(NET_ID_PROXY_SERVER_01, proxyIP.ipString(), 9999);
     811//   this->connectToMasterServer(proxyIP.ipString(), 9999);
    691812  #warning the ports are not yet integrated correctly in the ip class
    692813
     
    696817
    697818
     819
     820/**
     821 * reconnects to another server, with full handshake
     822 * @param address of the new server
     823 */
     824void NetworkStream::reconnectToServer(IP address)
     825{
     826  ///TODO make a redirection struct and push it to the network monitor
     827  this->networkMonitor->setForcedReconnection(address);
     828
     829  // reconnect (depending on how we are connected at the moment)
     830  if ( peers.find( NET_ID_MASTER_SERVER) != peers.end() )
     831    this->redirectionUID = NET_ID_MASTER_SERVER;
     832  else if( peers.find( NET_ID_PROXY_SERVER_01) != peers.end() )
     833    this->redirectionUID = NET_ID_PROXY_SERVER_01;
     834
     835  this->bRedirect = true;
     836}
     837
     838
     839
     840/**
     841 * softly reconnecting to another server
     842 * @param serverUserId the id of the client
     843 * @param address  of the new server
     844 */
     845void NetworkStream::softReconnectToServer(int serverUserId, IP address)
     846{
     847//   this->networkMonitor->setForcedReconnection(address);
     848//   this->handleReconnect( NET_ID_MASTER_SERVER);
     849
     850  // create the new udp socket and open the connection to the soft connection port
     851  NetworkSocket* newSocket = new UdpSocket(address.ipString(), 10001);
     852
     853  // delete the synchronization state of this client for all syncs
     854  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
     855    (*it2)->cleanUpUser( serverUserId );
     856  }
     857
     858  // temp save the old socket
     859  NetworkSocket* oldSocket = this->peers[serverUserId].socket;
     860
     861  // now integrate the new socket
     862  this->peers[serverUserId].socket = newSocket;
     863
     864  this->bSoftRedirect = false;
     865  return;
     866
     867  // now remove the old socket
     868  oldSocket->disconnectServer();
     869  delete oldSocket;
     870
     871  // replace the old connection monitor
     872  if ( this->peers[serverUserId].connectionMonitor )
     873    delete this->peers[serverUserId].connectionMonitor;
     874  this->peers[serverUserId].connectionMonitor = new ConnectionMonitor(serverUserId);
     875
     876  // remove old node from the network monitor
     877  this->networkMonitor->removeNode(&this->peers[serverUserId]);
     878
     879}
     880
     881
     882
     883/**
     884 * prepares a soft connection for a client to connect to
     885 * @param userId that will connect to this server
     886 */
     887void NetworkStream::prepareSoftConnection(int userId)
     888{
     889  PRINTF(0)("prepare soft connection for userId %i\n");
     890}
     891
     892
     893
    698894/**
    699895 * handles the disconnect event
     
    702898void NetworkStream::handleDisconnect( int userId )
    703899{
    704   peers[userId].socket->disconnectServer();
    705   delete peers[userId].socket;
    706   peers[userId].socket = NULL;
    707 
    708   if ( peers[userId].handshake )
    709     delete peers[userId].handshake;
    710   peers[userId].handshake = NULL;
    711 
    712   if ( peers[userId].connectionMonitor )
    713     delete peers[userId].connectionMonitor;
    714   peers[userId].connectionMonitor = NULL;
    715 
    716 
     900  this->peers[userId].socket->disconnectServer();
     901  delete this->peers[userId].socket;
     902  this->peers[userId].socket = NULL;
     903
     904  if ( this->peers[userId].handshake )
     905    delete this->peers[userId].handshake;
     906  this->peers[userId].handshake = NULL;
     907
     908  if ( this->peers[userId].connectionMonitor )
     909    delete this->peers[userId].connectionMonitor;
     910  this->peers[userId].connectionMonitor = NULL;
     911
     912  // delete the synchronization state of this client for all syncs
    717913  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
    718914    (*it2)->cleanUpUser( userId );
     
    724920  this->freeSocketSlots.push_back( userId );
    725921
    726   peers.erase( userId);
    727 }
    728 
     922  this->networkMonitor->removeNode(&this->peers[userId]);
     923  this->peers.erase( userId);
     924}
    729925
    730926
     
    793989      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
    794990
    795       // server fakes uniqueid == 0 for handshake
     991      // server fakes uniqueid == 0 for handshake synchronizeable
    796992      if ( ( SharedNetworkData::getInstance()->isMasterServer() ||
    797993             SharedNetworkData::getInstance()->isProxyServerActive() &&  peer->second.isClient() ) &&
    798              sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1) // plus one to handle one client more than the max to redirect it
     994             ( sync.getUniqueID() >= 1000 || sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1 + NET_ID_PROXY_MAX))
    799995        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
    800996      else
     
    9301126      while ( offset + 2 * INTSIZE < length )
    9311127      {
     1128        // read the unique id of the sync
    9321129        assert( offset > 0 );
    9331130        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
    9341131        offset += INTSIZE;
    9351132
     1133        // read the data length
    9361134        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
    9371135        offset += INTSIZE;
     
    9451143        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
    9461144        {
    947           // client thinks his handshake has id 0!!!!!
    948           if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
     1145          // client thinks his handshake has a special id: hostId * 1000 (host id of this server)
     1146          if ( (*it)->getUniqueID() == uniqueId ||                                          // so this client exists already go to sync work
     1147                 ( uniqueId == 0  && (*it)->getUniqueID() == peer->second.userId ) )        // so this is a Handshake!
    9491148          {
    9501149            sync = *it;
  • trunk/src/lib/network/network_stream.h

    r9494 r9656  
    4141    void init();
    4242
     43    /* network interface controls */
    4344    void connectToMasterServer(std::string host, int port);
    4445    void connectToProxyServer(int proxyId, std::string host, int port);
    45     void createServer(int clientPort, int proxyPort);
     46    void createServer(int clientPort, int proxyPort, int clientSoftPort);
    4647
    4748    void createNetworkGameManager();
    4849    void startHandshake(int userId = NET_ID_MASTER_SERVER);
     50
     51    void reconnectToServer(IP address);
     52    void softReconnectToServer(int serverUserId, IP address);
     53    void prepareSoftConnection(int userId);
     54
    4955
    5056    /* synchronizeable interface */
     
    7076    inline PeerInfo* getPeerInfo() { return this->pInfo; }
    7177    inline PeerList getPeerInfoList() { return this->peers; }
     78
     79    inline void setRedirectionTest() { this->bSoftRedirect = true; }
    7280
    7381    /* data processing*/
     
    96104
    97105    void handleConnect( int userId);
     106    void handleSoftConnect( int userId);
    98107    void handleReconnect( int userId );
    99108    void handleDisconnect( int userId );
     109    void handleSoftDisconnect( int userId);
    100110
    101111    void writeToNewDict( byte * data, int length, bool upstream );
     
    112122    NetworkMonitor*            networkMonitor;              //!< the network monitor
    113123    NetworkGameManager*        networkGameManager;          //!< reference to the network game manager
    114     ServerSocket*              clientSocket;                //!< the listening socket of the server
     124    ServerSocket*              clientSocket;                //!< the listening socket for clients of the server
     125    ServerSocket*              clientSoftSocket;            //!< the listening socket for soft connections to the server
    115126    ServerSocket*              proxySocket;                 //!< socket for proxy connections
    116127
     
    126137
    127138    bool                       bRedirect;                   //!< true if the master server sent a redirect command
     139    int                        redirectionUID;              //!< uid of the redir host
     140    bool                       bSoftRedirect;               //!< tsting
    128141};
    129142#endif /* _NETWORK_STREAM */
  • trunk/src/lib/network/peer_info.cc

    r9494 r9656  
    4242void PeerInfo::clear()
    4343{
    44   this->userId = 0;
    45   this->nodeType = NET_CLIENT;
     44  this->userId = NET_ID_UNASSIGNED;
     45  this->nodeType = NET_UNASSIGNED;
    4646  this->socket = NULL;
    4747  this->handshake = NULL;
     
    4949  this->lastRecvedState = 0;
    5050  this->connectionMonitor = NULL;
     51  this->bLocal = false;
    5152
    5253  this->ip = IP(0,0);
     
    6869const std::string PeerInfo::nodeNames[] =
    6970{
    70 
    71   "maser server",
     71  "master server",
    7272  "proxy server active",
    7373  "proxy server passive",
  • trunk/src/lib/network/peer_info.h

    r9494 r9656  
    3030    static const std::string& nodeTypeToString(unsigned int type);
    3131
     32    inline bool isLocal() { return this->bLocal; }
    3233
    3334
     
    4445    int                 lastRecvedState;         //!< last received state
    4546
     47    bool                bLocal;                  //!< true if this node is localy connected to this node
     48
    4649    static const std::string nodeNames[];
    4750
  • trunk/src/lib/network/player_stats.cc

    r9494 r9656  
    4141  init();
    4242
    43   this->userId = userId;
     43  this->assignedUserId = userId;
    4444}
    4545
     
    5656  this->setClassID( CL_PLAYER_STATS, "PlayerStats" );
    5757
    58   this->userId = 0;
     58  this->assignedUserId = 0;
    5959  this->teamId = TEAM_NOTEAM;
    6060  this->preferedTeamId = TEAM_NOTEAM;
     
    6565  this->oldNickName = "Player";
    6666
    67   userId_handle = registerVarId( new SynchronizeableInt( &userId, &userId, "userId" ) );
    68   teamId_handle = registerVarId( new SynchronizeableInt( &teamId, &teamId, "teamId" ) );
    69   preferedTeamId_handle = registerVarId( new SynchronizeableInt( &preferedTeamId, &preferedTeamId, "preferedUserId" ) );
    70   score_handle = registerVarId( new SynchronizeableInt( &score, &score, "score" ) );
    71   playableClassId_handle = registerVarId( new SynchronizeableInt( &playableClassId, &playableClassId, "playableClassId") );
    72   playableUniqueId_handle = registerVarId( new SynchronizeableInt( &playableUniqueId, &playableUniqueId, "playableUniqueId" ) );
    73   modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName" ) );
    74   nickName_handler = registerVarId( new SynchronizeableString( &nickName, &nickName, "nickName" ) );
     67  userId_handle = registerVarId( new SynchronizeableInt( &assignedUserId, &assignedUserId, "userId", PERMISSION_MASTER_SERVER ) );
     68  teamId_handle = registerVarId( new SynchronizeableInt( &teamId, &teamId, "teamId", PERMISSION_MASTER_SERVER ) );
     69  preferedTeamId_handle = registerVarId( new SynchronizeableInt( &preferedTeamId, &preferedTeamId, "preferedUserId", PERMISSION_MASTER_SERVER ) );
     70  score_handle = registerVarId( new SynchronizeableInt( &score, &score, "score", PERMISSION_MASTER_SERVER ) );
     71  playableClassId_handle = registerVarId( new SynchronizeableInt( &playableClassId, &playableClassId, "playableClassId", PERMISSION_MASTER_SERVER) );
     72  playableUniqueId_handle = registerVarId( new SynchronizeableInt( &playableUniqueId, &playableUniqueId, "playableUniqueId", PERMISSION_MASTER_SERVER ) );
     73  modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName", PERMISSION_MASTER_SERVER ) );
     74  nickName_handler = registerVarId( new SynchronizeableString( &nickName, &nickName, "nickName", PERMISSION_MASTER_SERVER ) );
    7575
    7676  MessageManager::getInstance()->registerMessageHandler( MSGID_CHANGENICKNAME, changeNickHandler, NULL );
    7777
    78   PRINTF(0)("PlayerStats created\n");
     78  PRINTF(5)("PlayerStats created\n");
    7979}
    8080
     
    8484 */
    8585PlayerStats::~PlayerStats()
    86 {
    87 }
    88 
    89 
    90  /**
    91  * override this function to be notified on change
    92  * of your registred variables.
    93  * @param id id's which have changed
    94   */
     86{}
     87
     88
     89/**
     90* override this function to be notified on change
     91* of your registred variables.
     92* @param id id's which have changed
     93 */
    9594void PlayerStats::varChangeHandler( std::list< int > & id )
    9695{
     
    9998    this->setPlayableUniqueId( this->playableUniqueId );
    10099
    101     PRINTF(0)("uniqueID changed %d %d %d\n", userId, SharedNetworkData::getInstance()->getHostID(), getUniqueID());
     100    PRINTF(4)("uniqueID changed %d %d %d\n", assignedUserId, SharedNetworkData::getInstance()->getHostID(), getUniqueID());
    102101  }
    103102
     
    105104  {
    106105    PRINTF(0)("user %s is now known as %s\n", oldNickName.c_str(), nickName.c_str());
    107     oldNickName = nickName;
    108   }
    109 }
     106    this->oldNickName = nickName;
     107  }
     108
     109  if ( std::find( id.begin(), id.end(), preferedTeamId_handle) != id.end() )
     110  {
     111    PRINTF(0)("user %s has changed team to %i\n", nickName.c_str(), this->teamId);
     112  }
     113}
     114
     115
    110116
    111117/**
     
    123129  }
    124130
    125   for ( std::list<BaseObject*>::const_iterator it = list->begin(); it != list->end(); it++ )
    126   {
    127     if ( dynamic_cast<PlayerStats*>(*it)->getUserId() == userId )
     131  for ( std::list<BaseObject*>::const_iterator it = list->
     132        begin();
     133        it != list->end();
     134        it++ )
     135  {
     136
     137
     138    if ( dynamic_cast<PlayerStats*>(*it)->getAssignedUserId() == userId )
    128139    {
    129140      return dynamic_cast<PlayerStats*>(*it);
     
    148159
    149160  this->playable = NULL;
    150   for ( std::list<BaseObject*>::const_iterator it = list->begin(); it != list->end(); it++ )
    151   {
    152     if ( dynamic_cast<Playable*>(*it)->getUniqueID() == uniqueId )
     161  for ( std::list<BaseObject*>::const_iterator it = list->
     162        begin();
     163        it != list->end();
     164        it++ )
     165  {
     166    if ( dynamic_cast<Playable*>(*it)->
     167         getUniqueID() == uniqueId )
    153168    {
    154169      this->playable = dynamic_cast<Playable*>(*it);
     
    159174  }
    160175
    161   if ( this->playable && userId == SharedNetworkData::getInstance()->getHostID() )
     176  if ( this->playable && this->assignedUserId == SharedNetworkData::getInstance()
     177       ->getHostID() )
    162178  {
    163179    State::getPlayer()->setPlayable( this->playable );
     180    // also set the team id
    164181  }
    165182
     
    204221    assert( Converter::stringToByteArray( nick, data, nick.length()+INTSIZE) == nick.length()+INTSIZE );
    205222
    206     MessageManager::getInstance()->sendMessage( MSGID_CHANGENICKNAME, data, nick.length()+INTSIZE, RT_SERVER, 0, MP_HIGHBANDWIDTH );
     223    MessageManager::getInstance()->sendMessage( MSGID_CHANGENICKNAME, data, nick.length()+INTSIZE, RT_SERVER, NET_MASTER_SERVER, MP_HIGHBANDWIDTH );
    207224    return;
    208225  }
    209226}
    210227
    211 bool PlayerStats::changeNickHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId )
     228/**
     229 * handler for the nick name
     230 * @param messageType type of the message
     231 * @param data  data of the message
     232 * @param dataLength length of the data
     233 * @param someData some additional data
     234 * @param senderId userId of the sender
     235 * @param destinationId userId of the rec
     236 * @return true if handled correctly
     237 */
     238bool PlayerStats::changeNickHandler( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId  )
    212239{
    213240  std::string newNick;
     
    216243  if ( res != dataLength )
    217244  {
    218     PRINTF(2)("invalid message size from user %d\n", userId);
     245    PRINTF(2)("invalid message size from user %d\n", senderId);
    219246    newNick = "invalid";
    220247  }
    221248
    222   if ( PlayerStats::getStats( userId ) )
    223     PlayerStats::getStats( userId )->setNickName( newNick );
     249  if ( PlayerStats::getStats( senderId) )
     250    PlayerStats::getStats( senderId )->setNickName( newNick );
    224251
    225252  return true;
    226253}
    227254
     255/**
     256 * sets the nick name from the shell
     257 * @param newNick new prefered nick name
     258 */
    228259void PlayerStats::shellNick( const std::string& newNick )
    229260{
     
    236267
    237268
     269/**
     270 * removes and delets all player stats
     271 */
    238272void PlayerStats::deleteAllPlayerStats( )
    239273{
     
    246280
    247281
     282/**
     283 * @return the score list of this player stat
     284 */
    248285ScoreList PlayerStats::getScoreList( )
    249286{
     
    257294  }
    258295
    259   for ( std::list<BaseObject*>::const_iterator it = list->begin(); it != list->end(); it++ )
     296  for ( std::list<BaseObject*>::const_iterator it = list->
     297        begin();
     298        it != list->end();
     299        it++ )
    260300  {
    261301    PlayerStats & stats = *dynamic_cast<PlayerStats*>(*it);
  • trunk/src/lib/network/player_stats.h

    r9110 r9656  
    1616enum
    1717{
    18   TEAM_NOTEAM = -3,
    19   TEAM_RANDOM = -2,
    20   TEAM_SPECTATOR = -1
     18  TEAM_NOTEAM       = -3,
     19  TEAM_RANDOM       = -2,
     20  TEAM_SPECTATOR    = -1
    2121};
     22
    2223
    2324struct PlayerScore
     
    2627  int score;
    2728};
     29
     30
    2831typedef std::list<PlayerScore> TeamScoreList;
    2932typedef std::map<int,TeamScoreList> ScoreList;
    3033
     34
    3135//! A class for storing player information
    32 class PlayerStats : public Synchronizeable 
     36class PlayerStats : public Synchronizeable
    3337{
    3438
     
    3741    PlayerStats( int userId );
    3842    virtual ~PlayerStats();
    39    
     43
    4044    virtual void varChangeHandler( std::list<int> & id );
    41    
     45
    4246    static PlayerStats * getStats( int userId );
    43    
    44     inline int getUserId(){ return userId; }
    45    
     47    inline int getAssignedUserId(){ return this->assignedUserId; }
     48
     49
    4650    inline int getTeamId(){ return teamId; }
    4751    inline void setTeamId( int teamId ){ this->teamId = teamId; }
    48    
     52
    4953    inline int getPreferedTeamId(){ return preferedTeamId; }
    50     inline void setPreferedTeamId( int preferedTeamId ){ this->preferedTeamId = preferedTeamId; }
    51    
     54    inline void setPreferedTeamId( int preferedTeamId ) { this->preferedTeamId = preferedTeamId; }
     55
    5256    inline int getScore(){ return score; }
    5357    inline void setScore( int score ){ this->score = score; }
    54    
     58
    5559    inline int getPlayableClassId(){ return playableClassId; }
    5660    void setPlayableClassId( int classId ){ this->playableClassId = classId; };
    57    
     61
    5862    inline int getPlayableUniqueId(){ return playableUniqueId; }
    5963    void setPlayableUniqueId( int uniqueId );
    60    
     64
    6165    inline std::string getModelFileName(){ return modelFileName; }
    6266    inline void setModelFileName( std::string filename ){ modelFileName = filename; }
    63    
     67
    6468    Playable * getPlayable();
    65    
     69
    6670    inline std::string getNickName(){ return this->nickName; }
    6771    void setNickName( std::string nick );
    68     static bool changeNickHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId );
     72    static bool changeNickHandler( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId );
    6973    void shellNick( const std::string&  newNick );
    70    
     74
    7175    static void deleteAllPlayerStats();
    72    
     76
    7377    static ScoreList getScoreList();
    7478
     79
    7580  private:
    76     int userId;                //!< userId
    77     int teamId;                //!< teamId
    78     int preferedTeamId;        //!< preferedTeamId
     81    void init();
    7982
    80     std::string nickName;      //!< players nickname
    81     std::string oldNickName;   //!< nickname player had before
    8283
    83     int score;                 //!< users score points
    84     int playableClassId;       //!< players playable class id
    85     int playableUniqueId;      //!< playable's uniqueId
    86     std::string modelFileName; //!< model filename
     84  private:
     85    // handles for SynchronizeableVars
     86    int              userId_handle;
     87    int              teamId_handle;
     88    int              preferedTeamId_handle;
     89    int              score_handle;
     90    int              playableClassId_handle;
     91    int              playableUniqueId_handle;
     92    int              modelFileName_handle;
     93    int              nickName_handler;
    8794
    88     Playable * playable;       //!< pointer to players playable
     95    int              assignedUserId;            //!< userId
     96    int              teamId;                    //!< teamId
     97    int              preferedTeamId;            //!< preferedTeamId
    8998
    90     // handles for SynchronizeableVars
    91     int userId_handle;
    92     int teamId_handle;
    93     int preferedTeamId_handle;
    94     int score_handle;
    95     int playableClassId_handle;
    96     int playableUniqueId_handle;
    97     int modelFileName_handle;
    98     int nickName_handler;
    99    
    100     void init();
     99    std::string      nickName;                  //!< players nickname
     100    std::string      oldNickName;               //!< nickname player had before
     101
     102    int              score;                     //!< users score points
     103    int              playableClassId;           //!< players playable class id
     104    int              playableUniqueId;          //!< playable's uniqueId
     105    std::string      modelFileName;             //!< model filename
     106
     107    Playable *       playable;                  //!< pointer to players playable
    101108};
    102109
  • trunk/src/lib/network/proxy/network_settings.cc

    r9494 r9656  
    8787  // setUniqueID( maxCon+2 ) because we need one id for every handshake
    8888  // and one for handshake to reject client maxCon+1
    89   SharedNetworkData::getInstance()->setNewUniqueID( this->maxPlayer + 2);
     89  // NEW: at most there will be
     90  SharedNetworkData::getInstance()->setNewUniqueID( this->maxPlayer + NET_ID_PROXY_MAX + 2);
    9091}
    9192
  • trunk/src/lib/network/server_socket.h

    r7954 r9656  
    11/*!
    22 * @file server_socket.h
    3  *  waits for incoming connections
    4 
     3 * waits for incoming connections and handles them.
     4 *
    55 */
    66
  • trunk/src/lib/network/shared_network_data.h

    r9494 r9656  
    1616
    1717class Synchronizeable;
     18class NetworkMonitor;
    1819
    1920
     
    6465    inline void setDefaultSyncStream(NetworkStream* defaultSyncStream) { this->defaultSyncStream = defaultSyncStream; }
    6566
     67    /** @returns the network monitor reference */
     68    inline NetworkMonitor* getNetworkMonitor() { return this->networkMonitor; }
     69    /** @param networkMonitor sets the NetworkMonitor reference */
     70    inline void setNetworkMonitor( NetworkMonitor* networkMonitor) { this->networkMonitor = networkMonitor; }
     71
    6672
    6773  private:
     
    7581    int                             hostID;                  //!< The Host-ID of the Manager
    7682    NetworkStream*                  defaultSyncStream;       //!< default synchronize NetworkStream
     83    NetworkMonitor*                 networkMonitor;          //!< reference to the NetworkMonitor
    7784
    7885    static SharedNetworkData*       singletonRef;            //!< Pointer to the only instance of this Class
  • trunk/src/lib/network/synchronizeable.cc

    r9494 r9656  
    5555  /* make sure loadClassId is first synced var because this is read by networkStream */
    5656  assert( syncVarList.size() == 0 );
    57   mLeafClassId = this->registerVarId( new SynchronizeableInt( (int*)&this->getLeafClassID(), (int*)&this->getLeafClassID(), "leafClassId" ) );
    58 
    59   this->registerVar( new SynchronizeableInt( &this->owner, &this->owner, "owner" ) );
    60   this->registerVar( new SynchronizeableString( &this->objectName, &this->objectName, "objectName" ) );
     57  mLeafClassId = this->registerVarId( new SynchronizeableInt( (int*)&this->getLeafClassID(), (int*)&this->getLeafClassID(), "leafClassId", PERMISSION_MASTER_SERVER) );
     58
     59  this->registerVar( new SynchronizeableInt( &this->owner, &this->owner, "owner", PERMISSION_MASTER_SERVER ) );
     60  this->registerVar( new SynchronizeableString( &this->objectName, &this->objectName, "objectName", PERMISSION_MASTER_SERVER ) );
    6161}
    6262
     
    126126int Synchronizeable::getStateDiff( int userId, byte* data, int maxLength, int stateId, int fromStateId, int priorityTH )
    127127{
    128   //make sure this user has his history
    129   if ( sentStates.size() <= userId )
     128  // make sure this user has his history or resize for new clients
     129  if ( (int)sentStates.size() <= userId )
    130130    sentStates.resize( userId+1 );
    131131
     
    133133  int neededSize = 0;
    134134
     135  // calculate the needed space for network packet by summing up
    135136  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
    136137  {
     
    201202  int n;
    202203
    203   bool hasPermission = false;
    204204  bool sizeChanged = false;
    205205
     
    207207  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
    208208  {
    209     // DATA PERMISSIONS
    210     // check if this synchronizeable has the permissions to write the data
    211 
    212     // first check MASTER_SERVER permissions
    213     if( SharedNetworkData::getInstance()->isMasterServer() && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
    214       hasPermission = true;
    215     // now check PROXY_SERVER permissions
    216     else if( SharedNetworkData::getInstance()->isProxyServerActive() && (*it)->checkPermission( PERMISSION_PROXY_SERVER ))
    217       hasPermission = true;
    218     // now check OWNER permissions
    219     else if( this->owner == SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
    220       hasPermission = true;
    221     // now check ALL permissions
    222     else if( (*it)->checkPermission( PERMISSION_ALL ))
    223       hasPermission = true;
    224     // SPECIAL: get write permissions if i am master server and i am able to overwrite the client stuff
    225 #warning this could probably override also clients that are connected to another proxy: the master server overwrites it
    226     else if( SharedNetworkData::getInstance()->isMasterServer() && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ))
    227       hasPermission = true;
    228     // SPECIAL: get write permissions if i am proxy server and i am able to overwrite the client stuff
    229     else if( SharedNetworkData::getInstance()->isProxyServerActive() && this->networkStream->isUserClient(userId)
    230              && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ) )
    231       hasPermission = true;
     209
     210    ////////////////////////////////
     211    // Data SENDING Permissions
     212    ////////////////////////////////
     213    bool hasPermission = false;
     214    bool b1, b2, b3, b4, b5, b6, b7, b8, b9;
     215    b1 = b2 = b3 = b4 = b5 = b6 = b7 = b8 = b9 = false;
     216
     217
     218    // Permission   OWNER accept if:
     219    // I am the owner
     220    if(       (*it)->checkPermission( PERMISSION_OWNER ) && this->owner == SharedNetworkData::getInstance()->getHostID()) {
     221      hasPermission = true; b1 = true; }
     222    // reciever != owner && owner is local
     223    else if(  (*it)->checkPermission( PERMISSION_OWNER ) && userId != this->owner &&
     224                (SharedNetworkData::getInstance()->isUserLocal(this->owner) || this->owner == SharedNetworkData::getInstance()->getHostID())) {
     225      hasPermission = true; b2 = true; }
     226
     227
     228    // Permission   MASTER_SERVER accept if:
     229    // im MASTER_SERVER
     230    else if( (*it)->checkPermission( PERMISSION_MASTER_SERVER ) && SharedNetworkData::getInstance()->isMasterServer()) {
     231      hasPermission = true; b3 = true; }
     232    // im PROXY_SERVER && reciever == CLIENT
     233    else if( (*it)->checkPermission( PERMISSION_MASTER_SERVER ) && SharedNetworkData::getInstance()->isProxyServerActive() &&
     234               SharedNetworkData::getInstance()->isUserClient( userId)) {
     235      hasPermission = true;  b4 = true; }
     236
     237
     238    // Pemission    SERVER accept if:
     239    // i am server && reciever == CLIENT
     240    else if( (*it)->checkPermission( PERMISSION_SERVER ) && !SharedNetworkData::getInstance()->isClient() &&
     241               SharedNetworkData::getInstance()->isUserClient( userId)) {
     242      hasPermission = true; b5 = true; }
     243    // i am SERVER && reciever == SERVER && reciever != owner && ( owner is local || i am owner)
     244    else if( (*it)->checkPermission( PERMISSION_SERVER ) && !SharedNetworkData::getInstance()->isClient() &&
     245               userId != this->owner &&
     246               ( SharedNetworkData::getInstance()->isUserLocal( this->owner) || this->owner ==  SharedNetworkData::getInstance()->getHostID())) {
     247      hasPermission = true; b6 = true; }
     248
     249
     250    // Permission   ALL accept if:
     251    else if( (*it)->checkPermission( PERMISSION_ALL )) {
     252      hasPermission = true; b7 = true; }
     253    // or else refuse sending data
    232254    else
    233255      hasPermission = false;
    234256
    235257
     258
    236259    if ( sizeIter == stateFrom->sizeList.end() || *sizeIter != (*it)->getSize() )
    237260      sizeChanged = true;
     
    241264      n = (*it)->writeToBuf( stateTo->data+i, stateTo->dataLength - i );
    242265      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
    243       //PRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
     266//       PRINTF(0)("sending %s %d\n", (*it)->getName().c_str(), n);
     267
     268//       if( this->isA(CL_PLAYABLE))
     269//       {
     270//         PRINTF(0)("ms: %i, ps: %i, c: %i, sender: %i, reciever: %i, owner: %i, perm: (ow %i, ms %i, s %i, a %i)\n",
     271//         SharedNetworkData::getInstance()->isMasterServer(), SharedNetworkData::getInstance()->isProxyServerActive(), SharedNetworkData::getInstance()->isClient(),
     272//         SharedNetworkData::getInstance()->getHostID(), userId, this->owner,
     273//         (*it)->checkPermission( PERMISSION_OWNER ), (*it)->checkPermission( PERMISSION_MASTER_SERVER ),
     274//         (*it)->checkPermission( PERMISSION_SERVER ), (*it)->checkPermission( PERMISSION_ALL ));
     275//         PRINTF(0)("hasPermission: %i, sizeChanged: %i, eval: %i, %i, %i, %i, %i, %i, %i\n", hasPermission, sizeChanged, b1, b2, b3, b4, b5, b6, b7);
     276//         PRINTF(0)("sending %s %s %d\n", this->getClassCName(), (*it)->getName().c_str(), n);
     277//       }
     278
     279
    244280      stateTo->sizeList.push_back( n );
    245281      // this is only for very hardcore debug sessions
     
    282318
    283319/**
    284  * sets a new state out of a diff created on another host
     320 * sets a new state out of a diff created on another host (recieving data)
    285321 * @param userId hostId of user who send me that diff
    286322 * @param data pointer to diff
     
    295331{
    296332  //make sure this user has his history
    297   if ( recvStates.size() <= userId )
     333  if ( (int)recvStates.size() <= userId )
    298334    recvStates.resize( userId+1 );
    299335
     
    345381  int n = 0;
    346382  std::list<int> changes;
    347   bool hasPermission = false;
    348383
    349384  // extract the new state for every client
     
    353388    // check if this synchronizeable has the permissions to write the data
    354389
    355     // first check MASTER_SERVER permissions
    356     if(  this->networkStream->isUserMasterServer( userId ) && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
    357       hasPermission = true;
    358     // now check PROXY_SERVER permissions
    359     else if( this->networkStream->isUserProxyServerActive( userId )  && (*it)->checkPermission( PERMISSION_MASTER_SERVER )
    360              && SharedNetworkData::getInstance()->isClient())
    361       hasPermission = true;
    362     // now check OWNER permissions
    363     else if( this->owner == userId && (*it)->checkPermission( PERMISSION_OWNER ))
    364       hasPermission = true;
    365     // now check ALL permissions
    366     else if( (*it)->checkPermission( PERMISSION_ALL ))
    367       hasPermission = true;
    368     // SPECIAL: get write permissions if im sending to a master server that does not own this sync
    369     else if( this->networkStream->isUserMasterServer( userId ) && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
    370       hasPermission = true;
    371     // SPECIAL: get write permissions if im sending to a proxy server that does not own this sync
    372     else if( this->networkStream->isUserProxyServerActive( userId ) && SharedNetworkData::getInstance()->isClient()
    373               && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
    374       hasPermission = true;
     390    bool hasPermission = false;
     391    bool b1, b2, b3, b4, b5, b6, b7, b8, b9;
     392    b1 = b2 = b3 = b4 = b5 = b6 = b7 = b8 = b9 = false;
     393
     394    ////////////////////////////////
     395    // Data RECIEVING Permissions
     396    ////////////////////////////////
     397
     398    // i should never ever receive a state update from a synchronizeable, that belongs to me! If it does somethings wrong with the send rules
     399//     assert(   !((*it)->checkPermission( PERMISSION_OWNER ) && this->owner == SharedNetworkData::getInstance()->getHostID()));
     400
     401
     402    // Permission   OWNER accept if:
     403    // sender == owner
     404    if(      (*it)->checkPermission( PERMISSION_OWNER ) && this->owner == userId) {
     405      hasPermission = true; b1 = true; }
     406    // sender == MASTER_SERVER
     407    else if( (*it)->checkPermission( PERMISSION_OWNER ) && SharedNetworkData::getInstance()->isUserMasterServer( userId)
     408               && this->owner != SharedNetworkData::getInstance()->getHostID()) {
     409      hasPermission = true; b2 = true; }
     410    // sender == PROXY_SERVER
     411      else if( (*it)->checkPermission( PERMISSION_OWNER ) && SharedNetworkData::getInstance()->isUserProxyServerActive( userId) &&
     412                 this->owner != SharedNetworkData::getInstance()->getHostID()) {
     413        hasPermission = true; b3 = true; }
     414
     415
     416
     417    // Permission   MASTER_SERVER accept if:
     418    // sender == MASTER_SERVER
     419    else if( (*it)->checkPermission( PERMISSION_MASTER_SERVER) && SharedNetworkData::getInstance()->isUserMasterServer( userId)) {
     420      hasPermission = true; b4 = true; }
     421    // sender == PROXY_SERVER && im not MASTER_SERVER && im not PROXY_SERVER
     422    else if( (*it)->checkPermission( PERMISSION_MASTER_SERVER) && SharedNetworkData::getInstance()->isClient() &&
     423               SharedNetworkData::getInstance()->isUserProxyServerActive( userId)) {
     424      hasPermission = true; b5 = true; }
     425
     426    // Permission   SERVER accept if:
     427    // sender == SERVER
     428    else if( (*it)->checkPermission( PERMISSION_SERVER ) && !SharedNetworkData::getInstance()->isUserClient( userId) /*&&
     429               SharedNetworkData::getInstance()->isClient()*/) {
     430      hasPermission = true; b6 = true; }
     431
     432
     433
     434    // Pemission    ALL accept if:
     435    else if(  (*it)->checkPermission( PERMISSION_ALL )) {
     436      hasPermission = true; b8 = true; }
     437
     438
     439   // no rights to over-write local data
    375440    else
    376441      hasPermission = false;
     
    384449      i += n;
    385450      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
    386       //PRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
     451//       PRINTF(0)("recieving: %s %d\n", (*it)->getName().c_str(), n);
    387452      //(*it)->debug();
     453
     454//       if( this->isA(CL_PLAYABLE))
     455//       {
     456//         PRINTF(0)("ms: %i, ps: %i, c: %i, sender: %i, reciever: %i, owner: %i, perm: (ow %i, ms %i, s %i, a %i)\n",
     457//         SharedNetworkData::getInstance()->isMasterServer(), SharedNetworkData::getInstance()->isProxyServerActive(), SharedNetworkData::getInstance()->isClient(),
     458//         userId, SharedNetworkData::getInstance()->getHostID(), this->owner,
     459//         (*it)->checkPermission( PERMISSION_OWNER ), (*it)->checkPermission( PERMISSION_MASTER_SERVER ),
     460//         (*it)->checkPermission( PERMISSION_SERVER ), (*it)->checkPermission( PERMISSION_ALL ));
     461//         PRINTF(0)("hasPermission: %i, eval: %i, %i, %i, %i, %i, %i, %i, %i\n", hasPermission, b1, b2, b3, b4, b5, b6, b7, b8);
     462//         PRINTF(0)("rec %s %s %d\n", this->getClassCName(), (*it)->getName().c_str(), n);
     463//       }
     464
     465
    388466      if ( (*it)->getHasChanged() )
    389467      {
     
    444522void Synchronizeable::cleanUpUser( int userId )
    445523{
    446   if ( recvStates.size() > userId )
     524  if ( (int)recvStates.size() > userId )
    447525  {
    448526    for ( std::list<StateHistoryEntry*>::iterator it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
     
    459537  }
    460538
    461   if ( sentStates.size() > userId )
     539  if ( (int)sentStates.size() > userId )
    462540  {
    463541
     
    485563{
    486564   //make sure this user has his history
    487   if ( recvStates.size() <= userId )
     565  if ( (int)recvStates.size() <= userId )
    488566    recvStates.resize( userId+1 );
    489567
     
    575653{
    576654   //make sure this user has his history
    577   if ( sentStates.size() <= userId )
     655  if ( (int)sentStates.size() <= userId )
    578656    sentStates.resize( userId+1 );
    579657
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_bool.h

    r9406 r9656  
    1212
    1313  public:
    14     SynchronizeableBool( bool * ptrIn, bool * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
     14    SynchronizeableBool( bool * ptrIn, bool * ptrOut, std::string name, int permission, int priority = 0 );
    1515    virtual ~SynchronizeableBool();
    1616
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_float.h

    r9406 r9656  
    1313
    1414  public:
    15     SynchronizeableFloat( float * ptrIn, float * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
     15    SynchronizeableFloat( float * ptrIn, float * ptrOut, std::string name, int permission, int priority = 0 );
    1616    virtual ~SynchronizeableFloat();
    1717
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_int.h

    r9406 r9656  
    1313
    1414  public:
    15     SynchronizeableInt( int * ptrIn, int * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
     15    SynchronizeableInt( int * ptrIn, int * ptrOut, std::string name, int permission, int priority = 0 );
    1616    virtual ~SynchronizeableInt();
    1717
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_ip.h

    r9406 r9656  
    1515
    1616  public:
    17     SynchronizeableIP( IP *ptrIn, IP * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
     17    SynchronizeableIP( IP *ptrIn, IP * ptrOut, std::string name, int permission, int priority = 0 );
    1818    virtual ~SynchronizeableIP();
    1919
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_quaternion.h

    r9406 r9656  
    1414
    1515  public:
    16     SynchronizeableQuaternion( Quaternion * ptrIn, Quaternion * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
     16    SynchronizeableQuaternion( Quaternion * ptrIn, Quaternion * ptrOut, std::string name, int permission, int priority = 0 );
    1717    virtual ~SynchronizeableQuaternion();
    1818
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_string.h

    r9406 r9656  
    1414
    1515  public:
    16     SynchronizeableString( std::string * ptrIn, std::string * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
     16    SynchronizeableString( std::string * ptrIn, std::string * ptrOut, std::string name, int permission, int priority = 0 );
    1717    virtual ~SynchronizeableString();
    1818
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_uint.h

    r9406 r9656  
    1313
    1414  public:
    15     SynchronizeableUInt( unsigned int * ptrIn, unsigned int * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
     15    SynchronizeableUInt( unsigned int * ptrIn, unsigned int * ptrOut, std::string name, int permission, int priority = 0 );
    1616    virtual ~SynchronizeableUInt();
    1717
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_var.h

    r9494 r9656  
    1515
    1616  public:
    17     SynchronizeableVar( void * ptrIn, void * ptrOut, std::string name, int length, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
     17    SynchronizeableVar( void * ptrIn, void * ptrOut, std::string name, int length, int permission, int priority = 0 );
    1818    virtual ~SynchronizeableVar();
    1919
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_vector.h

    r9406 r9656  
    1414
    1515  public:
    16     SynchronizeableVector( Vector * ptrIn, Vector * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
     16    SynchronizeableVector( Vector * ptrIn, Vector * ptrOut, std::string name, int permission, int priority = 0 );
    1717    virtual ~SynchronizeableVector();
    1818
  • trunk/src/lib/network/udp_socket.h

    r9406 r9656  
    4141
    4242  private:
     43    void init();
     44
     45    bool writeRawPacket( byte * data, int length );
     46    bool checkUdpCmd( byte udpCmd );
     47    bool checkRandomByte( byte rndByte );
     48    byte generateNewRandomByte();
     49
     50
     51  private:
    4352    UdpServerSocket * serverSocket;   //!< will get packets here
    4453    int               userId;         //!< user id used by serverSocket
     
    4756
    4857    byte              randomByte;     //!< contains random bytes & 0xFC
    49 
    50     bool writeRawPacket( byte * data, int length );
    51     bool checkUdpCmd( byte udpCmd );
    52     bool checkRandomByte( byte rndByte );
    53     byte generateNewRandomByte();
    54 
    55     void init();
    56 
    5758};
    5859
  • trunk/src/lib/particles/particle_system.cc

    r9406 r9656  
    5555
    5656/**
    57  * standard deconstructor
    58 */
     57 * @brief standard deconstructor
     58 */
    5959ParticleSystem::~ParticleSystem()
    6060{
     
    8484
    8585/**
    86  * loads Parameters from a TiXmlElement
     86 * @brief loads Parameters from a TiXmlElement
    8787 * @param root the XML-element to load from.
    8888 */
     
    241241
    242242/**
     243 * @brief sets a key in the color-animation on a per-particle basis
     244 * @param lifeCycleTime: the time (partilceLifeTime/particleAge) [0-1]
     245 * @param color the Color.
     246 */
     247void ParticleSystem::setColor(float lifeCycleTime, const Color& color)
     248{
     249  this->setColor(lifeCycleTime, color.r(), color.g(), color.b(), color.a());
     250}
     251
     252
     253/**
    243254 * @brief adds an Emitter to this System.
    244255 * @param emitter the Emitter to add.
     
    455466           this->maxCount,
    456467           ((this->maxCount!=0)?100*this->count/this->maxCount:0));
    457   if (this->deadList)
     468
     469
     470  PRINT(0)("  Coloring sceme: r:"), this->colorAnim[0].debug();
     471  PRINT(0)("  Coloring sceme: g:"), this->colorAnim[1].debug();
     472  PRINT(0)("  Coloring sceme: b:"), this->colorAnim[2].debug();
     473  PRINT(0)("  Coloring sceme: a:"), this->colorAnim[3].debug();
     474
     475  if (likely(this->deadList != NULL))
    458476  {
    459477    PRINT(0)("  - ParticleDeadList is used: ");
  • trunk/src/lib/particles/particle_system.h

    r7300 r9656  
    1313#include "vector.h"
    1414#include <list>
     15#include "color.h"
    1516
    1617#include "quick_animation.h"
     
    7172  void setMass(float lifeCycleTime, float mass, float randMass = 0.0);
    7273  void setColor(float lifeCycleTime, float red, float green, float blue, float alpha);
     74  void setColor(float lifeCycleTime, const Color& color);
    7375
    7476  /** @returns the lifespan of the particles */
  • trunk/src/lib/particles/quick_animation.cc

    r9406 r9656  
    287287
    288288  for (unsigned int i = 0; i < this->keyFrames.size(); i++)
    289     printf("(%f, %f)->", this->keyFrames[i].position, this->keyFrames[i].value);
     289    printf("(%0.2f, %0.2f)->", this->keyFrames[i].position, this->keyFrames[i].value);
    290290  printf("\n");
    291291}
  • trunk/src/lib/util/color.h

    r8986 r9656  
    4848  inline const Color& operator-=(const Color& c) { r()-=c.r(); g()-=c.g(); b()-=c.b(); a()-=c.a(); return *this; };
    4949  inline Color operator-(const Color& c) const { return Color(r()-c.r(), g()-c.g(), b()-c.b(), a()-c.a()); };
     50  inline const Color& operator*=(float v) { r()*=v, g()*=v, b()*=v, a()*=v; return *this; };
    5051  inline Color operator*(float v) const { return Color(r()*v, g()*v, b()*v, a()*v); };
    5152
  • trunk/src/story_entities/menu/game_menu.cc

    r9406 r9656  
    7676  if( this->dataTank)
    7777    delete this->dataTank;
    78   delete OrxGui::GLGuiHandler::getInstance( );
     78  OrxGui::GLGuiHandler::deleteInstance( );
    7979}
    8080
  • trunk/src/story_entities/multi_player_world.cc

    r9406 r9656  
    6363  if( this->dataTank)
    6464    delete this->dataTank;
    65   delete OrxGui::GLGuiHandler::getInstance( );
     65  OrxGui::GLGuiHandler::deleteInstance( );
    6666}
    6767
  • trunk/src/subprojects/network/network_unit_test.cc

    r9494 r9656  
    5252    server1 = server.getNewSocket();
    5353  }
    54  
     54
    5555  assert( server1->isOk() );
    5656
     
    8686  printf("%d bytes send from server2\n", n);
    8787  SDL_Delay(10);
    88  
     88
    8989  server.update();
    9090
     
    120120
    121121  printf("data: '%s'\n", buf);
    122  
    123  
     122
     123
    124124  //22222222222222222222222222222222222222222
    125125  n = client1->writePacket((byte*)str1, strlen(str1)+1);
     
    132132  printf("%d bytes send from server2\n", n);
    133133  SDL_Delay(10);
    134  
     134
    135135  server.update();
    136136
     
    181181  delete client2;
    182182  delete server1;
    183   delete server2; 
    184  
     183  delete server2;
     184
    185185  return 0;
    186186}
     
    238238}
    239239
    240 bool testCB( MessageId messageId, byte * data, int dataLength, void * someData, int userId )
     240bool testCB( MessageType messageType, byte * data, int dataLength, void * someData, int userId )
    241241{
    242242  printf("GOT MESSAGE: %s\n", data);
     
    259259
    260260  NetworkManager* netMan = NetworkManager::getInstance();
    261  
     261
    262262  netMan->initialize();
    263  
     263
    264264  netMan->createMasterServer(/**ss, */ 9999);
    265  
     265
    266266  SimpleSync* ss = new SimpleSync("Server");
    267267  ss->setSynchronized( true );
    268  
     268
    269269  NetworkLog::getInstance()->listen( 8888 );
    270270
    271271  //MessageManager::getInstance()->initUser( 1 );
    272272  MessageManager::getInstance()->registerMessageHandler( TESTMESSAGEID, testCB, NULL );
    273  
     273
    274274  SDL_Delay(20);
    275275
    276276  for(;;)
    277277  {
    278     MessageManager::getInstance()->sendMessage( TESTMESSAGEID, (byte*)"server to client", 18, RT_ALL_BUT_ME, 0, MP_HIGHBANDWIDTH );
     278    MessageManager::getInstance()->sendMessage( TESTMESSAGEID, (byte*)"server to client", 18, RT_ALL_BUT_ME, NET_UNASSIGNED, MP_HIGHBANDWIDTH );
    279279    netMan->synchronize( 100 );
    280280    SDL_Delay(100);
     
    296296  State::setOnline(true);
    297297  NetworkManager* netMan = NetworkManager::getInstance();
    298  
     298
    299299
    300300  netMan->initialize();
    301  
     301
    302302  std::string host;
    303  
     303
    304304  if ( argc > 2 )
    305305    host = argv[2];
    306306  else
    307307    host = "localhost";
    308  
     308
    309309  netMan->createClient(host, 9999);
    310  
     310
    311311//  SimpleSync* ss = new SimpleSync("SimpleSync");
    312312//  ss->setSynchronized( true );
    313313//  netMan->connectSynchronizeable( *ss );
    314  
     314
    315315  NetworkLog::getInstance()->listen( 7777 );
    316316
    317317  SimpleSync * ss = NULL;
    318  
     318
    319319  //MessageManager::getInstance()->initUser( 0 );
    320320  MessageManager::getInstance()->registerMessageHandler( TESTMESSAGEID, testCB, NULL );
    321  
     321
    322322  for(;;)
    323323  {
    324324    netMan->synchronize( 100 );
    325     MessageManager::getInstance()->sendMessage( TESTMESSAGEID, (byte*)"client to server", 18, RT_ALL_BUT_ME, 0, MP_HIGHBANDWIDTH );
     325    MessageManager::getInstance()->sendMessage( TESTMESSAGEID, (byte*)"client to server", 18, RT_ALL_BUT_ME, NET_UNASSIGNED, MP_HIGHBANDWIDTH );
    326326    ss = dynamic_cast<SimpleSync*>(ClassList::getObject( "Server", CL_SIMPLE_SYNC ) );
    327327    SDL_Delay(100);
  • trunk/src/util/multiplayer_team_deathmatch.cc

    r9494 r9656  
    138138  if ( currentGameState == GAMESTATE_PRE_GAME || currentGameState == GAMESTATE_GAME )
    139139  {
    140     if ( PlayerStats::getStats( SharedNetworkData::getInstance()->getHostID() )
    141          && box == NULL
    142          &&  (PlayerStats::getStats( SharedNetworkData::getInstance()->getHostID() )->getPreferedTeamId() == TEAM_NOTEAM
    143          || bShowTeamChange )
     140    if ( PlayerStats::getStats( SharedNetworkData::getInstance()->getHostID() ) &&
     141         box == NULL &&
     142         (PlayerStats::getStats( SharedNetworkData::getInstance()->getHostID() )->getPreferedTeamId() == TEAM_NOTEAM || bShowTeamChange )
    144143
    145144       )
     
    193192  }
    194193
    195   if ( box != NULL
    196        && PlayerStats::getStats( SharedNetworkData::getInstance()->getHostID() )
    197        && PlayerStats::getStats( SharedNetworkData::getInstance()->getHostID() )->getPreferedTeamId() != TEAM_NOTEAM
    198        && !bShowTeamChange
     194//   if( PlayerStats::getStats( SharedNetworkData::getInstance()->getHostID() ) )
     195//   {
     196//     PRINTF(0)("prefered team id: %i, noteam: %i\n", PlayerStats::getStats( SharedNetworkData::getInstance()->getHostID() )->getPreferedTeamId(), TEAM_NOTEAM);
     197//   }
     198
     199  // check if the menu should be removed and the game state should be entered
     200  if ( box != NULL &&
     201       PlayerStats::getStats( SharedNetworkData::getInstance()->getHostID() ) &&
     202       PlayerStats::getStats( SharedNetworkData::getInstance()->getHostID() )->getPreferedTeamId() != TEAM_NOTEAM &&
     203       !bShowTeamChange
    199204     )
    200205  {
     
    310315  assert( false );
    311316}
     317
    312318
    313319std::string MultiplayerTeamDeathmatch::getPlayableModelFileName( int userId, int team, ClassID classId )
     
    442448}
    443449
     450/**
     451 *  this handles team changes but only on the master server
     452 */
    444453void MultiplayerTeamDeathmatch::handleTeamChanges( )
    445454{
     
    458467      if ( stats.getPreferedTeamId() == TEAM_SPECTATOR || ( stats.getPreferedTeamId() >= 0 && stats.getPreferedTeamId() < numTeams ) )
    459468      {
    460         teamChange( stats.getUserId() );
     469        teamChange( stats.getAssignedUserId() );
    461470      }
    462471    }
     
    473482      {
    474483        stats.setPreferedTeamId( getRandomTeam() );
    475         teamChange( stats.getUserId() );
     484        teamChange( stats.getAssignedUserId() );
    476485      }
    477486    }
     
    479488}
    480489
     490
     491
     492/**
     493 * changes the team
     494 * @param userId the user changing team (userId)
     495 */
    481496void MultiplayerTeamDeathmatch::teamChange( int userId )
    482497{
     
    489504
    490505
    491   ClassID playableClassId = getPlayableClassId( userId, stats.getPreferedTeamId() );
    492   std::string playableModel = getPlayableModelFileName( userId, stats.getPreferedTeamId(), playableClassId );
    493   std::string playableTexture = getPlayableModelTextureFileName( userId, stats.getPreferedTeamId(), playableClassId );
    494   float       playableScale = getPlayableScale( userId, stats.getPreferedTeamId(), playableClassId );
     506  ClassID       playableClassId = getPlayableClassId( userId, stats.getPreferedTeamId() );
     507  std::string   playableModel    = getPlayableModelFileName( userId, stats.getPreferedTeamId(), playableClassId );
     508  std::string   playableTexture = getPlayableModelTextureFileName( userId, stats.getPreferedTeamId(), playableClassId );
     509  float         playableScale    = getPlayableScale( userId, stats.getPreferedTeamId(), playableClassId );
    495510
    496511  BaseObject * bo = Factory::fabricate( playableClassId );
     
    507522  playable.setSynchronized( true );
    508523
    509   stats.setTeamId( stats.getPreferedTeamId() );
    510524  stats.setPlayableClassId( playableClassId );
    511525  stats.setPlayableUniqueId( playable.getUniqueID() );
    512526  stats.setModelFileName( playableModel );
     527  stats.setTeamId( stats.getPreferedTeamId() );
     528
     529  playable.setTeam(stats.getPreferedTeamId());
     530
    513531
    514532  this->respawnPlayable( &playable, stats.getPreferedTeamId(), 0.0f );
     
    516534  if ( oldPlayable )
    517535  {
    518     //if ( userId == SharedNetworkData::getInstance()->getHostID() )
    519     //  State::getPlayer()->setPlayable( NULL );
    520536    delete oldPlayable;
    521537  }
    522538}
     539
    523540
    524541void MultiplayerTeamDeathmatch::onButtonExit( )
     
    558575}
    559576
    560   /**
    561    * function that processes events from the handler
    562    * @param event: the event
    563    * @todo replace SDLK_o with something from KeyMapper
    564    */
     577
     578/**
     579 * function that processes events from the handler
     580 * @param event: the event
     581 * @todo replace SDLK_o with something from KeyMapper
     582 */
    565583void MultiplayerTeamDeathmatch::process( const Event & event )
    566584{
     
    573591    if ( this->statsBox && !this->bLocalPlayerDead && event.bPressed )
    574592    {
    575       PRINTF(0)("hide stats\n");
     593      PRINTF(5)("hide stats\n");
    576594      this->hideStats();
    577595    }
    578596    else if ( !this->statsBox && event.bPressed )
    579597    {
    580       PRINTF(0)("show stats\n");
     598      PRINTF(5)("show stats\n");
    581599      this->showStats();
    582600    }
     
    740758  PlayerStats & killerStats = *PlayerStats::getStats( killerUserId );
    741759
    742   if ( killerStats.getPlayable() != killer || victimStats.getPlayable() != victim )
    743   {
    744     PRINTF(0)("killerStats.getPlayable() != killer || victimStats.getPlayable() != victim\n");
     760  if ( killerStats.getPlayable() == NULL || victimStats.getPlayable() == NULL)
     761  {
     762    PRINTF(0)("killerStats.getPlayable() != NULL || victimStats.getPlayable() != NULL\n");
    745763    PRINTF(0)("%x %x %x %x\n", killerStats.getPlayable(), killer, victimStats.getPlayable(), victim );
    746764    PRINTF(0)("%d %d %d %d\n", killerStats.getPlayable()->getUniqueID(), killer->getUniqueID(), victimStats.getPlayable()->getUniqueID(), victim->getUniqueID() );
     
    796814
    797815
     816/**
     817 * respawns a playable in the world via spawning points
     818 * @param playable the playable to respawn
     819 * @param teamId the teamId to use
     820 * @param delay time delay for delayed spawning
     821 */
    798822void MultiplayerTeamDeathmatch::respawnPlayable( Playable * playable, int teamId, float delay )
    799823{
  • trunk/src/util/object_manager.cc

    r9406 r9656  
    134134  if (omList != OM_INIT || omList == OM_SIZE)
    135135  {
    136     PRINT(0)(" +ObjectManager-LIST: '%s'==size='%d'==---\n", ObjectManager::OMListToString((OM_LIST)omList), this->objectLists[omList].size());
     136    PRINT(0)(" +ObjectManager-LIST: '%s'==size='%d'==---\n", ObjectManager::OMListToString((OM_LIST)omList).c_str(), this->objectLists[omList].size());
    137137  //  if (level >= 1)
    138138    {
     
    174174 * @returns the String transformed from omList.
    175175 */
    176 const char* ObjectManager::OMListToString(OM_LIST omList)
     176const std::string& ObjectManager::OMListToString(OM_LIST omList)
    177177{
    178178  if (omList == OM_INIT || omList == OM_SIZE)
    179     return "===invalid===";
     179    return ObjectManager::objectManagerListNames[OM_NULL];
    180180
    181181  printf("%d\n", omList);
     
    199199    }
    200200  }
    201   return OM_DEFAULT_LIST;
    202 }
    203 
    204 
    205 
    206 const char* ObjectManager::objectManagerListNames[] = {
     201  return OM_NULL;
     202}
     203
     204
     205
     206const std::string ObjectManager::objectManagerListNames[] = {
    207207    "null",
    208208    "dead",
  • trunk/src/util/object_manager.h

    r8068 r9656  
    9696
    9797  static OM_LIST StringToOMList(const std::string& listName);
    98   static const char* OMListToString(OM_LIST omList);
     98  static const std::string& OMListToString(OM_LIST omList);
    9999
    100100
     
    113113  EntityList                              objectLists[OM_SIZE];     //!< The ObjectLists.
    114114
    115   static const char*                      objectManagerListNames[]; //!< Names of all the lists
     115  static const std::string                objectManagerListNames[]; //!< Names of all the lists
    116116
    117117  EntityList                              reflectionList;           //!< A list of all reflected objects in the world
  • trunk/src/world_entities/WorldEntities.am

    r9235 r9656  
    55                world_entities/npcs/ground_turret.cc \
    66                world_entities/npcs/space_turret.cc \
     7                world_entities/npcs/network_turret.cc \
    78                world_entities/npcs/generic_npc.cc \
    89                world_entities/npcs/door.cc \
     
    7980                npcs/ground_turret.h \
    8081                npcs/space_turret.h \
     82                npcs/network_turret.h \
    8183                npcs/door.cc \
    8284                npcs/repair_station.h \
  • trunk/src/world_entities/bsp_entity.cc

    r9406 r9656  
    5454  this->bspManager = NULL;
    5555
    56   this->name_handle = registerVarId( new SynchronizeableString( &this->name, &this->name_write, "name" ) );
     56  this->name_handle = registerVarId( new SynchronizeableString( &this->name, &this->name_write, "name", PERMISSION_MASTER_SERVER ) );
    5757
    5858  this->setSynchronized( true );
  • trunk/src/world_entities/environments/model_entity.cc

    r9406 r9656  
    3636  this->speed = NULL;
    3737  this->momentum = NULL;
     38
     39  this->setSynchronized(true);
    3840
    3941  if (root != NULL)
  • trunk/src/world_entities/environments/water.cc

    r9406 r9656  
    5959  // To test the Wave equation
    6060  //this->wave(5.0,4.0, 1, 10);
    61  
    62   height_handle = registerVarId( new SynchronizeableFloat( &height, &height, "height" ) );
    63   resX_handle = registerVarId( new SynchronizeableUInt( &resX, &resX, "resX" ) );
    64   resY_handle = registerVarId( new SynchronizeableUInt( &resY, &resY, "resY" ) );
    65   sizeX_handle = registerVarId( new SynchronizeableFloat( &sizeX, &sizeX, "sizeX" ) );
    66   sizeY_handle = registerVarId( new SynchronizeableFloat( &sizeY, &sizeY, "sizeY" ) );
     61
     62  height_handle = registerVarId( new SynchronizeableFloat( &height, &height, "height", PERMISSION_MASTER_SERVER ) );
     63  resX_handle = registerVarId( new SynchronizeableUInt( &resX, &resX, "resX", PERMISSION_MASTER_SERVER ) );
     64  resY_handle = registerVarId( new SynchronizeableUInt( &resY, &resY, "resY", PERMISSION_MASTER_SERVER ) );
     65  sizeX_handle = registerVarId( new SynchronizeableFloat( &sizeX, &sizeX, "sizeX", PERMISSION_MASTER_SERVER ) );
     66  sizeY_handle = registerVarId( new SynchronizeableFloat( &sizeY, &sizeY, "sizeY", PERMISSION_MASTER_SERVER ) );
    6767}
    6868
     
    313313    this->rebuildGrid();
    314314  }
    315  
     315
    316316  WorldEntity::varChangeHandler( id );
    317317}
  • trunk/src/world_entities/npcs/ground_turret.cc

    r9406 r9656  
    3939 */
    4040GroundTurret::GroundTurret(const TiXmlElement* root)
    41   : NPC(root)
     41    : NPC(root)
    4242{
    4343  this->init();
     
    5252GroundTurret::~GroundTurret ()
    5353{
    54 
    5554}
    5655
     
    8079
    8180/**
    82  * loads a GroundTurret from a XML-element
     81 * @brief loads a GroundTurret from a XML-element
    8382 * @param root the XML-element to load from
    8483 * @todo make the class Loadable
     
    8887  // all the clases this Entity is directly derived from must be called in this way, to load all settings.
    8988  NPC::loadParams(root);
    90 
    9189
    9290  /**
     
    126124void GroundTurret::tick(float dt)
    127125{
    128   if(this->getHealth() > 0.0f && State::getPlayer() &&
    129      State::getPlayer()->getPlayable() &&
    130      State::getPlayer()->getPlayable()->distance(this) < 120) // HACK
     126  if(this->getHealth() > 0.0f
     127    ) // HACK <--- YOU ARE THE MOTHERFUCKER
    131128  {
    132   if (likely(this->left != NULL))
    133   {
    134 //    this->left->tickW(dt);
    135     this->left->requestAction(WA_SHOOT);
    136   }
    137   if (likely(this->right != NULL))
    138   {
    139 //    this->right->tickW(dt);
    140     this->right->requestAction(WA_SHOOT);
    141   }
     129    if (likely(this->left != NULL))
     130    {
     131      //    this->left->tickW(dt);
     132      this->left->requestAction(WA_SHOOT);
     133    }
     134    if (likely(this->right != NULL))
     135    {
     136      //    this->right->tickW(dt);
     137      this->right->requestAction(WA_SHOOT);
     138    }
    142139  }
    143140}
     
    164161void GroundTurret::postSpawn ()
    165162{
    166 
    167163}
    168164
     
    173169void GroundTurret::leftWorld ()
    174170{
    175 
    176171}
    177172
  • trunk/src/world_entities/npcs/ground_turret.h

    r9235 r9656  
    1515{
    1616
    17  public:
     17public:
    1818  GroundTurret(const TiXmlElement* root = NULL);
    1919  virtual ~GroundTurret();
    2020
    21   void init();
    2221  virtual void loadParams(const TiXmlElement* root);
    2322
     
    3029  virtual void tick(float time);
    3130
    32  private:
    33    PNode  weaponHolder[2];
    34    Weapon *left, *right;
     31private:
     32  void init();
     33
     34
     35private:
     36  PNode  weaponHolder[2];
     37  Weapon *left, *right;
    3538};
    3639
  • trunk/src/world_entities/npcs/space_turret.cc

    r9235 r9656  
    7474  this->weaponHolder[0].setParent(this);
    7575  this->weaponHolder[1].setParent(this);
     76
     77  this->wLeftHandle = registerVarId( new SynchronizeableString( &this->wLeft, &this->wLeft, "weapon-left", PERMISSION_MASTER_SERVER ) );
     78  this->wRightHandle = registerVarId( new SynchronizeableString( &this->wRight, &this->wRight, "weapon-right", PERMISSION_MASTER_SERVER ) );
     79
    7680}
    7781
     
    98102  if (this->left)
    99103  {
     104    this->wLeft = element->Value();
     105
    100106    this->left->setParent(this);
    101107    this->left->toList(this->getOMListNumber());
     
    110116  if (this->right)
    111117  {
     118    this->wRight = element->Value();
     119
    112120    this->right->setParent(this);
    113121    this->right->toList(this->getOMListNumber());
     
    117125  }
    118126}
     127
     128
     129/**
     130 * sets the left weapon called from net sync
     131 * @param wLeft the left weapon string
     132 */
     133void SpaceTurret::setWeaponLeft(const std::string& wLeft)
     134{
     135
     136}
     137
     138/**
     139 * sets the left weapon called from net sync
     140 * @param wRught the right weapon string
     141 */
     142void SpaceTurret::setWeaponRight(const std::string& wRight)
     143{}
    119144
    120145/**
     
    198223
    199224}
     225
     226
     227
     228/**
     229 * handler for changes on registred vars
     230 * @param id id's which changed
     231 */
     232void SpaceTurret::varChangeHandler( std::list< int > & id )
     233{
     234  if ( std::find( id.begin(), id.end(), this->wLeftHandle ) != id.end())
     235  {
     236    this->setWeaponLeft(this->wLeft);
     237  }
     238
     239  if ( std::find( id.begin(), id.end(), this->wRightHandle ) != id.end() )
     240  {
     241    this->setWeaponRight(this->wRight);
     242  }
     243
     244
     245  WorldEntity::varChangeHandler( id );
     246}
     247
  • trunk/src/world_entities/npcs/space_turret.h

    r9235 r9656  
    88
    99#include "npcs/npc.h"
     10
     11#include <string>
     12#include <list>
     13
    1014
    1115class Weapon;
     
    2024
    2125  virtual void loadParams(const TiXmlElement* root);
     26  virtual void varChangeHandler( std::list< int > & id );
     27
     28
     29  void setWeaponLeft(const std::string& wLeft);
     30  void setWeaponRight(const std::string& wRight);
    2231
    2332  virtual void postSpawn ();
     
    3645  PNode  weaponHolder[2];
    3746  Weapon *left, *right;
     47
     48  std::string wLeft;
     49  std::string wRight;
     50  int wLeftHandle;
     51  int wRightHandle;
    3852};
    3953
  • trunk/src/world_entities/playable.cc

    r9406 r9656  
    6868
    6969
    70   registerVar( new SynchronizeableInt( &score, &score, "score" ) );
     70  this->teamChangeHandler = registerVarId( new SynchronizeableInt( &this->teamId, &this->teamId, "team-id", PERMISSION_MASTER_SERVER ) );
     71
     72  registerVar( new SynchronizeableInt( &score, &score, "score", PERMISSION_MASTER_SERVER ) );
    7173  registerVar( new SynchronizeableBool( &bFire, &bFire, "bFire", PERMISSION_OWNER));
    7274}
     
    139141bool Playable::addWeapon(Weapon* weapon, int configID, int slotID)
    140142{
     143  weapon->setOwner(this->getOwner());
     144
     145
    141146  if(this->weaponMan.addWeapon(weapon, configID, slotID))
    142147  {
     
    272277  return false;
    273278}
     279
     280
     281/**
     282 * @brief sets the TeamID and all the properties needed to be visible on the Playable
     283 * @param teamID: the new TeamID of the Entity
     284 */
     285void Playable::setTeam(int teamID)
     286{
     287  /// Derive this function to make it look different with differen groups.
     288  PRINTF(4)("No special team specific function implemented for %s::%s in Team %d\n", this->getClassCName(), this->getCName(), teamID);
     289}
     290
    274291
    275292/**
     
    512529  "FirstPerson"
    513530};
     531
     532
     533/**
     534 * handler for changes on registred vars
     535 * @param id id's which changed
     536 */
     537void Playable::varChangeHandler( std::list< int > & id )
     538{
     539  if ( std::find( id.begin(), id.end(), this->teamChangeHandler) != id.end() )
     540  {
     541    this->setTeam(this->teamId);
     542  }
     543
     544  WorldEntity::varChangeHandler(id);
     545}
  • trunk/src/world_entities/playable.h

    r9406 r9656  
    1111#include "event.h"
    1212#include <vector>
     13#include <list>
    1314
    1415#include "world_entities/weapons/weapon_manager.h"
     
    4344
    4445  virtual void loadParams(const TiXmlElement* root);
     46  void varChangeHandler( std::list< int > & id );
    4547
    4648  // Weapon and Pickups
     
    6264  inline const std::vector<int>& getEventList() { return this->events; };
    6365
     66
    6467  // Camera and Playmode
    6568  void attachCamera();
     
    7275  void setPlayDirection(float angle, float dirX, float dirY, float dirZ, float speed = 0.0f);
    7376
     77  // Networking interface
    7478  inline void setScore( int score ) { this->score = score; }
    7579  inline int  getScore() { return this->score; }
     80  inline void setTeamId( int teamId) { this->teamId = teamId;}
     81  inline int getTeamId() const { return this->teamId; }
     82  virtual void setTeam(int teamID);
     83
    7684
    7785  void setEnterRadius(float radius) { this->enterRadius = radius; };
     
    8593  virtual void tick(float dt);
    8694
     95
     96  inline bool beFire() const { return this->bFire; }
     97  inline void fire(bool bF) { this->bFire = bF;}
     98
    8799  // Transformations:
    88100  static Playable::Playmode stringToPlaymode(const std::string& playmode);
    89101  static const std::string& playmodeToString(Playable::Playmode playmode);
    90102  static const std::string playmodeNames[];
    91 
    92   inline bool beFire(){ return this->bFire; }
    93   inline void fire(bool bF){ this->bFire = bF;}
    94103
    95104protected:
     
    117126
    118127  int                   score;              //!< players score
     128  int                   teamChangeHandler;  //!< handler id for team changes network sync
     129  int                   teamId;             //!< id of the current team
    119130
    120131  bool                  bDead;
     
    124135  float                 enterRadius;        //!< How far one can be away from the Playable to enter it.
    125136
    126   WorldEntity* collider;
     137  WorldEntity*          collider;
    127138};
    128139
  • trunk/src/world_entities/power_ups/param_power_up.cc

    r9406 r9656  
    4343  if( root != NULL)
    4444    this->loadParams(root);
    45  
    46   registerVar( new SynchronizeableInt( (int*)&type, (int*)&type, "type" ) );
    47   registerVar( new SynchronizeableFloat( &value, &value, "value" ) );
    48   registerVar( new SynchronizeableFloat( &max_value, &max_value, "max_value" ) );
    49   registerVar( new SynchronizeableFloat( &min_value, &min_value, "min_value" ) );
     45
     46  registerVar( new SynchronizeableInt( (int*)&type, (int*)&type, "type", PERMISSION_MASTER_SERVER ) );
     47  registerVar( new SynchronizeableFloat( &value, &value, "value", PERMISSION_MASTER_SERVER ) );
     48  registerVar( new SynchronizeableFloat( &max_value, &max_value, "max_value", PERMISSION_MASTER_SERVER ) );
     49  registerVar( new SynchronizeableFloat( &min_value, &min_value, "min_value", PERMISSION_MASTER_SERVER ) );
    5050}
    5151
  • trunk/src/world_entities/projectiles/guided_missile.h

    r9235 r9656  
    1313class ParticleEmitter;
    1414class FastFactory;
    15 class Aim;
    1615
    1716class GuidedMissile : public Projectile
  • trunk/src/world_entities/projectiles/laser.cc

    r9406 r9656  
    8888  }
    8989
    90   this->setDamage(0);
     90  this->setDamage(20);
    9191  this->setHealth(0);
    9292}
  • trunk/src/world_entities/projectiles/projectile.cc

    r9406 r9656  
    4545  this->explosionBuffer = NULL;
    4646  this->engineBuffer = NULL;
     47
     48  //this->addNodeFlags(PNODE_PROHIBIT_DELETE_WITH_PARENT);
    4749}
    4850
  • trunk/src/world_entities/script_trigger.cc

    r9406 r9656  
    4949 */
    5050ScriptTrigger::ScriptTrigger(const TiXmlElement* root)
    51 { PRINT(1)("testerror\n");
     51{
    5252  this->setClassID(CL_SCRIPT_TRIGGER, "ScriptTrigger");
    5353  this->toList(OM_COMMON);
  • trunk/src/world_entities/skybox.cc

    r9406 r9656  
    9696{
    9797  this->rebuild();
    98  
    99   textureName_handle = registerVarId( new SynchronizeableString( &textureName, &textureName, "textureName") );
    100   size_handle = registerVarId( new SynchronizeableFloat( &size, &size, "size" ) );
     98
     99  textureName_handle = registerVarId( new SynchronizeableString( &textureName, &textureName, "textureName", PERMISSION_MASTER_SERVER) );
     100  size_handle = registerVarId( new SynchronizeableFloat( &size, &size, "size", PERMISSION_MASTER_SERVER ) );
    101101}
    102102
     
    297297{
    298298  bool somethinChanged = false;
    299  
     299
    300300  if ( std::find( id.begin(), id.end(), textureName_handle ) != id.end() )
    301301  {
     
    303303    setTexture( textureName );
    304304  }
    305  
     305
    306306  if ( std::find( id.begin(), id.end(), size_handle ) != id.end() )
    307307  {
    308308    somethinChanged = true;
    309309  }
    310  
     310
    311311  rebuild();
    312  
     312
    313313  WorldEntity::varChangeHandler( id );
    314314}
  • trunk/src/world_entities/space_ships/hover.cc

    r9235 r9656  
    330330  this->shiftCoor (this->velocity * dt);
    331331
    332     // limit the maximum rotation speed.
     332  // limit the maximum rotation speed.
    333333  if (this->rotation != 0.0f)
    334334  {
  • trunk/src/world_entities/space_ships/space_ship.cc

    r9494 r9656  
    234234  this->burstSystem->setColor(1.0, .8,.8,.8,.0);
    235235
    236   registerVar( new SynchronizeableVector( &velocity, &velocity, "velocity" ) );
     236  registerVar( new SynchronizeableVector( &velocity, &velocity, "velocity", PERMISSION_MASTER_SERVER ) );
    237237  registerVar( new SynchronizeableQuaternion( &mouseDir, &mouseDir, "mousedir", PERMISSION_OWNER ) );
    238238
  • trunk/src/world_entities/space_ships/turbine_hover.cc

    r9494 r9656  
    9191
    9292  this->loadModel("models/ships/hoverglider_mainbody.obj");
     93
    9394}
    9495
     
    222223  registerVar( new SynchronizeableFloat( &cameraLook, &cameraLook, "cameraLook", PERMISSION_OWNER ) );
    223224  registerVar( new SynchronizeableFloat( &rotation, &rotation, "rotation", PERMISSION_OWNER ) );
     225
     226  if( State::isOnline())
     227    toList( OM_PLAYERS );
    224228}
    225229
     
    231235{
    232236  Playable::loadParams(root);
     237}
     238
     239
     240void TurbineHover::setBoostColor(const Color& color)
     241{
     242  this->burstSystem->setColor(0.0, color);
     243  this->burstSystem->setColor(0.2, color * 0.6);
     244  this->burstSystem->setColor(0.5, color * .3 + Color(0.5, 0.5, 0.8, 0.3));
     245  this->burstSystem->setColor(1.0, 0.8, 0.8, 0.8, 0.0);
     246
     247  printf(":::::::::::::::::::::::\n");
     248  this->burstSystem->debug();
    233249}
    234250
     
    256272
    257273}
     274
     275void TurbineHover::setTeam(int teamID)
     276{
     277  printf("::::::::::::::::: TEAM ::: %d\n", teamID);
     278  if (teamID == 0)
     279  {
     280    this->setBoostColor(Color::blue);
     281  }
     282  else if (teamID == 1)
     283  {
     284    this->setBoostColor(Color::red);
     285  }
     286
     287  ///HACK this is very much hard coded.set the owner of the weapons
     288  this->getWeaponManager().getWeapon(0)->setOwner(this->getOwner());
     289  this->getWeaponManager().getWeapon(1)->setOwner(this->getOwner());
     290
     291  //choose collision list
     292  if( State::isOnline())
     293  {
     294    if( teamID == 0)
     295      toList( OM_GROUP_00 );
     296    else if(teamID == 1)
     297      toList( OM_GROUP_01);
     298  }
     299
     300
     301  // set the local team id, very important
     302  this->setTeamId(teamID);
     303}
     304
    258305
    259306
     
    527574  }
    528575}
     576
     577
     578/**
     579 *  respawning function called by the GameRules
     580 */
     581void TurbineHover::respawn( )
     582{
     583
     584  Playable::respawn();
     585}
  • trunk/src/world_entities/space_ships/turbine_hover.h

    r8490 r9656  
    99
    1010#include "playable.h"
     11
     12#include "color.h"
    1113
    1214// Forward Declaration
     
    2123    virtual ~TurbineHover();
    2224
     25    void setBoostColor(const Color& color);
     26
    2327    virtual void loadParams(const TiXmlElement* root);
    2428    virtual void setPlayDirection(const Quaternion& rot, float speed = 0.0f);
     
    2630    virtual void leave();
    2731
     32    virtual void setTeam(int teamID);
     33
    2834    virtual void postSpawn();
    2935    virtual void leftWorld();
     36    virtual void respawn();
    3037
    3138    virtual void collidesWith(WorldEntity* entity, const Vector& location);
  • trunk/src/world_entities/spawning_point.cc

    r9494 r9656  
    207207void SpawningPoint::sendRespawnMessage( int uniqueId )
    208208{
    209 #warning this byte array is not being deleted according to valginrd
    210   byte * buf = new byte[2*INTSIZE];
     209  byte buf[2*INTSIZE];
    211210
    212211  assert( Converter::intToByteArray( this->getUniqueID(), buf, INTSIZE ) == INTSIZE );
    213212  assert( Converter::intToByteArray( uniqueId, buf + INTSIZE, INTSIZE ) == INTSIZE );
    214213
    215   MessageManager::getInstance()->sendMessage( MSGID_RESPAWN, buf, 2*INTSIZE, RT_ALL_BUT_ME, 0, MP_HIGHBANDWIDTH );
    216 }
    217 
    218 bool SpawningPoint::respawnMessageHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId )
     214  MessageManager::getInstance()->sendMessage( MSGID_RESPAWN, buf, 2*INTSIZE, RT_ALL_BUT_ME, NET_UNASSIGNED, MP_HIGHBANDWIDTH );
     215}
     216
     217/**
     218 * message handler for respawn message
     219 */
     220bool SpawningPoint::respawnMessageHandler( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId  )
    219221{
    220222  if ( SharedNetworkData::getInstance()->isMasterServer() /*|| SharedNetworkData::getInstance()->isProxyServerActive()*/)
  • trunk/src/world_entities/spawning_point.h

    r9494 r9656  
    7070
    7171    void sendRespawnMessage( int uniqueId );
    72     static bool respawnMessageHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId );
     72    static bool respawnMessageHandler( MessageType messageType, byte * data, int dataLength, void * someData, int senderId, int destinationId );
    7373
    7474
  • trunk/src/world_entities/weapons/aim.cc

    r9406 r9656  
    5050Aim::~Aim ()
    5151{
    52   if (this->material)
    53     delete this->material;
    54 
    5552/*  if (this->text != NULL)
    5653    delete this->text;*/
     
    7067
    7168  this->setBindNode(this);
    72   this->material = new Material;
    7369  this->source = NULL;
    7470
    75   this->range = 10000;
     71  this->range = 1000;
    7672  this->angle = M_PI_4;
    77   this->group = OM_GROUP_01;
     73  this->targetGroup = OM_GROUP_01;
    7874  this->anim = new tAnimation<Aim>(this, &Aim::setSize);
    7975  this->anim->setInfinity(ANIM_INF_CONSTANT);
     
    10399  LoadParam(root, "rotation-speed", this, Aim, setRotationSpeed)
    104100      .describe("the Speed with which the Aim should rotate");
     101
     102  LoadParam(root, "target-group", this, Aim, setTargetGroupS);
    105103}
    106104
     
    108106{
    109107  ObjectManager::EntityList::iterator entity;
    110 
    111   for (entity = State::getObjectManager()->getObjectList(group).begin();
    112        entity != State::getObjectManager()->getObjectList(group).end();
     108  //printf("%d\n", this->targetGroup);
     109  for (entity = State::getObjectManager()->getObjectList(this->targetGroup).begin();
     110       entity != State::getObjectManager()->getObjectList(this->targetGroup).end();
    113111       entity ++)
    114112  {
    115113    diffVec = ( (*entity)->getAbsCoor() - this->source->getAbsCoor() );
    116114
    117     if ( diffVec.len() < range &&  acos( (this->source->getAbsDirX()).dot(diffVec)/(diffVec.len() * (this->source->getAbsDirX()).len() ) )  < angle)
     115    if ( diffVec.len() < range )//&&  acos( (this->source->getAbsDirX()).dot(diffVec)/(diffVec.len() * (this->source->getAbsDirX()).len() ) )  < angle)
    118116    {
    119117      //if (this->getParent() != (*entity))
    120118      {
     119        printf("found target::: %d %s::%s\n", (*entity)->getOMListNumber(), (*entity)->getClassCName(), (*entity)->getCName());
    121120        this->anim->replay();
    122121        this->setParentSoft(*entity, 5);
     
    128127   //if no target found:
    129128   this->setParent(PNode::getNullParent());
    130 
    131 
    132 
    133 }
    134 
     129}
     130
     131void Aim::setTargetGroupS(const std::string& groupName)
     132{
     133  OM_LIST id = ObjectManager::StringToOMList(groupName);
     134  if (id != OM_NULL)
     135    this->setTargetGroup(id);
     136  else
     137    PRINTF(2)("List %s not found for targetting\n", groupName.c_str());
     138}
    135139
    136140/**
     
    149153void Aim::setTexture(const std::string& textureFile)
    150154{
    151   this->material->setDiffuseMap(textureFile);
     155  this->material.setDiffuseMap(textureFile);
    152156}
    153157
     
    170174//only look for target if the aim hasn`t locked a target yet or if the actual target is out of range
    171175   if(this->getParent() == PNode::getNullParent() ||
    172       diffVec.len() > range ||
    173      ( acos( (this->source->getAbsDirX()).dot(diffVec)/(diffVec.len() * (this->source->getAbsDirX()).len() ) ) > angle))
     176      diffVec.len() > range )// ||
     177     //( acos( (this->source->getAbsDirX()).dot(diffVec)/(diffVec.len() * (this->source->getAbsDirX()).len() ) ) > angle))
    174178    {
    175179     this->setParentSoft(PNode::getNullParent(),5);
     
    213217
    214218  glRotatef(this->getAbsDir2D(), 0,0,1);
    215   this->material->select();
     219  this->material.select();
    216220  glBegin(GL_TRIANGLE_STRIP);
    217221  glTexCoord2f(0, 0);
  • trunk/src/world_entities/weapons/aim.h

    r7221 r9656  
    1111#include "object_manager.h"
    1212
     13#include "material.h"
     14
    1315// FORWARD DECLARATION
    1416class Model;
    1517class Text;
    16 class Material;
    1718class TiXmlElement;
    1819template<class T> class tAnimation;
     
    2526 * Also the Aim is a Element2D, as it draws a cross onto the Target.
    2627 */
    27 class Aim : public PNode, public Element2D {
     28class Aim : public PNode, public Element2D
     29{
    2830
    29  public:
     31public:
    3032  Aim(PNode* source, const TiXmlElement* root = NULL);
    3133  virtual ~Aim();
    3234
    33   void init();
    3435  virtual void loadParams(const TiXmlElement* root);
    3536
     
    3738
    3839  inline void selectTarget(PNode* target) { this->setParent(target); };
    39   inline PNode* getTarget(PNode* target) { return this->getParent(); };
     40  inline PNode* getTarget(PNode* target) const { return this->getParent(); };
    4041
    4142  void searchTarget();
    4243
    43   void setRange(float range){this->range = range;};
    44   void setAngle(float angle){this->angle = angle;};
    45   void setGroup(OM_LIST group){this->group = group;};
     44  void setRange(float range) {this->range = range;};
     45  void setAngle(float angle) {this->angle = angle;};
     46  void setTargetGroup(OM_LIST group) { this->targetGroup = group; };
     47  void setTargetGroupS(const std::string& grounName);
    4648
    4749  void setSize(float size);
     
    5355  virtual void draw() const;
    5456
    55  private:
    56    Material*        material;             //!< a material for the Aim.
    57    float            rotationSpeed;        //!< Speed of the Rotation.
    58    tAnimation<Aim>* anim;
     57private:
     58  void init();
    5959
    60    float            range;                //!<
    61    float            angle;                //!<
    62    Vector           diffVec;
    63    OM_LIST          group;
    6460
    65    PNode*           source;               //!< Where this Shot has come from.
     61private:
     62  Material         material;             //!< a material for the Aim.
     63  float            rotationSpeed;        //!< Speed of the Rotation.
     64  tAnimation<Aim>* anim;
    6665
    67    Text*            text;                 //!< A Text to display onto this Node. (distance to Target)
     66  float            range;                //!<
     67  float            angle;                //!<
     68  Vector           diffVec;
     69  OM_LIST          targetGroup;
     70
     71  PNode*           source;               //!< Where this Shot has come from.
     72
     73  //   Text             text;                 //!< A Text to display onto this Node. (distance to Target)
    6874};
    6975
  • trunk/src/world_entities/weapons/aiming_turret.cc

    r9406 r9656  
    3838*/
    3939AimingTurret::AimingTurret ()
    40   : Weapon()
     40    : Weapon(), target(this)
    4141{
    4242  this->init();
     
    4646
    4747AimingTurret::AimingTurret(const TiXmlElement* root)
     48    : target(this)
    4849{
    4950  this->init();
     
    5859{
    5960  // model will be deleted from WorldEntity-destructor
    60 //  delete this->target;
     61  //  delete this->target;
    6162}
    6263
     
    9192  //this->getProjectileFactory()->prepare(100);
    9293
    93   this->target = new Aim(this);
    94   this->target->setVisibility(false);
    95   this->target->setRange(400);
    96   this->target->setAngle(M_PI_2);
     94  this->target.addNodeFlags(PNODE_PROHIBIT_DELETE_WITH_PARENT | PNODE_PROHIBIT_CHILD_DELETE);
     95  this->target.setVisibility(false);
     96  this->target.setRange(400);
     97  this->target.setAngle(M_PI_2);
    9798
    9899  this->setActionSound(WA_SHOOT, "sound/explosions/explosion_3.wav");
     
    110111void AimingTurret::activate()
    111112{
    112   this->target->setVisibility(true);
     113  this->target.setVisibility(true);
    113114}
    114115
    115116void AimingTurret::deactivate()
    116117{
    117   this->target->setVisibility(false);
     118  this->target.setVisibility(false);
    118119}
    119120
     
    123124    return;
    124125  Quaternion quat;
    125   Vector direction = this->target->getAbsCoor() - this->getAbsCoor();
     126  Vector direction = this->target.getAbsCoor() - this->getAbsCoor();
    126127
    127128  direction.normalize();
    128129
    129130  if (likely (this->getParent() != NULL))
    130     quat = Quaternion(direction, this->getParent()->getAbsDir().apply(Vector(0,1,0))) * Quaternion ( -M_PI_2, Vector(0,1,0)) ;
     131    //quat = Quaternion(direction, this->getParent()->getAbsDirY()) * Quaternion ( -M_PI_2, Vector(0,1,0)) ;
     132    quat = Quaternion ( M_PI_2, this->getParent()->getAbsDirY()) * Quaternion::lookAt(this->getAbsCoor(), this->target.getAbsCoor(), this->getParent()->getAbsDirY());
    131133  else
    132     quat = Quaternion(direction, Vector(0,1,0)) * Quaternion ( -M_PI_2, Vector(0,1,0)) ;
     134    //quat = Quaternion(direction, Vector(0,1,0)) * Quaternion ( -M_PI_2, Vector(0,1,0)) ;
     135    quat = Quaternion ( M_PI_2, Vector(0,1,0)) * Quaternion::lookAt(this->getAbsCoor(), this->target.getAbsCoor(), Vector(0,1,0));
    133136
    134137  this->setAbsDirSoft(quat, 5);
    135138
    136   this->target->tick(dt);
     139  this->target.tick(dt);
    137140}
    138141
     
    143146    return;
    144147
    145   pj->setVelocity(/*this->getVelocity()+*/(this->getAbsDir().apply(Vector(1,0,0))*250.0 + VECTOR_RAND(13)
    146             /*target->getAbsCoor() - this->getAbsCoor()*/)*.5);//this->getVelocity());
     148  pj->setVelocity(/*this->getVelocity()+*/(this->getAbsDirX()*250.0 + VECTOR_RAND(4)
     149                                          /*target.getAbsCoor() - this->getAbsCoor()*/)*.5);//this->getVelocity());
    147150
    148151  pj->setParent(PNode::getNullParent());
  • trunk/src/world_entities/weapons/aiming_turret.h

    r8777 r9656  
    88
    99#include "weapon.h"
    10 
     10#include "aim.h"
    1111/* FORWARD DECLARATION */
    12 class Aim;
    1312
    1413class AimingTurret : public Weapon
    15   {
    16   public:
    17     AimingTurret ();
    18     AimingTurret(const TiXmlElement* root);
    19     virtual ~AimingTurret ();
     14{
     15public:
     16  AimingTurret ();
     17  AimingTurret(const TiXmlElement* root);
     18  virtual ~AimingTurret ();
    2019
    21     void init();
    22     virtual void loadParams(const TiXmlElement* root);
     20  virtual void loadParams(const TiXmlElement* root);
    2321
    24     virtual void activate();
    25     virtual void deactivate();
     22  void setTargetGroup(OM_LIST targetGroup) { this->target.setTargetGroup(targetGroup); };
    2623
    27     virtual void tick(float dt);
    28     virtual void fire();
     24  virtual void activate();
     25  virtual void deactivate();
     26
     27  virtual void tick(float dt);
     28  virtual void fire();
    2929
    3030
    31     virtual void draw() const;
     31  virtual void draw() const;
    3232
    33   private:
    34     Aim*          target;
    35   };
     33private:
     34  void init();
     35
     36private:
     37  Aim           target;
     38};
    3639
    3740#endif /* _AIMING_TURRET_H */
  • trunk/src/world_entities/weapons/laser_cannon.cc

    r9235 r9656  
    121121    return;
    122122
     123  // make this to let the onKill(...) fuction get the stuff
     124  pj->setOwner(this->getOwner());
     125
    123126  pj->setParent(PNode::getNullParent());
    124127
  • trunk/src/world_entities/weapons/targeting_turret.cc

    r9406 r9656  
    1717#include "targeting_turret.h"
    1818
    19 #include "weapon_manager.h"
    20 #include "aim.h"
    21 #include "world_entities/projectiles/projectile.h"
     19#include "projectiles/projectile.h"
    2220
    2321#include "model.h"
     
    2523#include "animation3d.h"
    2624
     25#include "util/loading/load_param.h"
    2726#include "util/loading/factory.h"
    2827
     
    3029
    3130
    32 
    33 
    34 /**
    35  *  standard constructor
    36 
    37    creates a new weapon
    38 */
    39 TargetingTurret::TargetingTurret ()
    40   : Weapon()
    41 {
    42   this->init();
    43 
    44 }
    45 
    46 
    4731TargetingTurret::TargetingTurret(const TiXmlElement* root)
     32  : target(this)
    4833{
    4934  this->init();
     
    9176  //this->getProjectileFactory()->prepare(100);
    9277
    93   this->target = new Aim(this);
    94   this->target->setVisibility(false);
    95   this->target->setRange(1000);
    96   this->target->setAngle(M_PI_4);
    97   this->lockedTarget = this->target;
     78  this->target.setVisibility(false);
     79  this->target.addNodeFlags(PNODE_PROHIBIT_DELETE_WITH_PARENT | PNODE_PROHIBIT_CHILD_DELETE);
     80  this->target.setRange(1000);
     81  this->target.setAngle(M_PI_4);
     82  this->lockedTarget = &this->target;
    9883
    9984  this->lockedTime = 0;
     
    11297  Weapon::loadParams(root);
    11398
     99  LoadParam(root, "target-group", &target, Aim, setTargetGroupS);
     100
    114101}
    115102
     
    122109void TargetingTurret::deactivate()
    123110{
    124   this->target->setVisibility(false);
     111  this->target.setVisibility(false);
    125112}
    126113
     
    130117    return;
    131118
     119  this->target.tick(dt);
     120
    132121  if( lockedTime >= neededLockTime )
    133122   {
    134     lockedTarget = this->target->getParent();
     123    lockedTarget = this->target.getParent();
    135124    lockedTime = 0;
    136125   }
    137126
    138   this->target->tick(dt);
    139127
    140   if(this->target->getParent() == PNode::getNullParent())
     128  if(this->target.getParent() == PNode::getNullParent())
    141129   lockedTime = 0;
    142130  else
     
    159147  pj->setAbsDir(this->getAbsDir());
    160148  pj->activate();
    161 
    162149}
    163150
  • trunk/src/world_entities/weapons/targeting_turret.h

    r8777 r9656  
    88
    99#include "weapon.h"
    10 
    11 /* FORWARD DECLARATION */
    12 class Aim;
     10#include "aim.h"
    1311
    1412class TargetingTurret : public Weapon
    15   {
    16   public:
    17     TargetingTurret ();
    18     TargetingTurret(const TiXmlElement* root);
    19     virtual ~TargetingTurret ();
     13{
     14public:
     15  TargetingTurret(const TiXmlElement* root = NULL);
     16  virtual ~TargetingTurret ();
    2017
    21     void init();
    22     virtual void loadParams(const TiXmlElement* root);
     18  virtual void loadParams(const TiXmlElement* root);
    2319
    24     virtual void activate();
    25     virtual void deactivate();
     20  virtual void activate();
     21  virtual void deactivate();
    2622
    27     virtual void tick(float dt);
    28     virtual void fire();
     23  virtual void tick(float dt);
     24  virtual void fire();
    2925
    30     virtual void draw() const;
     26  virtual void draw() const;
    3127
    32   private:
    33     Aim*           target;
    34     PNode*         lockedTarget;
    35     float          lockedTime;
    36     float          neededLockTime;
    37   };
     28  void setTargetGroup(OM_LIST targetGroup) { this->target.setTargetGroup(targetGroup); };
     29  const PNode* getLockedTarget() const { return lockedTarget; };
     30
     31private:
     32  void init();
     33
     34private:
     35  Aim            target;
     36  PNode*         lockedTarget;
     37  float          lockedTime;
     38  float          neededLockTime;
     39};
    3840
    3941#endif /* _TARGETING_TURRET_H */
  • trunk/src/world_entities/weapons/test_gun.cc

    r9002 r9656  
    177177  if (pj == NULL)
    178178    return;
     179
     180  // set the owner
     181  pj->setOwner(this->getOwner());
    179182
    180183  pj->setParent(PNode::getNullParent());
  • trunk/src/world_entities/world_entity.cc

    r9494 r9656  
    2828#include "util/loading/resource_manager.h"
    2929#include "util/loading/load_param.h"
    30 #include "vector.h"
    3130#include "obb_tree.h"
    3231
     
    8685  this->toList(OM_NULL);
    8786
    88   registerVar( new SynchronizeableString( &this->md2TextureFileName, &this->md2TextureFileName, "md2TextureFileName" ) );
    89   modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName" ) );
    90   scaling_handle = registerVarId( new SynchronizeableFloat( &scaling, &scaling, "scaling" ) );
    91   list_handle = registerVarId( new SynchronizeableInt( (int*)&objectListNumber, &list_write, "list" ) );
    92 
    93   health_handle = registerVarId( new SynchronizeableFloat( &this->health, &this->health_write, "health" ) );
    94   healthMax_handle = registerVarId( new SynchronizeableFloat( &this->healthMax, &this->healthMax_write, "maxHealth" ) );
     87  registerVar( new SynchronizeableString( &this->md2TextureFileName, &this->md2TextureFileName, "md2TextureFileName", PERMISSION_MASTER_SERVER ) );
     88  modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName", PERMISSION_MASTER_SERVER ) );
     89  scaling_handle = registerVarId( new SynchronizeableFloat( &scaling, &scaling, "scaling", PERMISSION_MASTER_SERVER ) );
     90  list_handle = registerVarId( new SynchronizeableInt( (int*)&objectListNumber, &list_write, "list", PERMISSION_MASTER_SERVER ) );
     91
     92  health_handle = registerVarId( new SynchronizeableFloat( &this->health, &this->health_write, "health", PERMISSION_MASTER_SERVER ) );
     93  healthMax_handle = registerVarId( new SynchronizeableFloat( &this->healthMax, &this->healthMax_write, "maxHealth", PERMISSION_MASTER_SERVER ) );
    9594}
    9695
     
    141140  .describe("The Health the WorldEntity has at this moment")
    142141  .defaultValues(1.0f);
     142
     143  LoadParam(root, "list", this, WorldEntity, toListS);
    143144}
    144145
     
    478479}
    479480
     481void WorldEntity::toListS(const std::string& listName)
     482{
     483  OM_LIST id = ObjectManager::StringToOMList(listName);
     484  if (id != OM_NULL)
     485    this->toList(id);
     486  else
     487    PRINTF(2)("List %s not found\n", listName.c_str());
     488}
     489
     490
    480491void WorldEntity::toReflectionList()
    481492{
     
    822833  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassCName(), this->getCName());
    823834  this->debugNode();
    824   PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
     835  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber).c_str(), this->models.size());
    825836  for (unsigned int i = 0; i < this->models.size(); i++)
    826837  {
  • trunk/src/world_entities/world_entity.h

    r9298 r9656  
    115115  /* --- Object Manager Block --- */
    116116  void toList(OM_LIST list);
     117  void toListS(const std::string& listName);
    117118
    118119  void toReflectionList();
Note: See TracChangeset for help on using the changeset viewer.