stage.hh

Go to the documentation of this file.
00001 #ifndef STG_H
00002 #define STG_H
00003 /*
00004  *  Stage : a multi-robot simulator. Part of the Player Project.
00005  * 
00006  *  Copyright (C) 2001-2009 Richard Vaughan, Brian Gerkey, Andrew
00007  *  Howard, Toby Collett, Reed Hedges, Alex Couture-Beil, Jeremy
00008  *  Asher, Pooya Karimian
00009  *
00010  *  This program is free software; you can redistribute it and/or modify
00011  *  it under the terms of the GNU General Public License as published by
00012  *  the Free Software Foundation; either version 2 of the License, or
00013  *  (at your option) any later version.
00014  *
00015  *  This program is distributed in the hope that it will be useful,
00016  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00017  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00018  *  GNU General Public License for more details.
00019  *
00020  *  You should have received a copy of the GNU General Public License
00021  *  along with this program; if not, write to the Free Software
00022  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00023  *
00024  */
00025 
00033 // C libs
00034 #include <unistd.h>
00035 #include <stdint.h> // for portable int types eg. uint32_t
00036 #include <assert.h>
00037 #include <stdlib.h>
00038 #include <stdio.h>
00039 #include <string.h>
00040 #include <sys/types.h>
00041 #include <sys/time.h>
00042 #include <pthread.h> 
00043 
00044 // C++ libs
00045 #include <cmath>
00046 #include <iostream>
00047 #include <vector>
00048 #include <list>
00049 #include <map>
00050 #include <ext/hash_map>
00051 #include <set>
00052 #include <queue>
00053 #include <algorithm>
00054 
00055 
00056 // FLTK Gui includes
00057 #include <FL/Fl.H>
00058 #include <FL/Fl_Box.H>
00059 #include <FL/Fl_Gl_Window.H>
00060 #include <FL/Fl_Menu_Bar.H>
00061 #include <FL/Fl_Window.H>
00062 #include <FL/fl_draw.H>
00063 #include <FL/gl.h> // FLTK takes care of platform-specific GL stuff
00064 // except GLU & GLUT
00065 #ifdef __APPLE__
00066 #include <OpenGL/glu.h>
00067 //#include <GLUT/glut.h>
00068 #else
00069 #include <GL/glu.h>
00070 //#include <GL/glut.h>
00071 #endif 
00072 
00074 namespace Stg 
00075 {
00076   // forward declare
00077   class Block;
00078   class Canvas;
00079   class Cell;
00080   class Worldfile;
00081   class World;
00082   class WorldGui;
00083   class Model;
00084   class OptionsDlg;
00085   class Camera;
00086   class FileManager;
00087   class Option;
00088     
00090   typedef std::set<Model*> ModelPtrSet;
00092   typedef std::vector<Model*> ModelPtrVec;
00094   typedef std::vector<Block*> BlockPtrVec;
00096   typedef std::vector<Cell*> CellPtrVec;
00097 
00099   void Init( int* argc, char** argv[] );
00100 
00102   bool InitDone();
00103   
00106   const char* Version();
00107 
00110   typedef enum {
00111     MODEL_TYPE_PLAIN = 0,
00112     MODEL_TYPE_LASER,
00113     MODEL_TYPE_FIDUCIAL,
00114     MODEL_TYPE_RANGER,
00115     MODEL_TYPE_POSITION,
00116     MODEL_TYPE_BLOBFINDER,
00117     MODEL_TYPE_BLINKENLIGHT,
00118     MODEL_TYPE_CAMERA,
00119         MODEL_TYPE_GRIPPER,
00120         MODEL_TYPE_ACTUATOR,
00121         MODEL_TYPE_LOADCELL,
00122         MODEL_TYPE_LIGHTINDICATOR,
00123     MODEL_TYPE_COUNT // must be the last entry, to count the number of types
00124   } stg_model_type_t;
00125     
00127   const char COPYRIGHT[] =                     
00128     "Copyright Richard Vaughan and contributors 2000-2009";
00129 
00131   const char AUTHORS[] =                    
00132     "Richard Vaughan, Brian Gerkey, Andrew Howard, Reed Hedges, Pooya Karimian, Toby Collett, Jeremy Asher, Alex Couture-Beil and contributors.";
00133 
00135   const char WEBSITE[] = "http://playerstage.org";
00136 
00138   const char DESCRIPTION[] =                       
00139     "Robot simulation library\nPart of the Player Project";
00140 
00142   const char LICENSE[] = 
00143     "Stage robot simulation library\n"                  \
00144     "Copyright (C) 2000-2009 Richard Vaughan and contributors\n"    \
00145     "Part of the Player Project [http://playerstage.org]\n"     \
00146     "\n"                                \
00147     "This program is free software; you can redistribute it and/or\n"   \
00148     "modify it under the terms of the GNU General Public License\n" \
00149     "as published by the Free Software Foundation; either version 2\n"  \
00150     "of the License, or (at your option) any later version.\n"      \
00151     "\n"                                \
00152     "This program is distributed in the hope that it will be useful,\n" \
00153     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"  \
00154     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"   \
00155     "GNU General Public License for more details.\n"            \
00156     "\n"                                \
00157     "You should have received a copy of the GNU General Public License\n" \
00158     "along with this program; if not, write to the Free Software\n" \
00159     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n" \
00160     "\n"                                \
00161     "The text of the license may also be available online at\n"     \
00162     "http://www.gnu.org/licenses/old-licenses/gpl-2.0.html\n";
00163   
00165   const uint32_t TOKEN_MAX = 64;
00166 
00168   const double thousand = 1e3;
00169 
00171   const double million = 1e6;
00172 
00174   const double billion = 1e9;
00175 
00177   inline double rtod( double r ){ return( r*180.0/M_PI ); }
00178   
00180   inline double dtor( double d ){ return( d*M_PI/180.0 ); }
00181   
00183   inline double normalize( double a )
00184   {
00185      while( a < -M_PI ) a += 2.0*M_PI;
00186      while( a >  M_PI ) a -= 2.0*M_PI;   
00187      return a;
00188   };
00189 
00191   inline int sgn( int a){ return( a<0 ? -1 : 1); }
00192 
00194   inline double sgn( double a){ return( a<0 ? -1.0 : 1.0); }
00195   
00197   enum { FiducialNone = 0 };
00198 
00200   typedef uint32_t stg_id_t;
00201 
00203   typedef double stg_meters_t;
00204 
00206   typedef double stg_radians_t;
00207 
00209   typedef struct timeval stg_time_t;
00210 
00212   typedef unsigned long stg_msec_t;
00213 
00215   typedef uint64_t stg_usec_t;
00216 
00218   typedef double stg_kg_t; // Kilograms (mass)
00219 
00221   typedef double stg_joules_t;
00222 
00224   typedef double stg_watts_t;
00225   
00227   typedef bool stg_bool_t;
00228   
00229   class Color
00230   {
00231   public:
00232     float r,g,b,a;
00233     
00234     Color( float r, float g, float b, float a=1.0 );
00235     
00239     Color( const char* name );  
00240     
00241     Color();
00242     
00243     bool operator!=( const Color& other );
00244     bool operator==( const Color& other );
00245     static Color RandomColor();
00246     void Print( const char* prefix );
00247   };
00248   
00250   class Size
00251   {
00252   public:
00253     stg_meters_t x, y, z;
00254     
00255     Size( stg_meters_t x, 
00256           stg_meters_t y, 
00257           stg_meters_t z )
00258       : x(x), y(y), z(z)
00259     {/*empty*/}
00260     
00262     Size() : x( 0.4 ), y( 0.4 ), z( 1.0 )
00263     {/*empty*/} 
00264     
00265     void Load( Worldfile* wf, int section, const char* keyword );
00266     void Save( Worldfile* wf, int section, const char* keyword );
00267   };
00268   
00270   class Pose
00271   {
00272   public:
00273     stg_meters_t x, y, z;
00274     stg_radians_t a;
00275     
00276     Pose( stg_meters_t x, 
00277           stg_meters_t y, 
00278           stg_meters_t z,
00279           stg_radians_t a ) 
00280       : x(x), y(y), z(z), a(a)
00281     { /*empty*/ }
00282     
00283     Pose() : x(0.0), y(0.0), z(0.0), a(0.0)
00284     { /*empty*/ }        
00285     
00286     virtual ~Pose(){};
00287     
00290     static Pose Random( stg_meters_t xmin, stg_meters_t xmax, 
00291                         stg_meters_t ymin, stg_meters_t ymax )
00292     {        
00293       return Pose( xmin + drand48() * (xmax-xmin),
00294                                      ymin + drand48() * (ymax-ymin),
00295                                      0, 
00296                                      normalize( drand48() * (2.0 * M_PI) ));
00297     }
00298     
00302     virtual void Print( const char* prefix )
00303     {
00304       printf( "%s pose [x:%.3f y:%.3f z:%.3f a:%.3f]\n",
00305               prefix, x,y,z,a );
00306     }
00307     
00308     std::string String()
00309     {
00310       char buf[256];
00311       snprintf( buf, 256, "[ %.3f %.3f %.3f %.3f ]",
00312                 x,y,z,a );
00313       return std::string(buf);
00314     }
00315     
00316     /* returns true iff all components of the velocity are zero. */
00317     bool IsZero() const { return( !(x || y || z || a )); };
00318     
00320     void Zero(){ x=y=z=a=0.0; }
00321     
00322     void Load( Worldfile* wf, int section, const char* keyword );
00323     void Save( Worldfile* wf, int section, const char* keyword );
00324     
00325     inline Pose operator+( const Pose& p )
00326     {
00327       const double cosa = cos(a);
00328       const double sina = sin(a);
00329       
00330       return Pose( x + p.x * cosa - p.y * sina,
00331                    y + p.x * sina + p.y * cosa,
00332                    z + p.z,
00333                    normalize(a + p.a) );     
00334     }   
00335   };
00336   
00337   
00339   class Velocity : public Pose
00340   {
00341   public:
00347     Velocity( stg_meters_t x, 
00348                   stg_meters_t y, 
00349                   stg_meters_t z,
00350                   stg_radians_t a ) 
00351     { /*empty*/ }
00352     
00353     Velocity()
00354     { /*empty*/ }        
00355     
00359     virtual void Print( const char* prefix )
00360     {
00361       printf( "%s velocity [x:%.3f y:%.3f z:%3.f a:%.3f]\n",
00362                   prefix, x,y,z,a );
00363     }    
00364   };
00365   
00368   class Geom
00369   {
00370   public:
00371     Pose pose;
00372     Size size;
00373     
00374     void Print( const char* prefix )
00375     {
00376       printf( "%s geom pose: (%.2f,%.2f,%.2f) size: [%.2f,%.2f]\n",
00377                   prefix,
00378                   pose.x,
00379                   pose.y,
00380                   pose.a,
00381                   size.x,
00382                   size.y );
00383     }
00384      
00386      Geom() : pose(), size() {}
00387 
00389      Geom( const Pose& p, const Size& s ) : pose(p), size(s) {}
00390   };
00391   
00394   class Waypoint
00395   {
00396   public:
00397     Waypoint( stg_meters_t x, stg_meters_t y, stg_meters_t z, stg_radians_t a, Color color ) ;
00398     Waypoint( const Pose& pose, Color color ) ;
00399     Waypoint();
00400     void Draw();
00401     
00402     Pose pose;
00403     Color color;
00404   };
00405   
00407   class Bounds
00408   {
00409   public:
00411     double min;
00413     double max; 
00414     
00415     Bounds() : min(0), max(0) { /* empty*/  }
00416     Bounds( double min, double max ) : min(min), max(max) { /* empty*/  }
00417   };
00418     
00420   class stg_bounds3d_t
00421   {
00422   public:
00424     Bounds x; 
00426     Bounds y; 
00428     Bounds z; 
00429 
00430      stg_bounds3d_t() : x(), y(), z() {}
00431      stg_bounds3d_t( const Bounds& x, const Bounds& y, const Bounds& z) 
00432         : x(x), y(y), z(z) {}
00433   };
00434   
00436   typedef struct
00437   {
00438     Bounds range; 
00439     stg_radians_t angle; 
00440   } stg_fov_t;
00441   
00443   class stg_point_t
00444   {
00445   public:
00446     stg_meters_t x, y;
00447     stg_point_t( stg_meters_t x, stg_meters_t y ) : x(x), y(y){}     
00448     stg_point_t() : x(0.0), y(0.0){}
00449     
00450     bool operator+=( const stg_point_t& other ) 
00451     { return ((x += other.x) && (y += other.y) ); }  
00452   };
00453   
00455   class stg_point3_t
00456   {
00457   public:
00458     stg_meters_t x,y,z;
00459     stg_point3_t( stg_meters_t x, stg_meters_t y, stg_meters_t z ) 
00460       : x(x), y(y), z(z) {}  
00461   
00462     stg_point3_t() : x(0.0), y(0.0), z(0.0) {}
00463   };
00464   
00466   class stg_point_int_t
00467   {
00468   public:
00469     int x,y;
00470      stg_point_int_t( int x, int y ) : x(x), y(y){}  
00471      stg_point_int_t() : x(0), y(0){}
00472      
00474      bool operator<( const stg_point_int_t& other ) const
00475      { return ((x < other.x) || (y < other.y) ); }
00476 
00477      bool operator==( const stg_point_int_t& other ) const
00478      { return ((x == other.x) && (y == other.y) ); }
00479   };
00480   
00481   typedef std::vector<stg_point_int_t> PointIntVec;
00482 
00485   stg_point_t* stg_unit_square_points_create();
00486   
00487   typedef uint32_t stg_movemask_t;  
00488   const stg_movemask_t STG_MOVE_TRANS = (1 << 0); 
00489   const stg_movemask_t STG_MOVE_ROT   = (1 << 1); 
00490   const stg_movemask_t STG_MOVE_SCALE = (1 << 2); 
00491 
00492   const char MP_PREFIX[] =             "_mp_";
00493   const char MP_POSE[] =               "_mp_pose";
00494   const char MP_VELOCITY[] =           "_mp_velocity";
00495   const char MP_GEOM[] =               "_mp_geom";
00496   const char MP_COLOR[] =              "_mp_color";
00497   const char MP_WATTS[] =              "_mp_watts";
00498   const char MP_FIDUCIAL_RETURN[] =    "_mp_fiducial_return";
00499   const char MP_LASER_RETURN[] =       "_mp_laser_return";
00500   const char MP_OBSTACLE_RETURN[] =    "_mp_obstacle_return";
00501   const char MP_RANGER_RETURN[] =      "_mp_ranger_return";
00502   const char MP_GRIPPER_RETURN[] =     "_mp_gripper_return";
00503   const char MP_MASS[] =               "_mp_mass";
00504 
00506   typedef enum 
00507     {
00508       LaserTransparent=0, 
00509       LaserVisible, 
00510       LaserBright  
00511     } stg_laser_return_t;
00512   
00515   namespace Gl
00516   {
00517     void pose_shift( const Pose &pose );
00518     void pose_inverse_shift( const Pose &pose );
00519     void coord_shift( double x, double y, double z, double a  );
00520     void draw_grid( stg_bounds3d_t vol );
00522     void draw_string( float x, float y, float z, const char *string);
00523     void draw_string_multiline( float x, float y, float w, float h, 
00524                                 const char *string, Fl_Align align );
00525     void draw_speech_bubble( float x, float y, float z, const char* str );
00526     void draw_octagon( float w, float h, float m );
00527     void draw_octagon( float x, float y, float w, float h, float m );
00528     void draw_vector( double x, double y, double z );
00529     void draw_origin( double len );
00530     void draw_array( float x, float y, float w, float h, 
00531                      float* data, size_t len, size_t offset, 
00532                      float min, float max );
00533     void draw_array( float x, float y, float w, float h, 
00534                      float* data, size_t len, size_t offset );
00536     void draw_centered_rect( float x, float y, float dx, float dy );
00537   } // namespace Gl
00538   
00539   
00541   typedef Model* (*stg_creator_t)( World*, Model* );
00542   typedef std::pair<const char*, stg_creator_t> TypeEntry;
00543   
00544   void RegisterModels();
00545 
00546 
00547   class Flag
00548   {
00549   public:
00550     Color color;
00551     double size;
00552 
00553     Flag( Color color, double size );
00554     Flag* Nibble( double portion );
00555 
00558      void Draw(  GLUquadric* quadric );
00559   };
00560   
00562   class Visualizer {
00563   private:
00564      const std::string menu_name;
00565      const std::string worldfile_name;
00566      
00567   public:
00568      Visualizer( const std::string& menu_name, 
00569                      const std::string& worldfile_name ) 
00570         : menu_name( menu_name ),
00571           worldfile_name( worldfile_name )
00572      { }
00573      
00574      virtual ~Visualizer( void ) { }
00575      virtual void Visualize( Model* mod, Camera* cam ) = 0;
00576      
00577      const std::string& GetMenuName() { return menu_name; }
00578      const std::string& GetWorldfileName() { return worldfile_name; }
00579   };
00580 
00581 
00582   typedef int(*stg_model_callback_t)(Model* mod, void* user );
00583   typedef int(*stg_world_callback_t)(World* world, void* user );
00584   //typedef int(*stg_cell_callback_t)(Cell* cell, void* user );
00585   
00586   // return val, or minval if val < minval, or maxval if val > maxval
00587   double constrain( double val, double minval, double maxval );
00588     
00589   typedef struct 
00590   {
00591     int enabled;
00592     Pose pose;
00593     stg_meters_t size; 
00594     Color color;
00595     stg_msec_t period; 
00596     double duty_cycle; 
00597   } stg_blinkenlight_t;
00598 
00599   class TrailItem 
00600     {                                                                                           
00601     public:
00602     stg_usec_t time;
00603     Pose pose;
00604     Color color;
00605 
00606         TrailItem( stg_usec_t time, Pose pose, Color color ) 
00607             : time(time), pose(pose), color(color){}
00608   };
00609   
00611   typedef struct
00612   {
00613     Pose pose;
00614     Size size;
00615   } stg_rotrect_t; // rotated rectangle
00616 
00622   int stg_rotrects_from_image_file( const char* filename, 
00623                                                 stg_rotrect_t** rects,
00624                                                 unsigned int* rect_count,
00625                                                 unsigned int* widthp, 
00626                                                 unsigned int* heightp );
00627 
00628   
00631   typedef bool (*stg_ray_test_func_t)(Model* candidate, 
00632                                                   Model* finder, 
00633                                                   const void* arg );
00634 
00635   // STL container iterator macros
00636 #define VAR(V,init) __typeof(init) V=(init)
00637 #define FOR_EACH(I,C) for(VAR(I,(C).begin());I!=(C).end();I++)
00638 
00639   // Error macros - output goes to stderr
00640 #define PRINT_ERR(m) fprintf( stderr, "\033[41merr\033[0m: "m" (%s %s)\n", __FILE__, __FUNCTION__)
00641 #define PRINT_ERR1(m,a) fprintf( stderr, "\033[41merr\033[0m: "m" (%s %s)\n", a, __FILE__, __FUNCTION__)    
00642 #define PRINT_ERR2(m,a,b) fprintf( stderr, "\033[41merr\033[0m: "m" (%s %s)\n", a, b, __FILE__, __FUNCTION__) 
00643 #define PRINT_ERR3(m,a,b,c) fprintf( stderr, "\033[41merr\033[0m: "m" (%s %s)\n", a, b, c, __FILE__, __FUNCTION__)
00644 #define PRINT_ERR4(m,a,b,c,d) fprintf( stderr, "\033[41merr\033[0m: "m" (%s %s)\n", a, b, c, d, __FILE__, __FUNCTION__)
00645 #define PRINT_ERR5(m,a,b,c,d,e) fprintf( stderr, "\033[41merr\033[0m: "m" (%s %s)\n", a, b, c, d, e, __FILE__, __FUNCTION__)
00646 
00647   // Warning macros
00648 #define PRINT_WARN(m) printf( "\033[44mwarn\033[0m: "m" (%s %s)\n", __FILE__, __FUNCTION__)
00649 #define PRINT_WARN1(m,a) printf( "\033[44mwarn\033[0m: "m" (%s %s)\n", a, __FILE__, __FUNCTION__)    
00650 #define PRINT_WARN2(m,a,b) printf( "\033[44mwarn\033[0m: "m" (%s %s)\n", a, b, __FILE__, __FUNCTION__) 
00651 #define PRINT_WARN3(m,a,b,c) printf( "\033[44mwarn\033[0m: "m" (%s %s)\n", a, b, c, __FILE__, __FUNCTION__)
00652 #define PRINT_WARN4(m,a,b,c,d) printf( "\033[44mwarn\033[0m: "m" (%s %s)\n", a, b, c, d, __FILE__, __FUNCTION__)
00653 #define PRINT_WARN5(m,a,b,c,d,e) printf( "\033[44mwarn\033[0m: "m" (%s %s)\n", a, b, c, d, e, __FILE__, __FUNCTION__)
00654 
00655   // Message macros
00656 #ifdef DEBUG
00657 #define PRINT_MSG(m) printf( "Stage: "m" (%s %s)\n", __FILE__, __FUNCTION__)
00658 #define PRINT_MSG1(m,a) printf( "Stage: "m" (%s %s)\n", a, __FILE__, __FUNCTION__)    
00659 #define PRINT_MSG2(m,a,b) printf( "Stage: "m" (%s %s)\n", a, b, __FILE__, __FUNCTION__) 
00660 #define PRINT_MSG3(m,a,b,c) printf( "Stage: "m" (%s %s)\n", a, b, c, __FILE__, __FUNCTION__)
00661 #define PRINT_MSG4(m,a,b,c,d) printf( "Stage: "m" (%s %s)\n", a, b, c, d, __FILE__, __FUNCTION__)
00662 #define PRINT_MSG5(m,a,b,c,d,e) printf( "Stage: "m" (%s %s)\n", a, b, c, d, e,__FILE__, __FUNCTION__)
00663 #else
00664 #define PRINT_MSG(m) printf( "Stage: "m"\n" )
00665 #define PRINT_MSG1(m,a) printf( "Stage: "m"\n", a)
00666 #define PRINT_MSG2(m,a,b) printf( "Stage: "m"\n,", a, b )
00667 #define PRINT_MSG3(m,a,b,c) printf( "Stage: "m"\n", a, b, c )
00668 #define PRINT_MSG4(m,a,b,c,d) printf( "Stage: "m"\n", a, b, c, d )
00669 #define PRINT_MSG5(m,a,b,c,d,e) printf( "Stage: "m"\n", a, b, c, d, e )
00670 #endif
00671 
00672   // DEBUG macros
00673 #ifdef DEBUG
00674 #define PRINT_DEBUG(m) printf( "debug: "m" (%s %s)\n", __FILE__, __FUNCTION__)
00675 #define PRINT_DEBUG1(m,a) printf( "debug: "m" (%s %s)\n", a, __FILE__, __FUNCTION__)    
00676 #define PRINT_DEBUG2(m,a,b) printf( "debug: "m" (%s %s)\n", a, b, __FILE__, __FUNCTION__) 
00677 #define PRINT_DEBUG3(m,a,b,c) printf( "debug: "m" (%s %s)\n", a, b, c, __FILE__, __FUNCTION__)
00678 #define PRINT_DEBUG4(m,a,b,c,d) printf( "debug: "m" (%s %s)\n", a, b, c ,d, __FILE__, __FUNCTION__)
00679 #define PRINT_DEBUG5(m,a,b,c,d,e) printf( "debug: "m" (%s %s)\n", a, b, c ,d, e, __FILE__, __FUNCTION__)
00680 #else
00681 #define PRINT_DEBUG(m)
00682 #define PRINT_DEBUG1(m,a)
00683 #define PRINT_DEBUG2(m,a,b)
00684 #define PRINT_DEBUG3(m,a,b,c)
00685 #define PRINT_DEBUG4(m,a,b,c,d)
00686 #define PRINT_DEBUG5(m,a,b,c,d,e)
00687 #endif
00688 
00689   class Block;
00690   class Model;
00691 
00694   typedef int (*stg_model_callback_t)( Model* mod, void* user );
00695   
00696   // ANCESTOR CLASS
00698   class Ancestor
00699   {
00700     friend class Canvas; // allow Canvas access to our private members
00701      
00702   protected:
00703      ModelPtrVec children;
00704     bool debug;
00705     char* token;
00706      pthread_mutex_t access_mutex; 
00707 
00708      void Load( Worldfile* wf, int section );
00709      void Save( Worldfile* wf, int section );
00710      
00711   public:
00712     
00714     ModelPtrVec& GetChildren(){ return children;}
00715     
00717     void ForEachDescendant( stg_model_callback_t func, void* arg );
00718      
00720     unsigned int child_type_counts[MODEL_TYPE_COUNT];
00721      
00722     Ancestor();
00723     virtual ~Ancestor();
00724      
00725     virtual void AddChild( Model* mod );
00726     virtual void RemoveChild( Model* mod );
00727     virtual Pose GetGlobalPose();
00728      
00729     const char* Token()
00730     { return token; }
00731      
00732     void SetToken( const char* str )
00733     { token = strdup( str ); } // minor memory leak  
00734 
00735      void Lock(){ pthread_mutex_lock( &access_mutex ); }    
00736      void Unlock(){ pthread_mutex_unlock( &access_mutex ); }
00737   };
00738 
00741   class RaytraceResult
00742   {
00743   public:
00744     Pose pose; 
00745     stg_meters_t range; 
00746     Model* mod; 
00747     Color color; 
00748      
00749      RaytraceResult() : pose(), range(0), mod(NULL), color() {}
00750      RaytraceResult( const Pose& pose, 
00751                           stg_meters_t range ) 
00752         : pose(pose), range(range), mod(NULL), color() {}    
00753   };
00754 
00755   typedef RaytraceResult stg_raytrace_result_t;
00756     
00757   class Ray
00758   {
00759   public:
00760         Ray( const Model* mod, const Pose& origin, const stg_meters_t range, const stg_ray_test_func_t func, const void* arg, const bool ztest ) :
00761             mod(mod), origin(origin), range(range), func(func), arg(arg), ztest(ztest)
00762         {}
00763 
00764         Ray() : mod(NULL), origin(0,0,0,0), range(0), func(NULL), arg(NULL), ztest(true)
00765         {}
00766 
00767         const Model* mod;
00768         Pose origin;
00769         stg_meters_t range;
00770         stg_ray_test_func_t func;
00771         const void* arg;
00772         bool ztest;     
00773   };
00774         
00775   const uint32_t INTERVAL_LOG_LEN = 32;
00776 
00777   // defined in stage_internal.hh
00778   class Region;
00779   class SuperRegion;
00780   class BlockGroup;
00781   class PowerPack;
00782 
00783   class LogEntry
00784   {
00785      stg_usec_t timestamp;
00786      Model* mod;
00787      Pose pose;
00788      
00789   public:
00790      LogEntry( stg_usec_t timestamp, Model* mod );
00791      
00793      static std::vector<LogEntry> log;
00794      
00796      static size_t Count(){ return log.size(); }
00797      
00799      static void Clear(){ log.clear(); }
00800 
00802      static void Print();
00803   };
00804 
00806   class World : public Ancestor
00807   {
00808     friend class Block;
00809     friend class Model; // allow access to private members
00810     friend class ModelFiducial;
00811     friend class Canvas;
00812 
00813   public: 
00816      static std::vector<std::string> args;
00817 
00818   private:
00819     
00820     static std::set<World*> world_set; 
00821     static bool quit_all; 
00822     static void UpdateCb( World* world);
00823     static unsigned int next_id; 
00824      
00825      ModelPtrSet charge_list; 
00826     bool destroy;
00827     bool dirty; 
00828 
00829      // functor for comparing C strings in a hash_map
00830      struct eqstr 
00831      {
00832         bool operator()( const char* a, const char* b )
00833         { return( strcmp( a, b ) == 0 ); }
00834      };
00835      
00836         __gnu_cxx::hash_map<const char*, Model*, __gnu_cxx::hash<const char*>, eqstr > models_by_name; 
00837         
00838         std::map<int,Model*> models_by_wfentity;
00839 
00842      ModelPtrSet models_with_fiducials;
00843     
00844     double ppm; 
00845     bool quit; 
00846      
00848     stg_usec_t quit_time;
00849     stg_usec_t real_time_now; 
00850     stg_usec_t real_time_start; 
00851      bool show_clock; 
00852      unsigned int show_clock_interval; 
00853     //GMutex* thread_mutex; ///< protect the worker thread management stuff
00854     pthread_mutex_t thread_mutex; 
00855      unsigned int threads_working; 
00856     //GCond* threads_start_cond; ///< signalled to unblock worker threads
00857     //GCond* threads_done_cond; ///< signalled by last worker thread to unblock main thread
00858     pthread_cond_t threads_start_cond; 
00859     pthread_cond_t threads_done_cond; 
00860     int total_subs; 
00861      ModelPtrSet velocity_list; 
00862      unsigned int worker_threads; 
00863      
00864   protected:     
00865 
00866      std::list<std::pair<stg_world_callback_t,void*> > cb_list; 
00867     stg_bounds3d_t extent; 
00868     bool graphics;
00869     stg_usec_t interval_sim; 
00870      std::set<Option*> option_table; 
00871      std::list<PowerPack*> powerpack_list; 
00872      std::list<float*> ray_list;
00873     stg_usec_t sim_time; 
00874      std::map<stg_point_int_t,SuperRegion*> superregions;
00875     SuperRegion* sr_cached; 
00876      
00877     // todo - test performance of std::set
00878     std::vector<ModelPtrVec > update_lists;  
00879      
00880     long unsigned int updates; 
00881     Worldfile* wf; 
00882 
00883      void CallUpdateCallbacks(); 
00884 
00885   public:
00886      
00887     bool paused; 
00888     unsigned int steps; 
00889 
00890 
00891     virtual void Start(){ paused = false; };
00892     virtual void Stop(){ paused = true; };
00893     virtual void TogglePause(){ paused ? Start() : Stop(); };
00894 
00895      bool Paused(){ return( paused ); };
00896     
00897      PointIntVec rt_cells;
00898      PointIntVec rt_candidate_cells;
00899 
00900     static const int DEFAULT_PPM = 50;  // default resolution in pixels per meter
00901     static const stg_msec_t DEFAULT_INTERVAL_SIM = 100;  
00902 
00905      void AddUpdateCallback( stg_world_callback_t cb, void* user );
00906 
00909      int RemoveUpdateCallback( stg_world_callback_t cb, void* user );
00911      void Log( Model* mod );
00912 
00914     void NeedRedraw(){ dirty = true; };
00915         
00917         Model* ground;
00918         
00921     virtual std::string ClockString( void );
00922         
00923         Model* CreateModel( Model* parent, const char* typestr );    
00924     void LoadModel( Worldfile* wf, int entity );
00925     void LoadBlock( Worldfile* wf, int entity );
00926     void LoadBlockGroup( Worldfile* wf, int entity );
00927 
00928         virtual Model* RecentlySelectedModel(){ return NULL; }
00929         
00930     SuperRegion* AddSuperRegion( const stg_point_int_t& coord );
00931     SuperRegion* GetSuperRegion( const stg_point_int_t& coord );
00932     SuperRegion* GetSuperRegionCached( const stg_point_int_t& coord);
00933     SuperRegion* GetSuperRegionCached( int32_t x, int32_t y );
00934     void ExpireSuperRegion( SuperRegion* sr );
00935         
00936     inline Cell* GetCell( const stg_point_int_t& glob );
00937         
00940     void ForEachCellInLine( const stg_point_int_t& pt1,
00941                                                         const stg_point_int_t& pt2, 
00942                                                         CellPtrVec& cells );
00943         
00946     int32_t MetersToPixels( stg_meters_t x )
00947     { return (int32_t)floor(x * ppm); };
00948         
00949     stg_point_int_t MetersToPixels( const stg_point_t& pt )
00950     { return stg_point_int_t( MetersToPixels(pt.x), MetersToPixels(pt.y)); };
00951         
00952     // dummy implementations to be overloaded by GUI subclasses
00953     virtual void PushColor( Color col ) { /* do nothing */  };
00954     virtual void PushColor( double r, double g, double b, double a ) { /* do nothing */  };
00955     virtual void PopColor(){ /* do nothing */  };
00956         
00957     SuperRegion* CreateSuperRegion( stg_point_int_t origin );
00958     void DestroySuperRegion( SuperRegion* sr );
00959         
00961         stg_raytrace_result_t Raytrace( const Ray& ray );
00962 
00963     stg_raytrace_result_t Raytrace( const Pose& pose,            
00964                                                                         const stg_meters_t range,
00965                                                                         const stg_ray_test_func_t func,
00966                                                                         const Model* finder,
00967                                                                         const void* arg,
00968                                                                         const bool ztest );
00969         
00970     void Raytrace( const Pose &pose,             
00971                                      const stg_meters_t range,
00972                                      const stg_radians_t fov,
00973                                      const stg_ray_test_func_t func,
00974                                      const Model* finder,
00975                                      const void* arg,
00976                                      stg_raytrace_result_t* samples,
00977                                      const uint32_t sample_count,
00978                                      const bool ztest );
00979         
00980         
00982     void Extend( stg_point3_t pt );
00983   
00984     virtual void AddModel( Model* mod );
00985     virtual void RemoveModel( Model* mod );
00986         
00987     void AddPowerPack( PowerPack* pp );
00988     void RemovePowerPack( PowerPack* pp );
00989         
00990     void ClearRays();
00991   
00993     void RecordRay( double x1, double y1, double x2, double y2 );
00994         
00997     bool PastQuitTime();
00998         
00999     int UpdateListAdd( Model* mod );  
01000         void UpdateListRemove( Model* mod );
01001     
01002         void VelocityListAdd( Model* mod );
01003         void VelocityListRemove( Model* mod );
01004         
01005         void ChargeListAdd( Model* mod );
01006         void ChargeListRemove( Model* mod );
01007         
01008     static void* update_thread_entry( std::pair<World*,int>* info );
01009      
01010   public:
01012     static bool UpdateAll(); 
01013         
01014     World( const char* token = "MyWorld", 
01015                      stg_msec_t interval_sim = DEFAULT_INTERVAL_SIM,
01016                      double ppm = DEFAULT_PPM );
01017         
01018     virtual ~World();
01019   
01020     stg_usec_t SimTimeNow(void);
01021     stg_usec_t RealTimeNow(void);
01022     stg_usec_t RealTimeSinceStart(void);
01023      
01024     stg_usec_t GetSimInterval(){ return interval_sim; };
01025      
01026     Worldfile* GetWorldFile(){ return wf; };
01027      
01028     virtual bool IsGUI() { return false; }
01029      
01030     virtual void Load( const char* worldfile_path );
01031     virtual void UnLoad();
01032     virtual void Reload();
01033     virtual bool Save( const char* filename );
01034     virtual bool Update(void);
01035      
01036     bool TestQuit(){ return( quit || quit_all );  }
01037     void Quit(){ quit = true; }
01038     void QuitAll(){ quit_all = true; }
01039     void CancelQuit(){ quit = false; }
01040     void CancelQuitAll(){ quit_all = false; }
01041      
01042      void TryCharge( PowerPack* pp, const Pose& pose );
01043 
01046     double Resolution(){ return ppm; };
01047    
01050     Model* GetModel( const char* name );
01051   
01053     stg_bounds3d_t GetExtent(){ return extent; };
01054   
01056     long unsigned int GetUpdateCount() { return updates; }
01057 
01059      void RegisterOption( Option* opt );    
01060      
01062      void ShowClock( bool enable ){ show_clock = enable; };
01063 
01065     Model* GetGround() {return ground;};
01066     
01067   };
01068 
01069   class Block
01070   {
01071     friend class BlockGroup;
01072     friend class Model;
01073     friend class SuperRegion;
01074     friend class World;
01075     friend class Canvas;
01076   public:
01077   
01081     Block( Model* mod,  
01082               stg_point_t* pts, 
01083               size_t pt_count,
01084               stg_meters_t zmin,
01085               stg_meters_t zmax,
01086               Color color,
01087               bool inherit_color );
01088   
01090     Block(  Model* mod,  Worldfile* wf, int entity);
01091      
01092     ~Block();
01093      
01095     void Map();      
01096      
01098     void UnMap();    
01099          void DrawSolid();
01101     void Draw( Model* mod );  
01102 
01104     void DrawFootPrint(); 
01105 
01107      void Translate( double x, double y );   
01108 
01110      double CenterX();
01111 
01113      double CenterY();
01114 
01116      void SetCenterX( double y );
01117 
01119      void SetCenterY( double y );
01120 
01122      void SetCenter( double x, double y);    
01123 
01125      void SetZ( double min, double max );
01126 
01127     void RecordRendering( Cell* cell )
01128     { rendered_cells->push_back( cell ); }  
01129 
01130     stg_point_t* Points( unsigned int *count )
01131     { if( count ) *count = pt_count; return &pts[0]; };          
01132      
01133      std::vector<stg_point_t>& Points()
01134     { return pts; };             
01135      
01136     void AddToCellArray( CellPtrVec* blocks );
01137     void RemoveFromCellArray( CellPtrVec* blocks );
01138     void GenerateCandidateCells();  
01139 
01140     void AppendTouchingModels( ModelPtrSet& touchers );
01141      
01143     Model* TestCollision(); 
01144     void SwitchToTestedCells();  
01145     void Load( Worldfile* wf, int entity );  
01146     Model* GetModel(){ return mod; };  
01147     Color GetColor();       
01148         void Rasterize( uint8_t* data, 
01149                                         unsigned int width, unsigned int height,        
01150                                         stg_meters_t cellwidth, stg_meters_t cellheight );
01151         
01152   private:
01153     Model* mod; 
01154 
01155         std::vector<stg_point_t> mpts; 
01156     size_t pt_count; 
01157 
01158         std::vector<stg_point_t> pts; 
01159     //stg_point_t* pts; ///< points defining a polygon
01160      
01161     Size size;
01162      
01163     Bounds local_z; 
01164 
01165     Color color;
01166     bool inherit_color;
01167      
01168     void DrawTop();
01169     void DrawSides();
01170      
01172     Bounds global_z;
01173      
01174     bool mapped;
01175      
01178      CellPtrVec * rendered_cells;
01179 
01186     CellPtrVec * candidate_cells;
01187     
01188     PointIntVec gpts;
01189     
01192     stg_point_t BlockPointToModelMeters( const stg_point_t& bpt );
01193     
01195     //stg_point_t* GetPointsInModelCoords();
01196     
01198     void InvalidateModelPointCache();
01199   };
01200 
01201 
01202   class BlockGroup
01203   {
01204     friend class Model;
01205      friend class Block;
01206 
01207   private:
01208     int displaylist;
01209 
01210     void BuildDisplayList( Model* mod );
01211      
01212      BlockPtrVec blocks;
01213     Size size;
01214     stg_point3_t offset;
01215     stg_meters_t minx, maxx, miny, maxy;
01216 
01217   public:
01218     BlockGroup();
01219     ~BlockGroup();
01220      
01221     uint32_t GetCount(){ return blocks.size(); };
01222     Size GetSize(){ return size; };
01223     stg_point3_t GetOffset(){ return offset; };
01224 
01227     void CalcSize();
01228     void AppendBlock( Block* block );
01229     void CallDisplayList( Model* mod );
01230     void Clear() ; 
01232     void AppendTouchingModels( ModelPtrSet& touchers );
01233     
01236     Model* TestCollision();
01237  
01238     void SwitchToTestedCells();
01239      
01240     void Map();
01241     void UnMap();
01242      
01243     void DrawSolid( const Geom &geom); // draw the block in OpenGL as a solid single color
01244     void DrawFootPrint( const Geom &geom); // draw the
01245     // projection of the
01246     // block onto the z=0
01247     // plane
01248 
01249     void LoadBitmap( Model* mod, const char* bitmapfile, Worldfile *wf );
01250     void LoadBlock( Model* mod, Worldfile* wf, int entity );
01251      
01252      void Rasterize( uint8_t* data, 
01253                           unsigned int width, unsigned int height,
01254                           stg_meters_t cellwidth, stg_meters_t cellheight );
01255      
01256      void InvalidateModelPointCache()
01257      {
01258         for( BlockPtrVec::iterator it( blocks.begin() );
01259               it != blocks.end();
01260               ++it )
01261           (*it)->InvalidateModelPointCache();
01262      }
01263 
01264   };
01265 
01266 
01267   typedef int ctrlinit_t( Model* mod );
01268   //typedef void ctrlupdate_t( Model* mod );
01269   
01270   // BLOCKS
01271 
01272   class Camera 
01273   {
01274   protected:
01275     float _pitch; //left-right (about y)
01276     float _yaw; //up-down (about x)
01277     float _x, _y, _z;
01278     
01279   public:
01280     Camera() : _pitch( 0 ), _yaw( 0 ), _x( 0 ), _y( 0 ), _z( 0 ) { }
01281     virtual ~Camera() { }
01282 
01283     virtual void Draw( void ) const = 0;
01284     virtual void SetProjection( void ) const = 0;
01285 
01286      float yaw( void ) const { return _yaw; }
01287      float pitch( void ) const { return _pitch; }
01288      
01289      float x( void ) const { return _x; }
01290      float y( void ) const { return _y; }
01291      float z( void ) const { return _z; }
01292      
01293     virtual void reset() = 0;
01294     virtual void Load( Worldfile* wf, int sec ) = 0;
01295 
01296     //TODO data should be passed in somehow else. (at least min/max stuff)
01297     //virtual void SetProjection( float pixels_width, float pixels_height, float y_min, float y_max ) const = 0;
01298   };
01299 
01300   class PerspectiveCamera : public Camera
01301   {
01302   private:
01303     float _z_near;
01304     float _z_far;
01305     float _vert_fov;
01306     float _horiz_fov;
01307     float _aspect;
01308 
01309   public:
01310     PerspectiveCamera( void );
01311 
01312     virtual void Draw( void ) const;
01313     virtual void SetProjection( void ) const;
01314     //void SetProjection( float aspect ) const;
01315     void update( void );
01316 
01317     void strafe( float amount );
01318     void forward( float amount );
01319     
01320     void setPose( float x, float y, float z ) { _x = x; _y = y; _z = z; }
01321     void addPose( float x, float y, float z ) { _x += x; _y += y; _z += z; if( _z < 0.1 ) _z = 0.1; }
01322     void move( float x, float y, float z );
01323     void setFov( float horiz_fov, float vert_fov ) { _horiz_fov = horiz_fov; _vert_fov = vert_fov; }
01325     void setAspect( float aspect ) { 
01326       //std::cout << "aspect: " << aspect << " vert: " << _vert_fov << " => " << aspect * _vert_fov << std::endl;
01327       //_vert_fov = aspect / _horiz_fov;
01328       _aspect = aspect;
01329     }
01330     void setYaw( float yaw ) { _yaw = yaw; }
01331     float horizFov( void ) const { return _horiz_fov; }
01332     float vertFov( void ) const { return _vert_fov; }
01333     void addYaw( float yaw ) { _yaw += yaw; }
01334     void setPitch( float pitch ) { _pitch = pitch; }
01335     void addPitch( float pitch ) { _pitch += pitch; if( _pitch < 0 ) _pitch = 0; else if( _pitch > 180 ) _pitch = 180; }
01336     
01337     float realDistance( float z_buf_val ) const {
01338       //formula found at http://www.cs.unc.edu/~hoff/techrep/openglz.html
01339       //Z = Zn*Zf / (Zf - z*(Zf-Zn))
01340       return _z_near * _z_far / ( _z_far - z_buf_val * ( _z_far - _z_near ) );
01341     }
01342     void scroll( float dy ) { _z += dy; }
01343     float nearClip( void ) const { return _z_near; }
01344     float farClip( void ) const { return _z_far; }
01345     void setClip( float near, float far ) { _z_far = far; _z_near = near; }
01346     
01347     void reset() { setPitch( 70 ); setYaw( 0 ); }
01348     
01349     void Load( Worldfile* wf, int sec );
01350     void Save( Worldfile* wf, int sec );
01351   };
01352   
01353   class OrthoCamera : public Camera
01354   {
01355   private:
01356     float _scale;
01357     float _pixels_width;
01358     float _pixels_height;
01359     float _y_min;
01360     float _y_max;
01361   
01362   public:
01363     OrthoCamera( void ) : _scale( 15 ) { }
01364     virtual void Draw() const;
01365     virtual void SetProjection( float pixels_width, float pixels_height, float y_min, float y_max );
01366     virtual void SetProjection( void ) const;
01367   
01368     void move( float x, float y );
01369      void setYaw( float yaw ) { _yaw = yaw; }
01370      void setPitch( float pitch ) { _pitch = pitch; }
01371      void addYaw( float yaw ) { _yaw += yaw;    }
01372      void addPitch( float pitch ) {
01373       _pitch += pitch;
01374       if( _pitch > 90 )
01375           _pitch = 90;
01376       else if( _pitch < 0 )
01377           _pitch = 0;
01378     }
01379   
01380      void setScale( float scale ) { _scale = scale; }
01381      void setPose( float x, float y) { _x = x; _y = y; }
01382   
01383     void scale( float scale, float shift_x = 0, float h = 0, float shift_y = 0, float w = 0 );  
01384      void reset( void ) { _pitch = _yaw = 0; }
01385   
01386      float scale() const { return _scale; }
01387   
01388     void Load( Worldfile* wf, int sec );
01389     void Save( Worldfile* wf, int sec );
01390   };
01391 
01392 
01396   class WorldGui : public World, public Fl_Window 
01397   {
01398     friend class Canvas;
01399     friend class ModelCamera;
01400     friend class Model;
01401     friend class Option;
01402 
01403   private:
01404 
01405     Canvas* canvas;
01406     std::vector<Option*> drawOptions;
01407     FileManager* fileMan; 
01408     stg_usec_t interval_log[INTERVAL_LOG_LEN];
01409     stg_usec_t interval_real;   
01410     Fl_Menu_Bar* mbar;
01411     OptionsDlg* oDlg;
01412     bool pause_time;
01413     stg_usec_t real_time_of_last_update;
01414     
01415     // static callback functions
01416     static void windowCb( Fl_Widget* w, void* p );  
01417     static void fileLoadCb( Fl_Widget* w, void* p );
01418     static void fileSaveCb( Fl_Widget* w, void* p );
01419     static void fileSaveAsCb( Fl_Widget* w, void* p );
01420     static void fileExitCb( Fl_Widget* w, void* p );
01421     static void viewOptionsCb( OptionsDlg* oDlg, WorldGui* worldGui  );
01422     static void optionsDlgCb( OptionsDlg* oDlg, WorldGui* worldGui  );
01423     static void helpAboutCb( Fl_Widget* w, void* p );
01424     static void pauseCb( Fl_Widget* w, WorldGui* worldGui );
01425     static void onceCb( Fl_Widget* w, WorldGui* worldGui );
01426     static void fasterCb( Fl_Widget* w, WorldGui* worldGui );
01427     static void slowerCb( Fl_Widget* w, WorldGui* worldGui );
01428     static void realtimeCb( Fl_Widget* w, WorldGui* worldGui );
01429     static void fasttimeCb( Fl_Widget* w, WorldGui* worldGui );
01430     static void resetViewCb( Fl_Widget* w, WorldGui* worldGui );
01431     static void moreHelptCb( Fl_Widget* w, WorldGui* wg );
01432     
01433     // GUI functions
01434     bool saveAsDialog();
01435     bool closeWindowQuery();
01436     
01437     virtual void AddModel( Model* mod );
01438     
01439   protected:
01440     
01441     virtual void PushColor( Color col );
01442     virtual void PushColor( double r, double g, double b, double a );
01443     virtual void PopColor();
01444     
01445     void DrawTree( bool leaves );
01446     void DrawFloor();
01447     
01448   public:
01449     
01450     WorldGui(int W,int H,const char*L=0);
01451     ~WorldGui();
01452     
01453     virtual std::string ClockString();
01454     virtual bool Update();  
01455     virtual void Load( const char* filename );
01456     virtual void UnLoad();
01457     virtual bool Save( const char* filename );  
01458     virtual bool IsGUI() { return true; }   
01459     virtual Model* RecentlySelectedModel();
01460 
01461     virtual void Start();
01462     virtual void Stop();
01463      
01464     void DrawBoundingBoxTree();
01465     
01466     Canvas* GetCanvas( void ) { return canvas; }
01467 
01469     void Show(); 
01470 
01472     std::string EnergyString( void );
01473     
01476     void SetRealTimeInterval( stg_usec_t usec )
01477     { interval_real = usec; }
01478 
01479     virtual void RemoveChild( Model* mod );  
01480   };
01481 
01482 
01483   class StripPlotVis : public Visualizer
01484   {
01485   private:
01486      
01487      Model* mod;
01488      float* data;
01489      size_t len;
01490      size_t count;
01491      unsigned int index;
01492      float x,y,w,h,min,max;
01493      Color fgcolor, bgcolor;
01494      
01495   public:
01496      StripPlotVis( float x, float y, float w, float h, 
01497                         size_t len, 
01498                         Color fgcolor, Color bgcolor,
01499                         const char* name, const char* wfname );
01500      virtual ~StripPlotVis();
01501      virtual void Visualize( Model* mod, Camera* cam );     
01502      void AppendValue( float value );
01503   };
01504 
01505 
01506   class PowerPack
01507   {
01508      friend class WorldGui;
01509      friend class Canvas;
01510      
01511   protected:
01512      
01513      class DissipationVis : public Visualizer
01514      {
01515      private:
01516         unsigned int columns, rows;
01517         stg_meters_t width, height;
01518         stg_joules_t* cells;
01519         stg_joules_t peak_value;
01520         double cellsize;
01521         
01522         static stg_joules_t global_peak_value; 
01523 
01524      public:
01525         DissipationVis( stg_meters_t width, 
01526                              stg_meters_t height, 
01527                              stg_meters_t cellsize );
01528 
01529         virtual ~DissipationVis();
01530         virtual void Visualize( Model* mod, Camera* cam );      
01531         
01532         void Accumulate( stg_meters_t x, stg_meters_t y, stg_joules_t amount );
01533      } event_vis;
01534 
01535      StripPlotVis output_vis;
01536      StripPlotVis stored_vis;
01537 
01539      Model* mod;
01540     
01542      stg_joules_t stored;
01543      
01545      stg_joules_t capacity;
01546      
01548      bool charging;
01549      
01551      stg_joules_t dissipated;
01552 
01553      static stg_joules_t global_stored;
01554      static stg_joules_t global_capacity;
01555      static stg_joules_t global_dissipated;  
01556      static stg_joules_t global_input;
01557 
01558   public:
01559      PowerPack( Model* mod );
01560      ~PowerPack();
01561      
01563      void Visualize( Camera* cam ) const;
01564 
01567      void Print( char* prefix ) const;
01568      
01570      stg_joules_t RemainingCapacity() const;
01571      
01573      void Add( stg_joules_t j );
01574         
01576      void Subtract( stg_joules_t j );
01577         
01579      void TransferTo( PowerPack* dest, stg_joules_t amount );    
01580 
01581      double ProportionRemaining() const
01582      { return( stored / capacity ); }
01583 
01584      void Print( const char* prefix ) const
01585      { printf( "%s PowerPack %.2f/%.2f J\n", prefix, stored, capacity ); }      
01586      
01587      stg_joules_t GetStored() const;
01588      stg_joules_t GetCapacity() const;
01589      stg_joules_t GetDissipated() const;
01590      void SetCapacity( stg_joules_t j );
01591      void SetStored( stg_joules_t j );  
01592 
01594      bool GetCharging() const { return charging; }
01595      
01596      void ChargeStart(){ charging = true; }
01597      void ChargeStop(){ charging = false; }
01598 
01600      void Dissipate( stg_joules_t j );
01601      
01603      void Dissipate( stg_joules_t j, const Pose& p );
01604 };
01605 
01606   class Visibility
01607   {
01608   public:
01609     bool blob_return;
01610     int fiducial_key;
01611     int fiducial_return;
01612     bool gripper_return;
01613     stg_laser_return_t laser_return;
01614     bool obstacle_return;
01615     bool ranger_return;
01616     bool gravity_return;
01617     bool sticky_return;
01618     
01619     Visibility();
01620     void Load( Worldfile* wf, int wf_entity );
01621   };
01622 
01623   /* Hooks for attaching special callback functions (not used as
01624      variables - we just need unique addresses for them.) */  
01625   class CallbackHooks
01626   {
01627   public:
01628     int flag_incr;
01629     int flag_decr;
01630     int load;
01631     int save;
01632     int shutdown;
01633     int startup;
01634     int update;
01635     int update_done;
01636   };
01637   
01639   class GuiState
01640   {
01641   public:
01642     bool grid;
01643     unsigned int mask;
01644     bool nose;
01645     bool outline;
01646     
01647     GuiState();
01648     void Load( Worldfile* wf, int wf_entity );
01649   };
01650   
01652   class Model : public Ancestor
01653   {
01654     friend class Ancestor;
01655     friend class World;
01656     friend class WorldGui;
01657     friend class Canvas;
01658     friend class Block;
01659     friend class Region;
01660     friend class BlockGroup;
01661     friend class PowerPack;
01662     friend class Ray;
01663     
01664   public:
01667     static Model* Create( World* world, Model* parent )
01668     { return new  Model( world, parent ); }
01669 
01670   private:
01672      static uint32_t count;
01673      static std::map<stg_id_t,Model*> modelsbyid;
01674      std::vector<Option*> drawOptions;
01675      const std::vector<Option*>& getOptions() const { return drawOptions; }
01676      
01677   protected:
01678      pthread_mutex_t access_mutex;
01679      BlockGroup blockgroup;
01681      int blocks_dl;
01682 
01686      int boundary;
01687         
01690     public:
01691         class stg_cb_t
01692         {
01693         public:
01694             stg_model_callback_t callback;
01695             void* arg;
01696             
01697             stg_cb_t( stg_model_callback_t cb, void* arg ) 
01698                 : callback(cb), arg(arg) {}
01699             
01700             stg_cb_t( stg_world_callback_t cb, void* arg ) 
01701                 : callback(NULL), arg(arg) {}
01702             
01703             stg_cb_t() : callback(NULL), arg(NULL) {}
01704             
01706             bool operator<( const stg_cb_t& other ) const
01707             { return ((void*)(callback)) < ((void*)(other.callback)); }
01708             
01710             bool operator==( const stg_cb_t& other ) const
01711             { return( callback == other.callback);  }           
01712         };
01713         
01714     protected:
01718         std::map<void*, std::set<stg_cb_t> > callbacks;
01719         
01721         Color color;
01722         double friction;
01723         
01727      bool data_fresh;
01728      stg_bool_t disabled; 
01729      std::list<Visualizer*> cv_list;
01730      std::list<Flag*> flag_list;
01731      Geom geom;
01732      Pose global_pose;
01733      bool gpose_dirty; 
01734 
01735      GuiState gui;
01736   
01737      bool has_default_block;
01738   
01739      /* hooks for attaching special callback functions (not used as
01740          variables - we just need unique addresses for them.) */  
01741      CallbackHooks hooks;
01742   
01744      uint32_t id;   
01745      ctrlinit_t* initfunc;
01746      stg_usec_t interval; 
01747      stg_usec_t last_update; 
01748      bool log_state; 
01749      stg_meters_t map_resolution;
01750      stg_kg_t mass;
01751     //bool on_update_list;
01752      bool on_velocity_list;
01753 
01755      Model* parent; 
01756 
01759      Pose pose;
01760 
01762      PowerPack* power_pack;
01763 
01766      std::list<PowerPack*> pps_charging;
01767 
01771      //GData* props;
01772      std::map<const char*,const void*> props;
01773 
01775     class RasterVis : public Visualizer
01776     {
01777     private:
01778       uint8_t* data;
01779       unsigned int width, height;
01780       stg_meters_t cellwidth, cellheight;
01781       std::vector<stg_point_t> pts;
01782       
01783     public:
01784       RasterVis();
01785       virtual ~RasterVis( void ){}
01786       virtual void Visualize( Model* mod, Camera* cam );
01787       
01788       void SetData( uint8_t* data, 
01789                     unsigned int width, 
01790                     unsigned int height,
01791                     stg_meters_t cellwidth,
01792                     stg_meters_t cellheight );
01793       
01794       int subs;     //< the number of subscriptions to this model
01795       int used;     //< the number of connections to this model
01796       
01797       void AddPoint( stg_meters_t x, stg_meters_t y );
01798       void ClearPts();
01799       
01800     } rastervis;
01801         
01802         bool rebuild_displaylist; 
01803         char* say_string;   
01804         
01805         stg_bool_t stall;
01808         int subs;    
01809         bool thread_safe;
01810         
01812         std::list<TrailItem> trail;
01813 
01817         unsigned int trail_length;
01818 
01820         long unsigned int trail_interval;
01821 
01822         stg_model_type_t type;  
01825     int update_list_num; 
01826     bool used;   
01827     Velocity velocity;
01828     stg_watts_t watts;
01829     
01832     stg_watts_t watts_give;
01833     
01836     stg_watts_t watts_take;
01837     
01838     Worldfile* wf;
01839     int wf_entity;
01840     World* world; // pointer to the world in which this model exists
01841     WorldGui* world_gui; //pointer to the GUI world - NULL if running in non-gui mode
01842 
01843   public:
01844     
01845     stg_model_type_t GetModelType(){return type;}    
01846     std::string GetSayString(){return std::string(say_string);}
01847     Visibility vis;
01848     stg_usec_t GetSimInterval(){ return world->interval_sim; }
01849     
01852     void Rasterize( uint8_t* data, 
01853                     unsigned int width, unsigned int height,
01854                     stg_meters_t cellwidth, stg_meters_t cellheight );
01855     
01856 //  void Lock()
01857 //  { 
01858 //    if( access_mutex == NULL )
01859 //      access_mutex = g_mutex_new();
01860       
01861 //    assert( access_mutex );
01862 //    g_mutex_lock( access_mutex );
01863 //  }
01864     
01865 //  void Unlock()
01866 //  { 
01867 //    assert( access_mutex );
01868 //    g_mutex_unlock( access_mutex );
01869 //  }   
01870 
01871   private: 
01874      explicit Model(const Model& original);
01875 
01878      Model& operator=(const Model& original);
01879 
01880   protected:
01881 
01883      void RegisterOption( Option* opt );
01884 
01885      void AppendTouchingModels( ModelPtrSet& touchers );
01886 
01890      Model* TestCollision();
01891 
01894     Model* TestCollisionTree();
01895   
01896      void CommitTestedPose();
01897 
01898      void Map();
01899      void UnMap();
01900 
01901      void MapWithChildren();
01902      void UnMapWithChildren();
01903   
01904     // Find the root model, and map/unmap the whole tree.
01905     void MapFromRoot();
01906     void UnMapFromRoot();
01907 
01910      stg_raytrace_result_t Raytrace( const Pose &pose,
01911                                                 const stg_meters_t range, 
01912                                                 const stg_ray_test_func_t func,
01913                                                 const void* arg,
01914                                                 const bool ztest = true );
01915   
01918      void Raytrace( const Pose &pose,
01919                          const stg_meters_t range, 
01920                          const stg_radians_t fov, 
01921                          const stg_ray_test_func_t func,
01922                          const void* arg,
01923                          stg_raytrace_result_t* samples,
01924                          const uint32_t sample_count,
01925                          const bool ztest = true  );
01926   
01927      stg_raytrace_result_t Raytrace( const stg_radians_t bearing,            
01928                                                 const stg_meters_t range,
01929                                                 const stg_ray_test_func_t func,
01930                                                 const void* arg,
01931                                                 const bool ztest = true );
01932   
01933      void Raytrace( const stg_radians_t bearing,             
01934                          const stg_meters_t range,
01935                          const stg_radians_t fov,
01936                          const stg_ray_test_func_t func,
01937                          const void* arg,
01938                          stg_raytrace_result_t* samples,
01939                          const uint32_t sample_count,
01940                          const bool ztest = true );
01941   
01942 
01946      void GPoseDirtyTree();
01947 
01948      virtual void Startup();
01949      virtual void Shutdown();
01950      virtual void Update();
01951      virtual void UpdatePose();
01952      virtual void UpdateCharge();
01953 
01954      void StartUpdating();
01955      void StopUpdating();
01956 
01957      Model* ConditionalMove( const Pose& newpose );
01958 
01959      stg_meters_t ModelHeight() const;
01960 
01961      bool UpdateDue( void );
01962      void UpdateIfDue();
01963      void CallUpdateCallbacks( void );
01964 
01965      void DrawBlocksTree();
01966      virtual void DrawBlocks();
01967      void DrawBoundingBox();
01968      void DrawBoundingBoxTree();
01969      virtual void DrawStatus( Camera* cam );
01970      void DrawStatusTree( Camera* cam );
01971   
01972      void DrawOriginTree();
01973      void DrawOrigin();
01974   
01975      void PushLocalCoords();
01976      void PopCoords();
01977   
01979     void DrawImage( uint32_t texture_id, Camera* cam, float alpha, double width=1.0, double height=1.0 );
01980     
01981     virtual void DrawPicker();
01982     virtual void DataVisualize( Camera* cam );  
01983     virtual void DrawSelected(void);
01984     
01985     void DrawTrailFootprint();
01986     void DrawTrailBlocks();
01987     void DrawTrailArrows();
01988     void DrawGrid();
01989      // void DrawBlinkenlights();
01990     void DataVisualizeTree( Camera* cam );
01991     void DrawFlagList();
01992     void DrawPose( Pose pose );
01993     void LoadDataBaseEntries( Worldfile* wf, int entity );
01994     
01995   public:
01996      virtual void PushColor( Color col ){ world->PushColor( col ); }    
01997      virtual void PushColor( double r, double g, double b, double a ){ world->PushColor( r,g,b,a ); }   
01998      virtual void PopColor()    { world->PopColor(); }
01999     
02000     PowerPack* FindPowerPack() const;
02001     
02002      //void RecordRenderPoint( GSList** head, GSList* link, 
02003      //                 unsigned int* c1, unsigned int* c2 );
02004 
02005     void PlaceInFreeSpace( stg_meters_t xmin, stg_meters_t xmax, 
02006                            stg_meters_t ymin, stg_meters_t ymax );
02007     
02009     std::string PoseString()
02010     { return pose.String(); }
02011     
02013     static Model* LookupId( uint32_t id )
02014     { return modelsbyid[id]; }
02015     
02017     Model( World* world, 
02018            Model* parent, 
02019            stg_model_type_t type = MODEL_TYPE_PLAIN );
02020     
02022     virtual ~Model();
02023     
02024     void Say( const char* str );
02025      
02027      void AddVisualizer( Visualizer* custom_visual, bool on_by_default );
02028 
02030      void RemoveVisualizer( Visualizer* custom_visual );
02031 
02032      void BecomeParentOf( Model* child );
02033 
02034      void Load( Worldfile* wf, int wf_entity )
02035      {
02038         SetWorldfile( wf, wf_entity );
02039         Load(); // call virtual load
02040      }
02041     
02043      void SetWorldfile( Worldfile* wf, int wf_entity )
02044      { this->wf = wf; this->wf_entity = wf_entity; }
02045     
02047      virtual void Load();
02048     
02050      virtual void Save();
02051     
02053      void Init();   
02054      void InitRecursive();
02055 
02056      void AddFlag(  Flag* flag );
02057      void RemoveFlag( Flag* flag );
02058     
02059      void PushFlag( Flag* flag );
02060      Flag* PopFlag();
02061     
02062      int GetFlagCount() const { return flag_list.size(); }
02063   
02064 //   /** Add a pointer to a blinkenlight to the model. */
02065 //   void AddBlinkenlight( stg_blinkenlight_t* b )
02066 //   { g_ptr_array_add( this->blinkenlights, b ); }
02067   
02068 //   /** Clear all blinkenlights from the model. Does not destroy the
02069 //        blinkenlight objects. */
02070 //   void ClearBlinkenlights()
02071 //   {  g_ptr_array_set_size( this->blinkenlights, 0 ); }
02072   
02077      void Disable(){ disabled = true; };
02078 
02081      void Enable(){ disabled = false; };
02082   
02085      void LoadControllerModule( char* lib );
02086     
02089      void NeedRedraw();
02090     
02093      void LoadBlock( Worldfile* wf, int entity );
02094 
02097      Block* AddBlockRect( stg_meters_t x, stg_meters_t y, 
02098                                  stg_meters_t dx, stg_meters_t dy, 
02099                                  stg_meters_t dz );
02100     
02102      void ClearBlocks();
02103   
02106      Model* Parent() const { return this->parent; }
02107 
02108      Model* GetModel( const char* name ) const;
02109      //int GuiMask(){ return this->gui_mask; };
02110 
02112      World* GetWorld() const { return this->world; }
02113   
02115      Model* Root(){ return(  parent ? parent->Root() : this ); }
02116   
02117      bool IsAntecedent( const Model* testmod ) const;
02118     
02120      bool IsDescendent( const Model* testmod ) const;
02121     
02123      bool IsRelated( const Model* testmod ) const;
02124 
02126      Pose GetGlobalPose() const;
02127     
02129      Velocity GetGlobalVelocity()  const;
02130     
02131      /* set the velocity of a model in the global coordinate system */
02132      void SetGlobalVelocity( const Velocity& gvel );
02133     
02135      void Subscribe();
02136     
02138      void Unsubscribe();
02139     
02141      void SetGlobalPose(  const Pose& gpose );
02142     
02144      void SetVelocity(  const Velocity& vel );
02145     
02147      void SetPose(  const Pose& pose );
02148     
02150      void AddToPose(  const Pose& pose );
02151     
02153      void AddToPose(  double dx, double dy, double dz, double da );
02154     
02156      void SetGeom(  const Geom& src );
02157   
02160      void SetFiducialReturn(  int fid );
02161   
02163      int GetFiducialReturn()  const { return vis.fiducial_return; }
02164   
02167      void SetFiducialKey(  int key );
02168     
02169      Color GetColor() const { return color; }
02170      
02172      uint32_t GetId()  const { return id; }
02173      
02175     stg_kg_t GetTotalMass();
02176     
02178      int SetParent( Model* newparent);
02179     
02182      Geom GetGeom() const { return geom; }
02183     
02186      Pose GetPose() const { return pose; }
02187     
02190      Velocity GetVelocity() const { return velocity; }
02191     
02192      // guess what these do?
02193      void SetColor( Color col );
02194      void SetMass( stg_kg_t mass );
02195      void SetStall( stg_bool_t stall );
02196     void SetGravityReturn( int val );
02197      void SetGripperReturn( int val );
02198     void SetStickyReturn( int val );
02199      void SetLaserReturn( stg_laser_return_t val );
02200      void SetObstacleReturn( int val );
02201      void SetBlobReturn( int val );
02202      void SetRangerReturn( int val );
02203      void SetBoundary( int val );
02204      void SetGuiNose( int val );
02205      void SetGuiMask( int val );
02206      void SetGuiGrid( int val );
02207      void SetGuiOutline( int val );
02208      void SetWatts( stg_watts_t watts );
02209         void SetMapResolution( stg_meters_t res );
02210         void SetFriction( double friction );
02211     
02212      bool DataIsFresh() const { return this->data_fresh; }
02213     
02214      /* attach callback functions to data members. The function gets
02215          called when the member is changed using SetX() accessor method */
02216         
02217         void AddCallback( void* address, 
02218                                             stg_model_callback_t cb, 
02219                                             void* user );
02220         
02221         int RemoveCallback( void* member,
02222                                                 stg_model_callback_t callback );
02223         
02224         int CallCallbacks(  void* address );
02225         
02226      /* wrappers for the generic callback add & remove functions that hide
02227          some implementation detail */
02228     
02229      void AddStartupCallback( stg_model_callback_t cb, void* user )
02230      { AddCallback( &hooks.startup, cb, user ); };
02231     
02232      void RemoveStartupCallback( stg_model_callback_t cb )
02233      { RemoveCallback( &hooks.startup, cb ); };
02234     
02235      void AddShutdownCallback( stg_model_callback_t cb, void* user )
02236      { AddCallback( &hooks.shutdown, cb, user ); };
02237     
02238      void RemoveShutdownCallback( stg_model_callback_t cb )
02239      { RemoveCallback( &hooks.shutdown, cb ); }
02240     
02241      void AddLoadCallback( stg_model_callback_t cb, void* user )
02242      { AddCallback( &hooks.load, cb, user ); }
02243     
02244      void RemoveLoadCallback( stg_model_callback_t cb )
02245      { RemoveCallback( &hooks.load, cb ); }
02246     
02247      void AddSaveCallback( stg_model_callback_t cb, void* user )
02248      { AddCallback( &hooks.save, cb, user ); }
02249     
02250      void RemoveSaveCallback( stg_model_callback_t cb )
02251      { RemoveCallback( &hooks.save, cb ); }
02252   
02253      void AddUpdateCallback( stg_model_callback_t cb, void* user )
02254      {  AddCallback( &hooks.update, cb, user ); }
02255     
02256      void RemoveUpdateCallback( stg_model_callback_t cb )
02257      {  RemoveCallback( &hooks.update, cb ); }
02258 
02259      void AddFlagIncrCallback( stg_model_callback_t cb, void* user )
02260      {  AddCallback( &hooks.flag_incr, cb, user ); }
02261     
02262      void RemoveFlagIncrCallback( stg_model_callback_t cb )
02263      {  RemoveCallback( &hooks.flag_incr, cb ); }
02264 
02265      void AddFlagDecrCallback( stg_model_callback_t cb, void* user )
02266      {  AddCallback( &hooks.flag_decr, cb, user ); }
02267     
02268      void RemoveFlagDecrCallback( stg_model_callback_t cb )
02269      {  RemoveCallback( &hooks.flag_decr, cb ); }
02270      
02273      const void* GetProperty( const char* key ) const;
02274      bool GetPropertyFloat( const char* key, float* f, float defaultval ) const;     
02275      bool GetPropertyInt( const char* key, int* i, int defaultval ) const;   
02276      bool GetPropertyStr( const char* key, char** c, char* defaultval ) const;
02277 
02308      int SetProperty( const char* key, const void* data );
02309      void SetPropertyInt( const char* key, int i );
02310      void SetPropertyFloat( const char* key, float f );
02311      void SetPropertyStr( const char* key, const char* str );
02312      
02313      void UnsetProperty( const char* key );
02314         
02315      virtual void Print( char* prefix ) const;
02316      virtual const char* PrintWithPose() const;
02317     
02320      Pose GlobalToLocal( const Pose& pose ) const;
02321      
02324     Pose LocalToGlobal( const Pose& pose ) const
02325     {  
02326       return( ( GetGlobalPose() + geom.pose ) + pose );
02327     }
02328         
02329 //   /** Return the 3d point in world coordinates of a 3d point
02330 //        specified in the model's local coordinate system */
02331 //   stg_point3_t LocalToGlobal( const stg_point3_t local ) const;
02334      stg_point_t LocalToGlobal( const stg_point_t& pt) const;
02335 
02338      Model* GetUnsubscribedModelOfType( const stg_model_type_t type ) const;
02339     
02342      Model* GetUnusedModelOfType( const stg_model_type_t type );
02343   
02344 
02347      bool Stalled() const { return this->stall; }
02348 
02349     
02350     static std::map< std::string, stg_creator_t> name_map;
02351     static std::map< stg_model_type_t, std::string> type_map;
02352   };
02353 
02354 
02355   // BLOBFINDER MODEL --------------------------------------------------------
02356 
02357 
02359   class ModelBlobfinder : public Model
02360   {
02361     public:
02363         class Blob
02364         {
02365         public:
02366             Color color;
02367             uint32_t left, top, right, bottom;
02368             stg_meters_t range;
02369         };
02370 
02371      class Vis : public Visualizer 
02372      {
02373      private:
02374         //static Option showArea;
02375      public:
02376         Vis( World* world );
02377         virtual ~Vis( void ){}
02378         virtual void Visualize( Model* mod, Camera* cam );
02379      } vis;
02380 
02381   private:
02382         std::vector<Blob> blobs;
02383         std::vector<Color> colors;
02384 
02385      // predicate for ray tracing
02386      static bool BlockMatcher( Block* testblock, Model* finder );
02387      //static Option showBlobData;
02388 
02389   public:
02390      stg_radians_t fov;
02391      stg_radians_t pan;
02392      stg_meters_t range;
02393      unsigned int scan_height;
02394      unsigned int scan_width;
02395 
02396      // constructor
02397      ModelBlobfinder( World* world,
02398                             Model* parent );
02399      // destructor
02400      ~ModelBlobfinder();
02401     
02404     static Model* Create( World* world, Model* parent )
02405     { return new  ModelBlobfinder( world, parent ); }
02406 
02407      virtual void Startup();
02408      virtual void Shutdown();
02409      virtual void Update();
02410      virtual void Load();
02411         
02412      Blob* GetBlobs( unsigned int* count )
02413      { 
02414         if( count ) *count = blobs.size();
02415         return &blobs[0];
02416      }
02417 
02419      void AddColor( Color col );
02420 
02422      void RemoveColor( Color col );
02423 
02426      void RemoveAllColors();
02427   };
02428 
02429 
02430 
02431 
02432   // LASER MODEL --------------------------------------------------------
02433   
02435   class ModelLaser : public Model
02436   {
02437     public:
02439         class Sample
02440         {
02441         public:
02442             stg_meters_t range; 
02443             double reflectance; 
02444         };
02445         
02447         class Config
02448         {
02449         public:
02450             uint32_t sample_count; 
02451             uint32_t resolution; 
02452             Bounds range_bounds; 
02453             stg_radians_t fov; 
02454             stg_usec_t interval; 
02455         };
02456         
02457   private:
02458      
02459      class Vis : public Visualizer 
02460      {
02461      private:
02462         static Option showArea;
02463         static Option showStrikes;
02464         static Option showFov;
02465         static Option showBeams;
02466 
02467      public:
02468         Vis( World* world );        virtual ~Vis( void ){}
02469         virtual void Visualize( Model* mod, Camera* cam );
02470      } vis;
02471         
02472         unsigned int sample_count;
02473         std::vector<Sample> samples;
02474 
02475         stg_meters_t range_max;
02476         stg_radians_t fov;
02477         uint32_t resolution;
02478     
02479      // set up data buffers after the config changes
02480      void SampleConfig();
02481 
02482   public:
02483      // constructor
02484      ModelLaser( World* world,
02485                      Model* parent ); 
02486   
02487      // destructor
02488     ~ModelLaser();
02489     
02492     static Model* Create( World* world, Model* parent )
02493     { return new  ModelLaser( world, parent ); }
02494 
02495      virtual void Startup();
02496      virtual void Shutdown();
02497      virtual void Update();
02498      virtual void Load();
02499      virtual void Print( char* prefix );
02500   
02502      Sample* GetSamples( uint32_t* count );
02503      
02505      const std::vector<Sample>& GetSamples();
02506      
02508      Config GetConfig( );
02509      
02511      void SetConfig( Config& cfg );  
02512   };
02513   
02514 
02515 // LOAD CELL MODEL --------------------------------------------------------
02516 
02518 class ModelLoadCell : public Model
02519 {
02520 private:
02521 public:
02522   // constructor
02523   ModelLoadCell( World* world,
02524                       Model* parent );
02525 
02526   // destructor
02527   ~ModelLoadCell();
02528   
02531   static Model* Create( World* world, Model* parent )
02532   { return new  ModelLoadCell( world, parent ); }
02533 
02534   float GetVoltage();
02535 };
02536 
02537 
02538 // Light indicator model
02539 class ModelLightIndicator : public Model
02540 {
02541 public:
02542     ModelLightIndicator(World* world, Model* parent);
02543     ~ModelLightIndicator();
02544   
02547   static Model* Create( World* world, Model* parent )
02548   { return new  ModelLightIndicator( world, parent ); }
02549   
02550     void SetState(bool isOn);
02551 
02552 protected:
02553     virtual void DrawBlocks();
02554 
02555 private:
02556     bool m_IsOn;
02557 };
02558 
02559 // \todo  GRIPPER MODEL --------------------------------------------------------
02560 
02561 
02562   class ModelGripper : public Model
02563   {
02564   public:
02565 
02566      enum paddle_state_t {
02567         PADDLE_OPEN = 0, // default state
02568         PADDLE_CLOSED, 
02569         PADDLE_OPENING,
02570         PADDLE_CLOSING,
02571      };
02572      
02573      enum lift_state_t {
02574         LIFT_DOWN = 0, // default state
02575         LIFT_UP, 
02576         LIFT_UPPING, // verbed these to match the paddle state
02577         LIFT_DOWNING, 
02578      };
02579      
02580      enum cmd_t {
02581         CMD_NOOP = 0, // default state
02582         CMD_OPEN, 
02583         CMD_CLOSE,
02584         CMD_UP, 
02585         CMD_DOWN    
02586      };
02587      
02588      
02591      struct config_t
02592      {
02593         Size paddle_size; 
02594         paddle_state_t paddles;
02595         lift_state_t lift;      
02596         double paddle_position; 
02597         double lift_position; 
02598         Model* gripped;
02599         bool paddles_stalled; // true iff some solid object stopped the paddles closing or opening
02600         double close_limit; 
02601         bool autosnatch; 
02602         double break_beam_inset[2]; 
02603       Model* beam[2]; 
02604       Model* contact[2]; 
02605      };
02606      
02607   private:
02608      virtual void Update();
02609      virtual void DataVisualize( Camera* cam );
02610      
02611      void FixBlocks();
02612      void PositionPaddles();
02613      void UpdateBreakBeams();
02614      void UpdateContacts();
02615 
02616      config_t cfg;
02617      cmd_t cmd;
02618      
02619      Block* paddle_left;
02620      Block* paddle_right;
02621 
02622      static Option showData;
02623 
02624   public:    
02625      static const Size size;
02626 
02627      // constructor
02628      ModelGripper( World* world,
02629                          Model* parent );
02630      // destructor
02631      virtual ~ModelGripper();
02632   
02635     static Model* Create( World* world, Model* parent )
02636     { return new  ModelGripper( world, parent ); }
02637 
02638      virtual void Load();
02639      virtual void Save();
02640 
02642      void SetConfig( config_t & newcfg ){ this->cfg = cfg; FixBlocks(); }
02643      
02645      config_t GetConfig(){ return cfg; };
02646      
02648      void SetCommand( cmd_t cmd ) { this->cmd = cmd; }
02650      void CommandClose() { SetCommand( CMD_CLOSE ); }
02652      void CommandOpen() { SetCommand( CMD_OPEN ); }
02654      void CommandUp() { SetCommand( CMD_UP ); }
02656      void CommandDown() { SetCommand( CMD_DOWN ); }
02657   };
02658 
02659 
02660   // \todo BUMPER MODEL --------------------------------------------------------
02661 
02662   //   typedef struct
02663   //   {
02664   //     Pose pose;
02665   //     stg_meters_t length;
02666   //   } stg_bumper_config_t;
02667 
02668   //   typedef struct
02669   //   {
02670   //     Model* hit;
02671   //     stg_point_t hit_point;
02672   //   } stg_bumper_sample_t;
02673 
02674 
02675   // FIDUCIAL MODEL --------------------------------------------------------
02676 
02678   class ModelFiducial : public Model
02679   {
02680     public:  
02682         class Fiducial
02683         {
02684         public:
02685             stg_meters_t range; 
02686             stg_radians_t bearing; 
02687             Pose geom; 
02688             Pose pose; 
02689             Model* mod; 
02690             int id; 
02691         };
02692 
02693 private:
02694      // if neighbor is visible, add him to the fiducial scan
02695      void AddModelIfVisible( Model* him );
02696 
02697      virtual void Update();
02698      virtual void DataVisualize( Camera* cam );
02699 
02700      static Option showFiducialData;
02701         
02702         std::vector<Fiducial> fiducials;
02703         
02704   public:       
02705         ModelFiducial( World* world, Model* parent );
02706         virtual ~ModelFiducial();
02707     
02710     static Model* Create( World* world, Model* parent )
02711     { return new  ModelFiducial( world, parent ); }
02712     
02713         virtual void Load();
02714         void Shutdown( void );
02715 
02716         stg_meters_t max_range_anon;
02717         stg_meters_t max_range_id; 
02718         stg_meters_t min_range; 
02719         stg_radians_t fov; 
02720         stg_radians_t heading; 
02721         int key; 
02722         
02723         
02725         std::vector<Fiducial>& GetFiducials() { return fiducials; }
02726         
02728          Fiducial* GetFiducials( unsigned int* count )
02729         {
02730             if( count ) *count = fiducials.size();
02731             return &fiducials[0];
02732         }
02733   };
02734 
02735 
02736   // RANGER MODEL --------------------------------------------------------
02737 
02739   class ModelRanger : public Model
02740   {
02741     public:
02742         class Sensor
02743         {
02744         public:
02745             Pose pose;
02746             Size size;
02747             Bounds bounds_range;
02748             stg_radians_t fov;
02749             int ray_count;
02750             stg_meters_t range;
02751         };
02752 
02753   protected:
02754 
02755      virtual void Startup();
02756      virtual void Shutdown();
02757      virtual void Update();
02758      virtual void DataVisualize( Camera* cam );
02759     
02760   public:
02761      ModelRanger( World* world, Model* parent );
02762     virtual ~ModelRanger();
02763     
02766     static Model* Create( World* world, Model* parent )
02767     { return new  ModelRanger( world, parent ); }
02768     
02769      virtual void Load();
02770      virtual void Print( char* prefix );
02771      
02772      std::vector<Sensor> sensors;
02773     
02774   private:
02775     static Option showRangerData;
02776     static Option showRangerTransducers;        
02777   };
02778     
02779   // BLINKENLIGHT MODEL ----------------------------------------------------
02780   class ModelBlinkenlight : public Model
02781   {
02782   private:
02783      double dutycycle;
02784      bool enabled;
02785      stg_msec_t period;
02786      bool on;
02787 
02788      static Option showBlinkenData;
02789   public:
02790      ModelBlinkenlight( World* world,
02791                               Model* parent );
02792 
02793      ~ModelBlinkenlight();
02794     
02797     static Model* Create( World* world, Model* parent )
02798     { return new  ModelBlinkenlight( world, parent ); }
02799 
02800      virtual void Load();
02801      virtual void Update();
02802      virtual void DataVisualize( Camera* cam );
02803   };
02804 
02805     
02806 // CAMERA MODEL ----------------------------------------------------
02807 
02809 class ModelCamera : public Model
02810 {
02811 public:
02812   typedef struct 
02813   {
02814      // GL_V3F
02815      GLfloat x, y, z;
02816   } ColoredVertex;
02817   
02818   private:
02819      Canvas* _canvas;
02820 
02821      GLfloat* _frame_data;  //opengl read buffer
02822      GLubyte* _frame_color_data;  //opengl read buffer
02823 
02824      bool _valid_vertexbuf_cache;
02825      ColoredVertex* _vertexbuf_cache; //cached unit vectors with appropriate rotations (these must be scalled by z-buffer length)
02826     
02827      int _width;         //width of buffer
02828      int _height;        //height of buffer
02829      static const int _depth = 4;
02830     
02831      int _camera_quads_size;
02832      GLfloat* _camera_quads;
02833      GLubyte* _camera_colors;
02834     
02835      static Option showCameraData;
02836     
02837      PerspectiveCamera _camera;
02838      float _yaw_offset; //position camera is mounted at
02839      float _pitch_offset;
02840         
02842      bool GetFrame();
02843     
02844   public:
02845      ModelCamera( World* world,
02846                       Model* parent ); 
02847 
02848      ~ModelCamera();
02849   
02852   static Model* Create( World* world, Model* parent )
02853   { return new  ModelCamera( world, parent ); }
02854 
02855      virtual void Load();
02856     
02858      virtual void Update();
02859     
02861      //virtual void Draw( uint32_t flags, Canvas* canvas );
02862     
02864      virtual void DataVisualize( Camera* cam );
02865     
02867       int getWidth( void ) const { return _width; }
02868     
02870       int getHeight( void ) const { return _height; }
02871     
02873       const PerspectiveCamera& getCamera( void ) const { return _camera; }
02874     
02876       const GLfloat* FrameDepth() const { return _frame_data; }
02877     
02879       const GLubyte* FrameColor() const { return _frame_color_data; }
02880     
02882       void setPitch( float pitch ) { _pitch_offset = pitch; _valid_vertexbuf_cache = false; }
02883     
02885       void setYaw( float yaw ) { _yaw_offset = yaw; _valid_vertexbuf_cache = false; }
02886   };
02887 
02888   // POSITION MODEL --------------------------------------------------------
02889 
02891   class ModelPosition : public Model
02892   {
02893      friend class Canvas;
02894 
02895   public:
02897      typedef enum
02898         { STG_POSITION_CONTROL_VELOCITY, 
02899           STG_POSITION_CONTROL_POSITION 
02900         } ControlMode;
02901      
02903      typedef enum
02904         { STG_POSITION_LOCALIZATION_GPS, 
02905           STG_POSITION_LOCALIZATION_ODOM 
02906         } LocalizationMode;
02907      
02909      typedef enum
02910         { STG_POSITION_DRIVE_DIFFERENTIAL, 
02911           STG_POSITION_DRIVE_OMNI, 
02912           STG_POSITION_DRIVE_CAR 
02913         } DriveMode;
02914      
02915   private:
02916      Pose goal;
02917      ControlMode control_mode;
02918      DriveMode drive_mode;
02919      LocalizationMode localization_mode; 
02920      Velocity integration_error; 
02921 
02922      Waypoint* waypoints;
02923      uint32_t waypoint_count;    
02924 
02925   public:
02926      // constructor
02927      ModelPosition( World* world,
02928                          Model* parent );
02929      // destructor
02930      ~ModelPosition();
02931 
02934     static Model* Create( World* world, Model* parent )
02935     { return new  ModelPosition( world, parent ); }
02936 
02937      virtual void Startup();
02938      virtual void Shutdown();
02939      virtual void Update();
02940      virtual void Load();
02941      
02943      Waypoint* SetWaypoints( Waypoint* wps, uint32_t count );
02944     
02945      class WaypointVis : public Visualizer
02946      {
02947      public:
02948         WaypointVis();
02949         virtual ~WaypointVis( void ){}
02950         virtual void Visualize( Model* mod, Camera* cam );
02951      };
02952      
02953      WaypointVis wpvis;
02954      
02955      class PoseVis : public Visualizer
02956      {
02957      public:
02958         PoseVis();
02959         virtual ~PoseVis( void ){}
02960         virtual void Visualize( Model* mod, Camera* cam );
02961      };
02962      
02963      PoseVis posevis;
02964 
02966      void SetOdom( Pose odom );
02967 
02970      void SetSpeed( double x, double y, double a );
02971      void SetXSpeed( double x );
02972      void SetYSpeed( double y );
02973      void SetZSpeed( double z );
02974      void SetTurnSpeed( double a );
02975      void SetSpeed( Velocity vel );
02977      void Stop();
02978 
02981      void GoTo( double x, double y, double a );
02982      void GoTo( Pose pose );
02983 
02984      // localization state
02985      Pose est_pose; 
02986      Pose est_pose_error; 
02987      Pose est_origin; 
02988   };
02989 
02990 
02991 // ACTUATOR MODEL --------------------------------------------------------
02992 
02994 class ModelActuator : public Model
02995 {
02996 public:
02998   typedef enum
02999      { STG_ACTUATOR_CONTROL_VELOCITY,
03000         STG_ACTUATOR_CONTROL_POSITION
03001      } ControlMode;
03002   
03004   typedef enum
03005      { STG_ACTUATOR_TYPE_LINEAR,
03006         STG_ACTUATOR_TYPE_ROTATIONAL
03007      } ActuatorType;
03008   
03009 private:
03010   double goal; //< the current velocity or pose to reach, depending on the value of control_mode
03011   double pos;
03012   double max_speed;
03013   double min_position;
03014   double max_position;
03015   ControlMode control_mode;
03016   ActuatorType actuator_type;
03017   stg_point3_t axis;
03018   
03019   Pose InitialPose;
03020 public:  
03021   // constructor
03022   ModelActuator( World* world,
03023                       Model* parent );
03024   // destructor
03025   ~ModelActuator();
03026   
03029     static Model* Create( World* world, Model* parent )
03030   { return new  ModelActuator( world, parent ); }
03031 
03032   virtual void Startup();
03033   virtual void Shutdown();
03034   virtual void Update();
03035   virtual void Load();
03036   
03039   void SetSpeed( double speed );
03040   
03041   double GetSpeed() const {return goal;}
03042   
03045   void GoTo( double pose );
03046   
03047   double GetPosition() const {return pos;};
03048   double GetMaxPosition() const {return max_position;};
03049   double GetMinPosition() const {return min_position;};
03050   
03051 };
03052 
03053 
03054 }; // end namespace stg
03055 
03056 #endif

Generated on Wed Jul 22 11:51:03 2009 for Stage by  doxygen 1.5.9